sdk_repo_host.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // Copyright (C) 2021 The Android Open Source Project
  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 android_sdk
  15. import (
  16. "fmt"
  17. "io"
  18. "path/filepath"
  19. "strings"
  20. "github.com/google/blueprint"
  21. "github.com/google/blueprint/pathtools"
  22. "github.com/google/blueprint/proptools"
  23. "android/soong/android"
  24. "android/soong/cc/config"
  25. )
  26. var pctx = android.NewPackageContext("android/soong/android_sdk")
  27. func init() {
  28. registerBuildComponents(android.InitRegistrationContext)
  29. }
  30. func registerBuildComponents(ctx android.RegistrationContext) {
  31. ctx.RegisterModuleType("android_sdk_repo_host", SdkRepoHostFactory)
  32. }
  33. type sdkRepoHost struct {
  34. android.ModuleBase
  35. android.PackagingBase
  36. properties sdkRepoHostProperties
  37. outputBaseName string
  38. outputFile android.OptionalPath
  39. }
  40. type remapProperties struct {
  41. From string
  42. To string
  43. }
  44. type sdkRepoHostProperties struct {
  45. // The top level directory to use for the SDK repo.
  46. Base_dir *string
  47. // List of src:dst mappings to rename files from `deps`.
  48. Deps_remap []remapProperties `android:"arch_variant"`
  49. // List of zip files to merge into the SDK repo.
  50. Merge_zips []string `android:"arch_variant,path"`
  51. // List of sources to include into the SDK repo. These are usually raw files, filegroups,
  52. // or genrules, as most built modules should be referenced via `deps`.
  53. Srcs []string `android:"arch_variant,path"`
  54. // List of files to strip. This should be a list of files, not modules. This happens after
  55. // `deps_remap` and `merge_zips` are applied, but before the `base_dir` is added.
  56. Strip_files []string `android:"arch_variant"`
  57. }
  58. // android_sdk_repo_host defines an Android SDK repo containing host tools.
  59. //
  60. // This implementation is trying to be a faithful reproduction of how these sdk-repos were produced
  61. // in the Make system, which may explain some of the oddities (like `strip_files` not being
  62. // automatic)
  63. func SdkRepoHostFactory() android.Module {
  64. return newSdkRepoHostModule()
  65. }
  66. func newSdkRepoHostModule() *sdkRepoHost {
  67. s := &sdkRepoHost{}
  68. s.AddProperties(&s.properties)
  69. android.InitPackageModule(s)
  70. android.InitAndroidMultiTargetsArchModule(s, android.HostSupported, android.MultilibCommon)
  71. return s
  72. }
  73. type dependencyTag struct {
  74. blueprint.BaseDependencyTag
  75. android.PackagingItemAlwaysDepTag
  76. }
  77. // TODO(b/201696252): Evaluate whether licenses should be propagated through this dependency.
  78. func (d dependencyTag) PropagateLicenses() bool {
  79. return false
  80. }
  81. var depTag = dependencyTag{}
  82. func (s *sdkRepoHost) DepsMutator(ctx android.BottomUpMutatorContext) {
  83. s.AddDeps(ctx, depTag)
  84. }
  85. func (s *sdkRepoHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  86. dir := android.PathForModuleOut(ctx, "zip")
  87. outputZipFile := dir.Join(ctx, "output.zip")
  88. builder := android.NewRuleBuilder(pctx, ctx).
  89. Sbox(dir, android.PathForModuleOut(ctx, "out.sbox.textproto")).
  90. SandboxInputs()
  91. // Get files from modules listed in `deps`
  92. packageSpecs := s.GatherPackagingSpecs(ctx)
  93. // Handle `deps_remap` renames
  94. err := remapPackageSpecs(packageSpecs, s.properties.Deps_remap)
  95. if err != nil {
  96. ctx.PropertyErrorf("deps_remap", "%s", err.Error())
  97. }
  98. s.CopySpecsToDir(ctx, builder, packageSpecs, dir)
  99. noticeFile := android.PathForModuleOut(ctx, "NOTICES.txt")
  100. android.BuildNoticeTextOutputFromLicenseMetadata(
  101. ctx, noticeFile, "", "",
  102. []string{
  103. android.PathForModuleInstall(ctx, "sdk-repo").String() + "/",
  104. outputZipFile.String(),
  105. })
  106. builder.Command().Text("cp").
  107. Input(noticeFile).
  108. Text(filepath.Join(dir.String(), "NOTICE.txt"))
  109. // Handle `merge_zips` by extracting their contents into our tmpdir
  110. for _, zip := range android.PathsForModuleSrc(ctx, s.properties.Merge_zips) {
  111. builder.Command().
  112. Text("unzip").
  113. Flag("-DD").
  114. Flag("-q").
  115. FlagWithArg("-d ", dir.String()).
  116. Input(zip)
  117. }
  118. // Copy files from `srcs` into our tmpdir
  119. for _, src := range android.PathsForModuleSrc(ctx, s.properties.Srcs) {
  120. builder.Command().
  121. Text("cp").Input(src).Flag(dir.Join(ctx, src.Rel()).String())
  122. }
  123. // Handle `strip_files` by calling the necessary strip commands
  124. //
  125. // Note: this stripping logic was copied over from the old Make implementation
  126. // It's not using the same flags as the regular stripping support, nor does it
  127. // support the array of per-module stripping options. It would be nice if we
  128. // pulled the stripped versions from the CC modules, but that doesn't exist
  129. // for host tools today. (And not all the things we strip are CC modules today)
  130. if ctx.Darwin() {
  131. macStrip := config.MacStripPath(ctx)
  132. for _, strip := range s.properties.Strip_files {
  133. builder.Command().
  134. Text(macStrip).Flag("-x").
  135. Flag(dir.Join(ctx, strip).String())
  136. }
  137. } else {
  138. llvmStrip := config.ClangPath(ctx, "bin/llvm-strip")
  139. llvmLib := config.ClangPath(ctx, "lib/x86_64-unknown-linux-gnu/libc++.so.1")
  140. for _, strip := range s.properties.Strip_files {
  141. cmd := builder.Command().Tool(llvmStrip).ImplicitTool(llvmLib)
  142. if !ctx.Windows() {
  143. cmd.Flag("-x")
  144. }
  145. cmd.Flag(dir.Join(ctx, strip).String())
  146. }
  147. }
  148. // Fix up the line endings of all text files. This also removes executable permissions.
  149. builder.Command().
  150. Text("find").
  151. Flag(dir.String()).
  152. Flag("-name '*.aidl' -o -name '*.css' -o -name '*.html' -o -name '*.java'").
  153. Flag("-o -name '*.js' -o -name '*.prop' -o -name '*.template'").
  154. Flag("-o -name '*.txt' -o -name '*.windows' -o -name '*.xml' -print0").
  155. // Using -n 500 for xargs to limit the max number of arguments per call to line_endings
  156. // to 500. This avoids line_endings failing with "arguments too long".
  157. Text("| xargs -0 -n 500 ").
  158. BuiltTool("line_endings").
  159. Flag("unix")
  160. // Exclude some file types (roughly matching sdk.exclude.atree)
  161. builder.Command().
  162. Text("find").
  163. Flag(dir.String()).
  164. Flag("'('").
  165. Flag("-name '.*' -o -name '*~' -o -name 'Makefile' -o -name 'Android.mk' -o").
  166. Flag("-name '.*.swp' -o -name '.DS_Store' -o -name '*.pyc' -o -name 'OWNERS' -o").
  167. Flag("-name 'MODULE_LICENSE_*' -o -name '*.ezt' -o -name 'Android.bp'").
  168. Flag("')' -print0").
  169. Text("| xargs -0 -r rm -rf")
  170. builder.Command().
  171. Text("find").
  172. Flag(dir.String()).
  173. Flag("-name '_*' ! -name '__*' -print0").
  174. Text("| xargs -0 -r rm -rf")
  175. if ctx.Windows() {
  176. // Fix EOL chars to make window users happy
  177. builder.Command().
  178. Text("find").
  179. Flag(dir.String()).
  180. Flag("-maxdepth 2 -name '*.bat' -type f -print0").
  181. Text("| xargs -0 -r unix2dos")
  182. }
  183. // Zip up our temporary directory as the sdk-repo
  184. builder.Command().
  185. BuiltTool("soong_zip").
  186. FlagWithOutput("-o ", outputZipFile).
  187. FlagWithArg("-P ", proptools.StringDefault(s.properties.Base_dir, ".")).
  188. FlagWithArg("-C ", dir.String()).
  189. FlagWithArg("-D ", dir.String())
  190. builder.Command().Text("rm").Flag("-rf").Text(dir.String())
  191. builder.Build("build_sdk_repo", "Creating sdk-repo-"+s.BaseModuleName())
  192. osName := ctx.Os().String()
  193. if osName == "linux_glibc" {
  194. osName = "linux"
  195. }
  196. name := fmt.Sprintf("sdk-repo-%s-%s", osName, s.BaseModuleName())
  197. s.outputBaseName = name
  198. s.outputFile = android.OptionalPathForPath(outputZipFile)
  199. ctx.InstallFile(android.PathForModuleInstall(ctx, "sdk-repo"), name+".zip", outputZipFile)
  200. }
  201. func (s *sdkRepoHost) AndroidMk() android.AndroidMkData {
  202. return android.AndroidMkData{
  203. Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
  204. fmt.Fprintln(w, ".PHONY:", name, "sdk_repo", "sdk-repo-"+name)
  205. fmt.Fprintln(w, "sdk_repo", "sdk-repo-"+name+":", strings.Join(s.FilesToInstall().Strings(), " "))
  206. fmt.Fprintf(w, "$(call dist-for-goals,sdk_repo sdk-repo-%s,%s:%s-FILE_NAME_TAG_PLACEHOLDER.zip)\n\n", s.BaseModuleName(), s.outputFile.String(), s.outputBaseName)
  207. },
  208. }
  209. }
  210. func remapPackageSpecs(specs map[string]android.PackagingSpec, remaps []remapProperties) error {
  211. for _, remap := range remaps {
  212. for path, spec := range specs {
  213. if match, err := pathtools.Match(remap.From, path); err != nil {
  214. return fmt.Errorf("Error parsing %q: %v", remap.From, err)
  215. } else if match {
  216. newPath := remap.To
  217. if pathtools.IsGlob(remap.From) {
  218. rel, err := filepath.Rel(constantPartOfPattern(remap.From), path)
  219. if err != nil {
  220. return fmt.Errorf("Error handling %q", path)
  221. }
  222. newPath = filepath.Join(remap.To, rel)
  223. }
  224. delete(specs, path)
  225. spec.SetRelPathInPackage(newPath)
  226. specs[newPath] = spec
  227. }
  228. }
  229. }
  230. return nil
  231. }
  232. func constantPartOfPattern(pattern string) string {
  233. ret := ""
  234. for pattern != "" {
  235. var first string
  236. first, pattern = splitFirst(pattern)
  237. if pathtools.IsGlob(first) {
  238. return ret
  239. }
  240. ret = filepath.Join(ret, first)
  241. }
  242. return ret
  243. }
  244. func splitFirst(path string) (string, string) {
  245. i := strings.IndexRune(path, filepath.Separator)
  246. if i < 0 {
  247. return path, ""
  248. }
  249. return path[:i], path[i+1:]
  250. }