blob: 4ad039f4393df783df86708d40494112d20956da [file] [log] [blame]
Colin Cross43f08db2018-11-12 10:13:39 -08001// Copyright 2018 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
15// The dexpreopt package converts a global dexpreopt config and a module dexpreopt config into rules to perform
16// dexpreopting and to strip the dex files from the APK or JAR.
17//
18// It is used in two places; in the dexpeopt_gen binary for modules defined in Make, and directly linked into Soong.
19//
20// For Make modules it is built into the dexpreopt_gen binary, which is executed as a Make rule using global config and
21// module config specified in JSON files. The binary writes out two shell scripts, only updating them if they have
22// changed. One script takes an APK or JAR as an input and produces a zip file containing any outputs of preopting,
23// in the location they should be on the device. The Make build rules will unzip the zip file into $(PRODUCT_OUT) when
24// installing the APK, which will install the preopt outputs into $(PRODUCT_OUT)/system or $(PRODUCT_OUT)/system_other
25// as necessary. The zip file may be empty if preopting was disabled for any reason. The second script takes an APK or
26// JAR as an input and strips the dex files in it as necessary.
27//
28// The intermediate shell scripts allow changes to this package or to the global config to regenerate the shell scripts
29// but only require re-executing preopting if the script has changed.
30//
31// For Soong modules this package is linked directly into Soong and run from the java package. It generates the same
32// commands as for make, using athe same global config JSON file used by make, but using a module config structure
33// provided by Soong. The generated commands are then converted into Soong rule and written directly to the ninja file,
34// with no extra shell scripts involved.
35package dexpreopt
36
37import (
38 "fmt"
39 "path/filepath"
40 "strings"
41
42 "github.com/google/blueprint/pathtools"
43)
44
45const SystemPartition = "/system/"
46const SystemOtherPartition = "/system_other/"
47
48// GenerateStripRule generates a set of commands that will take an APK or JAR as an input and strip the dex files if
49// they are no longer necessary after preopting.
50func GenerateStripRule(global GlobalConfig, module ModuleConfig) (rule *Rule, err error) {
51 defer func() {
52 if r := recover(); r != nil {
53 if e, ok := r.(error); ok {
54 err = e
55 rule = nil
56 } else {
57 panic(r)
58 }
59 }
60 }()
61
62 tools := global.Tools
63
64 rule = &Rule{}
65
66 strip := shouldStripDex(module, global)
67
68 if strip {
69 // Only strips if the dex files are not already uncompressed
70 rule.Command().
71 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, module.StripInputPath).
72 Tool(tools.Zip2zip).FlagWithInput("-i ", module.StripInputPath).FlagWithOutput("-o ", module.StripOutputPath).
73 FlagWithArg("-x ", `"classes*.dex"`).
74 Textf(`; else cp -f %s %s; fi`, module.StripInputPath, module.StripOutputPath)
75 } else {
76 rule.Command().Text("cp -f").Input(module.StripInputPath).Output(module.StripOutputPath)
77 }
78
79 return rule, nil
80}
81
82// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
83// ModuleConfig. The produced files and their install locations will be available through rule.Installs().
84func GenerateDexpreoptRule(global GlobalConfig, module ModuleConfig) (rule *Rule, err error) {
85 defer func() {
86 if r := recover(); r != nil {
87 if e, ok := r.(error); ok {
88 err = e
89 rule = nil
90 } else {
91 panic(r)
92 }
93 }
94 }()
95
96 rule = &Rule{}
97
98 dexpreoptDisabled := contains(global.DisablePreoptModules, module.Name)
99
100 if contains(global.BootJars, module.Name) {
101 // Don't preopt individual boot jars, they will be preopted together
102 dexpreoptDisabled = true
103 }
104
105 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
106 // Also preopt system server jars since selinux prevents system server from loading anything from
107 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
108 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
109 if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
110 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
111 dexpreoptDisabled = true
112 }
113
114 generateProfile := module.ProfileClassListing != "" && !global.DisableGenerateProfile
115
116 var profile string
117 if generateProfile {
118 profile = profileCommand(global, module, rule)
119 }
120
121 if !dexpreoptDisabled {
122 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
123 !module.NoCreateAppImage
124
125 generateDM := shouldGenerateDM(module, global)
126
127 for _, arch := range module.Archs {
128 imageLocation := module.DexPreoptImageLocation
129 if imageLocation == "" {
130 imageLocation = global.DefaultDexPreoptImageLocation[arch]
131 }
132 dexpreoptCommand(global, module, rule, profile, arch, imageLocation, appImage, generateDM)
133 }
134 }
135
136 return rule, nil
137}
138
139func profileCommand(global GlobalConfig, module ModuleConfig, rule *Rule) string {
140 profilePath := filepath.Join(filepath.Dir(module.BuildPath), "profile.prof")
141 profileInstalledPath := module.DexLocation + ".prof"
142
143 if !module.ProfileIsTextListing {
144 rule.Command().FlagWithOutput("touch ", profilePath)
145 }
146
147 cmd := rule.Command().
148 Text(`ANDROID_LOG_TAGS="*:e"`).
149 Tool(global.Tools.Profman)
150
151 if module.ProfileIsTextListing {
152 // The profile is a test listing of classes (used for framework jars).
153 // We need to generate the actual binary profile before being able to compile.
154 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing)
155 } else {
156 // The profile is binary profile (used for apps). Run it through profman to
157 // ensure the profile keys match the apk.
158 cmd.
159 Flag("--copy-and-update-profile-key").
160 FlagWithInput("--profile-file=", module.ProfileClassListing)
161 }
162
163 cmd.
164 FlagWithInput("--apk=", module.DexPath).
165 Flag("--dex-location="+module.DexLocation).
166 FlagWithOutput("--reference-profile-file=", profilePath)
167
168 if !module.ProfileIsTextListing {
169 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
170 }
171 rule.Install(profilePath, profileInstalledPath)
172
173 return profilePath
174}
175
176func dexpreoptCommand(global GlobalConfig, module ModuleConfig, rule *Rule, profile, arch, bootImageLocation string,
177 appImage, generateDM bool) {
178
179 // HACK: make soname in Soong-generated .odex files match Make.
180 base := filepath.Base(module.DexLocation)
181 if filepath.Ext(base) == ".jar" {
182 base = "javalib.jar"
183 } else if filepath.Ext(base) == ".apk" {
184 base = "package.apk"
185 }
186
187 toOdexPath := func(path string) string {
188 return filepath.Join(
189 filepath.Dir(path),
190 "oat",
191 arch,
192 pathtools.ReplaceExtension(filepath.Base(path), "odex"))
193 }
194
Vladimir Markod2ee5322018-12-19 17:57:57 +0000195 bcp := strings.Join(global.PreoptBootClassPathDexFiles, ":")
196 bcp_locations := strings.Join(global.PreoptBootClassPathDexLocations, ":")
197
Colin Cross43f08db2018-11-12 10:13:39 -0800198 odexPath := toOdexPath(filepath.Join(filepath.Dir(module.BuildPath), base))
199 odexInstallPath := toOdexPath(module.DexLocation)
200 if odexOnSystemOther(module, global) {
201 odexInstallPath = strings.Replace(odexInstallPath, SystemPartition, SystemOtherPartition, 1)
202 }
203
204 vdexPath := pathtools.ReplaceExtension(odexPath, "vdex")
205 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
206
Alex Light5de41962018-12-18 15:16:26 -0800207 invocationPath := pathtools.ReplaceExtension(odexPath, "invocation")
208
Colin Cross43f08db2018-11-12 10:13:39 -0800209 // bootImageLocation is $OUT/dex_bootjars/system/framework/boot.art, but dex2oat actually reads
210 // $OUT/dex_bootjars/system/framework/arm64/boot.art
211 var bootImagePath string
212 if bootImageLocation != "" {
213 bootImagePath = filepath.Join(filepath.Dir(bootImageLocation), arch, filepath.Base(bootImageLocation))
214 }
215
216 // Lists of used and optional libraries from the build config to be verified against the manifest in the APK
217 var verifyUsesLibs []string
218 var verifyOptionalUsesLibs []string
219
220 // Lists of used and optional libraries from the build config, with optional libraries that are known to not
221 // be present in the current product removed.
222 var filteredUsesLibs []string
223 var filteredOptionalUsesLibs []string
224
225 // The class loader context using paths in the build
226 var classLoaderContextHost []string
227
228 // The class loader context using paths as they will be on the device
229 var classLoaderContextTarget []string
230
231 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 28
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000232 var conditionalClassLoaderContextHost28 []string
233 var conditionalClassLoaderContextTarget28 []string
234
235 // Extra paths that will be appended to the class loader if the APK manifest has targetSdkVersion < 29
236 var conditionalClassLoaderContextHost29 []string
237 var conditionalClassLoaderContextTarget29 []string
Colin Cross43f08db2018-11-12 10:13:39 -0800238
239 if module.EnforceUsesLibraries {
240 verifyUsesLibs = copyOf(module.UsesLibraries)
241 verifyOptionalUsesLibs = copyOf(module.OptionalUsesLibraries)
242
243 filteredOptionalUsesLibs = filterOut(global.MissingUsesLibraries, module.OptionalUsesLibraries)
244 filteredUsesLibs = append(copyOf(module.UsesLibraries), filteredOptionalUsesLibs...)
245
246 // Create class loader context for dex2oat from uses libraries and filtered optional libraries
247 for _, l := range filteredUsesLibs {
248
249 classLoaderContextHost = append(classLoaderContextHost,
250 pathForLibrary(module, l))
251 classLoaderContextTarget = append(classLoaderContextTarget,
252 filepath.Join("/system/framework", l+".jar"))
253 }
254
255 const httpLegacy = "org.apache.http.legacy"
256 const httpLegacyImpl = "org.apache.http.legacy.impl"
257
258 // Fix up org.apache.http.legacy.impl since it should be org.apache.http.legacy in the manifest.
259 replace(verifyUsesLibs, httpLegacyImpl, httpLegacy)
260 replace(verifyOptionalUsesLibs, httpLegacyImpl, httpLegacy)
261
262 if !contains(verifyUsesLibs, httpLegacy) && !contains(verifyOptionalUsesLibs, httpLegacy) {
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000263 conditionalClassLoaderContextHost28 = append(conditionalClassLoaderContextHost28,
Colin Cross43f08db2018-11-12 10:13:39 -0800264 pathForLibrary(module, httpLegacyImpl))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000265 conditionalClassLoaderContextTarget28 = append(conditionalClassLoaderContextTarget28,
Colin Cross43f08db2018-11-12 10:13:39 -0800266 filepath.Join("/system/framework", httpLegacyImpl+".jar"))
267 }
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000268
269 const hidlBase = "android.hidl.base-V1.0-java"
270 const hidlManager = "android.hidl.manager-V1.0-java"
271
272 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800273 pathForLibrary(module, hidlManager))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000274 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
275 filepath.Join("/system/framework", hidlManager+".jar"))
276 conditionalClassLoaderContextHost29 = append(conditionalClassLoaderContextHost29,
Alex Light5de41962018-12-18 15:16:26 -0800277 pathForLibrary(module, hidlBase))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000278 conditionalClassLoaderContextTarget29 = append(conditionalClassLoaderContextTarget29,
279 filepath.Join("/system/framework", hidlBase+".jar"))
Colin Cross43f08db2018-11-12 10:13:39 -0800280 } else {
281 // Pass special class loader context to skip the classpath and collision check.
282 // This will get removed once LOCAL_USES_LIBRARIES is enforced.
283 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default
284 // to the &.
285 classLoaderContextHost = []string{`\&`}
286 }
287
288 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath))
289 rule.Command().FlagWithOutput("rm -f ", odexPath)
290 // Set values in the environment of the rule. These may be modified by construct_context.sh.
291 rule.Command().FlagWithArg("class_loader_context_arg=--class-loader-context=",
292 strings.Join(classLoaderContextHost, ":"))
293 rule.Command().Text(`stored_class_loader_context_arg=""`)
294
295 if module.EnforceUsesLibraries {
Colin Cross43f08db2018-11-12 10:13:39 -0800296 rule.Command().Textf(`uses_library_names="%s"`, strings.Join(verifyUsesLibs, " "))
297 rule.Command().Textf(`optional_uses_library_names="%s"`, strings.Join(verifyOptionalUsesLibs, " "))
298 rule.Command().Textf(`aapt_binary="%s"`, global.Tools.Aapt)
Alex Light5de41962018-12-18 15:16:26 -0800299 rule.Command().Textf(`dex_preopt_host_libraries="%s"`, strings.Join(classLoaderContextHost, " "))
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000300 rule.Command().Textf(`dex_preopt_target_libraries="%s"`, strings.Join(classLoaderContextTarget, " "))
301 rule.Command().Textf(`conditional_host_libs_28="%s"`, strings.Join(conditionalClassLoaderContextHost28, " "))
302 rule.Command().Textf(`conditional_target_libs_28="%s"`, strings.Join(conditionalClassLoaderContextTarget28, " "))
303 rule.Command().Textf(`conditional_host_libs_29="%s"`, strings.Join(conditionalClassLoaderContextHost29, " "))
304 rule.Command().Textf(`conditional_target_libs_29="%s"`, strings.Join(conditionalClassLoaderContextTarget29, " "))
Colin Cross43f08db2018-11-12 10:13:39 -0800305 rule.Command().Text("source").Tool(global.Tools.VerifyUsesLibraries).Input(module.DexPath)
Nicolas Geoffray05aa7d22018-12-18 14:15:12 +0000306 rule.Command().Text("source").Tool(global.Tools.ConstructContext)
Colin Cross43f08db2018-11-12 10:13:39 -0800307 }
308
309 cmd := rule.Command().
310 Text(`ANDROID_LOG_TAGS="*:e"`).
311 Tool(global.Tools.Dex2oat).
312 Flag("--avoid-storing-invocation").
Alex Light5de41962018-12-18 15:16:26 -0800313 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
Colin Cross43f08db2018-11-12 10:13:39 -0800314 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
315 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
Vladimir Markod2ee5322018-12-19 17:57:57 +0000316 Flag("--runtime-arg").FlagWithArg("-Xbootclasspath:", bcp).
317 Implicits(global.PreoptBootClassPathDexFiles).
318 Flag("--runtime-arg").FlagWithArg("-Xbootclasspath-locations:", bcp_locations).
Colin Cross43f08db2018-11-12 10:13:39 -0800319 Flag("${class_loader_context_arg}").
320 Flag("${stored_class_loader_context_arg}").
321 FlagWithArg("--boot-image=", bootImageLocation).Implicit(bootImagePath).
322 FlagWithInput("--dex-file=", module.DexPath).
323 FlagWithArg("--dex-location=", module.DexLocation).
324 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
325 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
326 FlagWithArg("--android-root=", global.EmptyDirectory).
327 FlagWithArg("--instruction-set=", arch).
328 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
329 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
330 Flag("--no-generate-debug-info").
331 Flag("--generate-build-id").
332 Flag("--abort-on-hard-verifier-error").
333 Flag("--force-determinism").
334 FlagWithArg("--no-inline-from=", "core-oj.jar")
335
336 var preoptFlags []string
337 if len(module.PreoptFlags) > 0 {
338 preoptFlags = module.PreoptFlags
339 } else if len(global.PreoptFlags) > 0 {
340 preoptFlags = global.PreoptFlags
341 }
342
343 if len(preoptFlags) > 0 {
344 cmd.Text(strings.Join(preoptFlags, " "))
345 }
346
347 if module.UncompressedDex {
348 cmd.FlagWithArg("--copy-dex-files=", "false")
349 }
350
351 if !anyHavePrefix(preoptFlags, "--compiler-filter=") {
352 var compilerFilter string
353 if contains(global.SystemServerJars, module.Name) {
354 // Jars of system server, use the product option if it is set, speed otherwise.
355 if global.SystemServerCompilerFilter != "" {
356 compilerFilter = global.SystemServerCompilerFilter
357 } else {
358 compilerFilter = "speed"
359 }
360 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
361 // Apps loaded into system server, and apps the product default to being compiled with the
362 // 'speed' compiler filter.
363 compilerFilter = "speed"
364 } else if profile != "" {
365 // For non system server jars, use speed-profile when we have a profile.
366 compilerFilter = "speed-profile"
367 } else if global.DefaultCompilerFilter != "" {
368 compilerFilter = global.DefaultCompilerFilter
369 } else {
370 compilerFilter = "quicken"
371 }
372 cmd.FlagWithArg("--compiler-filter=", compilerFilter)
373 }
374
375 if generateDM {
376 cmd.FlagWithArg("--copy-dex-files=", "false")
377 dmPath := filepath.Join(filepath.Dir(module.BuildPath), "generated.dm")
378 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
379 tmpPath := filepath.Join(filepath.Dir(module.BuildPath), "primary.vdex")
380 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
381 rule.Command().Tool(global.Tools.SoongZip).
382 FlagWithArg("-L", "9").
383 FlagWithOutput("-o", dmPath).
384 Flag("-j").
385 Input(tmpPath)
386 rule.Install(dmPath, dmInstalledPath)
387 }
388
389 // By default, emit debug info.
390 debugInfo := true
391 if global.NoDebugInfo {
392 // If the global setting suppresses mini-debug-info, disable it.
393 debugInfo = false
394 }
395
396 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
397 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
398 if contains(global.SystemServerJars, module.Name) {
399 if global.AlwaysSystemServerDebugInfo {
400 debugInfo = true
401 } else if global.NeverSystemServerDebugInfo {
402 debugInfo = false
403 }
404 } else {
405 if global.AlwaysOtherDebugInfo {
406 debugInfo = true
407 } else if global.NeverOtherDebugInfo {
408 debugInfo = false
409 }
410 }
411
412 // Never enable on eng.
413 if global.IsEng {
414 debugInfo = false
415 }
416
417 if debugInfo {
418 cmd.Flag("--generate-mini-debug-info")
419 } else {
420 cmd.Flag("--no-generate-mini-debug-info")
421 }
422
423 // Set the compiler reason to 'prebuilt' to identify the oat files produced
424 // during the build, as opposed to compiled on the device.
425 cmd.FlagWithArg("--compilation-reason=", "prebuilt")
426
427 if appImage {
428 appImagePath := pathtools.ReplaceExtension(odexPath, "art")
429 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
430 cmd.FlagWithOutput("--app-image-file=", appImagePath).
431 FlagWithArg("--image-format=", "lz4")
432 rule.Install(appImagePath, appImageInstallPath)
433 }
434
435 if profile != "" {
436 cmd.FlagWithArg("--profile-file=", profile)
437 }
438
439 rule.Install(odexPath, odexInstallPath)
440 rule.Install(vdexPath, vdexInstallPath)
441}
442
443// Return if the dex file in the APK should be stripped. If an APK is found to contain uncompressed dex files at
444// dex2oat time it will not be stripped even if strip=true.
445func shouldStripDex(module ModuleConfig, global GlobalConfig) bool {
446 strip := !global.DefaultNoStripping
447
448 // Don't strip modules that are not on the system partition in case the oat/vdex version in system ROM
449 // doesn't match the one in other partitions. It needs to be able to fall back to the APK for that case.
450 if !strings.HasPrefix(module.DexLocation, SystemPartition) {
451 strip = false
452 }
453
454 // system_other isn't there for an OTA, so don't strip if module is on system, and odex is on system_other.
455 if odexOnSystemOther(module, global) {
456 strip = false
457 }
458
459 if module.HasApkLibraries {
460 strip = false
461 }
462
463 // Don't strip with dex files we explicitly uncompress (dexopt will not store the dex code).
464 if module.UncompressedDex {
465 strip = false
466 }
467
468 if shouldGenerateDM(module, global) {
469 strip = false
470 }
471
472 if module.PresignedPrebuilt {
473 // Only strip out files if we can re-sign the package.
474 strip = false
475 }
476
477 return strip
478}
479
480func shouldGenerateDM(module ModuleConfig, global GlobalConfig) bool {
481 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
482 // No reason to use a dm file if the dex is already uncompressed.
483 return global.GenerateDMFiles && !module.UncompressedDex &&
484 contains(module.PreoptFlags, "--compiler-filter=verify")
485}
486
487func odexOnSystemOther(module ModuleConfig, global GlobalConfig) bool {
488 if !global.HasSystemOther {
489 return false
490 }
491
492 if global.SanitizeLite {
493 return false
494 }
495
496 if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
497 return false
498 }
499
500 for _, f := range global.PatternsOnSystemOther {
501 if makefileMatch(filepath.Join(SystemPartition, f), module.DexLocation) {
502 return true
503 }
504 }
505
506 return false
507}
508
509func pathForLibrary(module ModuleConfig, lib string) string {
510 path := module.LibraryPaths[lib]
511 if path == "" {
512 panic(fmt.Errorf("unknown library path for %q", lib))
513 }
514 return path
515}
516
517func makefileMatch(pattern, s string) bool {
518 percent := strings.IndexByte(pattern, '%')
519 switch percent {
520 case -1:
521 return pattern == s
522 case len(pattern) - 1:
523 return strings.HasPrefix(s, pattern[:len(pattern)-1])
524 default:
525 panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
526 }
527}
528
529func contains(l []string, s string) bool {
530 for _, e := range l {
531 if e == s {
532 return true
533 }
534 }
535 return false
536}
537
538// remove all elements in a from b, returning a new slice
539func filterOut(a []string, b []string) []string {
540 var ret []string
541 for _, x := range b {
542 if !contains(a, x) {
543 ret = append(ret, x)
544 }
545 }
546 return ret
547}
548
549func replace(l []string, from, to string) {
550 for i := range l {
551 if l[i] == from {
552 l[i] = to
553 }
554 }
555}
556
557func copyOf(l []string) []string {
558 return append([]string(nil), l...)
559}
560
561func anyHavePrefix(l []string, prefix string) bool {
562 for _, x := range l {
563 if strings.HasPrefix(x, prefix) {
564 return true
565 }
566 }
567 return false
568}