jar.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // Copyright 2017 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jar
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "os"
  20. "strings"
  21. "text/scanner"
  22. "time"
  23. "unicode"
  24. "android/soong/third_party/zip"
  25. )
  26. const (
  27. MetaDir = "META-INF/"
  28. ManifestFile = MetaDir + "MANIFEST.MF"
  29. ModuleInfoClass = "module-info.class"
  30. )
  31. var DefaultTime = time.Date(2008, 1, 1, 0, 0, 0, 0, time.UTC)
  32. var MetaDirExtra = [2]byte{0xca, 0xfe}
  33. // EntryNamesLess tells whether <filepathA> should precede <filepathB> in
  34. // the order of files with a .jar
  35. func EntryNamesLess(filepathA string, filepathB string) (less bool) {
  36. diff := index(filepathA) - index(filepathB)
  37. if diff == 0 {
  38. return filepathA < filepathB
  39. }
  40. return diff < 0
  41. }
  42. // Treats trailing * as a prefix match
  43. func patternMatch(pattern, name string) bool {
  44. if strings.HasSuffix(pattern, "*") {
  45. return strings.HasPrefix(name, strings.TrimSuffix(pattern, "*"))
  46. } else {
  47. return name == pattern
  48. }
  49. }
  50. var jarOrder = []string{
  51. MetaDir,
  52. ManifestFile,
  53. MetaDir + "*",
  54. "*",
  55. }
  56. func index(name string) int {
  57. for i, pattern := range jarOrder {
  58. if patternMatch(pattern, name) {
  59. return i
  60. }
  61. }
  62. panic(fmt.Errorf("file %q did not match any pattern", name))
  63. }
  64. func MetaDirFileHeader() *zip.FileHeader {
  65. dirHeader := &zip.FileHeader{
  66. Name: MetaDir,
  67. Extra: []byte{MetaDirExtra[1], MetaDirExtra[0], 0, 0},
  68. }
  69. dirHeader.SetMode(0755 | os.ModeDir)
  70. dirHeader.SetModTime(DefaultTime)
  71. return dirHeader
  72. }
  73. // Create a manifest zip header and contents using the provided contents if any.
  74. func ManifestFileContents(contents []byte) (*zip.FileHeader, []byte, error) {
  75. b, err := manifestContents(contents)
  76. if err != nil {
  77. return nil, nil, err
  78. }
  79. fh := &zip.FileHeader{
  80. Name: ManifestFile,
  81. Method: zip.Store,
  82. UncompressedSize64: uint64(len(b)),
  83. }
  84. fh.SetMode(0644)
  85. fh.SetModTime(DefaultTime)
  86. return fh, b, nil
  87. }
  88. // Create manifest contents, using the provided contents if any.
  89. func manifestContents(contents []byte) ([]byte, error) {
  90. manifestMarker := []byte("Manifest-Version:")
  91. header := append(manifestMarker, []byte(" 1.0\nCreated-By: soong_zip\n")...)
  92. var finalBytes []byte
  93. if !bytes.Contains(contents, manifestMarker) {
  94. finalBytes = append(append(header, contents...), byte('\n'))
  95. } else {
  96. finalBytes = contents
  97. }
  98. return finalBytes, nil
  99. }
  100. var javaIgnorableIdentifier = &unicode.RangeTable{
  101. R16: []unicode.Range16{
  102. {0x00, 0x08, 1},
  103. {0x0e, 0x1b, 1},
  104. {0x7f, 0x9f, 1},
  105. },
  106. LatinOffset: 3,
  107. }
  108. func javaIdentRune(ch rune, i int) bool {
  109. if unicode.IsLetter(ch) {
  110. return true
  111. }
  112. if unicode.IsDigit(ch) && i > 0 {
  113. return true
  114. }
  115. if unicode.In(ch,
  116. unicode.Nl, // letter number
  117. unicode.Sc, // currency symbol
  118. unicode.Pc, // connecting punctuation
  119. ) {
  120. return true
  121. }
  122. if unicode.In(ch,
  123. unicode.Cf, // format
  124. unicode.Mc, // combining mark
  125. unicode.Mn, // non-spacing mark
  126. javaIgnorableIdentifier,
  127. ) && i > 0 {
  128. return true
  129. }
  130. return false
  131. }
  132. // JavaPackage parses the package out of a java source file by looking for the package statement, or the first valid
  133. // non-package statement, in which case it returns an empty string for the package.
  134. func JavaPackage(r io.Reader, src string) (string, error) {
  135. var s scanner.Scanner
  136. var sErr error
  137. s.Init(r)
  138. s.Filename = src
  139. s.Error = func(s *scanner.Scanner, msg string) {
  140. sErr = fmt.Errorf("error parsing %q: %s", src, msg)
  141. }
  142. s.IsIdentRune = javaIdentRune
  143. tok := s.Scan()
  144. if sErr != nil {
  145. return "", sErr
  146. }
  147. if tok == scanner.Ident {
  148. switch s.TokenText() {
  149. case "package":
  150. // Nothing
  151. case "import":
  152. // File has no package statement, first keyword is an import
  153. return "", nil
  154. case "class", "enum", "interface":
  155. // File has no package statement, first keyword is a type declaration
  156. return "", nil
  157. case "public", "protected", "private", "abstract", "static", "final", "strictfp":
  158. // File has no package statement, first keyword is a modifier
  159. return "", nil
  160. case "module", "open":
  161. // File has no package statement, first keyword is a module declaration
  162. return "", nil
  163. default:
  164. return "", fmt.Errorf(`expected first token of java file to be "package", got %q`, s.TokenText())
  165. }
  166. } else if tok == '@' {
  167. // File has no package statement, first token is an annotation
  168. return "", nil
  169. } else if tok == scanner.EOF {
  170. // File no package statement, it has no non-whitespace non-comment tokens
  171. return "", nil
  172. } else {
  173. return "", fmt.Errorf(`expected first token of java file to be "package", got %q`, s.TokenText())
  174. }
  175. var pkg string
  176. for {
  177. tok = s.Scan()
  178. if sErr != nil {
  179. return "", sErr
  180. }
  181. if tok != scanner.Ident {
  182. return "", fmt.Errorf(`expected "package <package>;", got "package %s%s"`, pkg, s.TokenText())
  183. }
  184. pkg += s.TokenText()
  185. tok = s.Scan()
  186. if sErr != nil {
  187. return "", sErr
  188. }
  189. if tok == ';' {
  190. return pkg, nil
  191. } else if tok == '.' {
  192. pkg += "."
  193. } else {
  194. return "", fmt.Errorf(`expected "package <package>;", got "package %s%s"`, pkg, s.TokenText())
  195. }
  196. }
  197. }