Have soong_zip add extended attribute to META-INF in jar mode

Bug: 64536066
Test: soong_zip --jar -o /tmp/out.zip -C . -l files.list && \
      zipdetails /tmp/out.zip | less \
      # and check that the first entry contains the \
      # "CAFE" extra attribute as shown below:

0000001E Filename              'META-INF/'
00000027 Extra ID #0001        CAFE 'Java Executable'
00000029   Length              0000

Change-Id: I12c4078591f2ce2afc1af5b9db20393b26601bca
diff --git a/cmd/soong_zip/soong_zip.go b/cmd/soong_zip/soong_zip.go
index 7405728..bb2a70f 100644
--- a/cmd/soong_zip/soong_zip.go
+++ b/cmd/soong_zip/soong_zip.go
@@ -219,6 +219,10 @@
 		usage()
 	}
 
+	if *emulateJar {
+		*directories = true
+	}
+
 	w := &zipWriter{
 		time:        time.Date(2009, 1, 1, 0, 0, 0, 0, time.UTC),
 		createdDirs: make(map[string]bool),
@@ -669,6 +673,19 @@
 	close(compressChan)
 }
 
+func (z *zipWriter) addExtraField(zipHeader *zip.FileHeader, fieldHeader [2]byte, data []byte) {
+	// add the field header in little-endian order
+	zipHeader.Extra = append(zipHeader.Extra, fieldHeader[1], fieldHeader[0])
+
+	// specify the length of the data (in little-endian order)
+	dataLength := len(data)
+	lengthBytes := []byte{byte(dataLength % 256), byte(dataLength / 256)}
+	zipHeader.Extra = append(zipHeader.Extra, lengthBytes...)
+
+	// add the contents of the extra field
+	zipHeader.Extra = append(zipHeader.Extra, data...)
+}
+
 func (z *zipWriter) writeDirectory(dir string) error {
 	// clean the input
 	cleanDir := filepath.Clean(dir)
@@ -692,6 +709,11 @@
 		dirHeader.SetMode(0700 | os.ModeDir)
 		dirHeader.SetModTime(z.time)
 
+		if *emulateJar && dir == "META-INF/" {
+			// Jar files have a 0-length extra field with header "CAFE"
+			z.addExtraField(dirHeader, [2]byte{0xca, 0xfe}, []byte{})
+		}
+
 		ze := make(chan *zipEntry, 1)
 		ze <- &zipEntry{
 			fh: dirHeader,