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