1// 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 15package main 16 17import ( 18 "bytes" 19 "flag" 20 "fmt" 21 "io/ioutil" 22 "os" 23 "path/filepath" 24 "runtime" 25 "strings" 26 27 "android/soong/android" 28 "android/soong/dexpreopt" 29 30 "github.com/google/blueprint" 31 "github.com/google/blueprint/pathtools" 32) 33 34var ( 35 dexpreoptScriptPath = flag.String("dexpreopt_script", "", "path to output dexpreopt script") 36 globalSoongConfigPath = flag.String("global_soong", "", "path to global configuration file for settings originating from Soong") 37 globalConfigPath = flag.String("global", "", "path to global configuration file") 38 moduleConfigPath = flag.String("module", "", "path to module configuration file") 39 outDir = flag.String("out_dir", "", "path to output directory") 40 // If uses_target_files is true, dexpreopt_gen will be running on extracted target_files.zip files. 41 // In this case, the tool replace output file path with $(basePath)/$(on-device file path). 42 // The flag is useful when running dex2oat on system image and vendor image which are built separately. 43 usesTargetFiles = flag.Bool("uses_target_files", false, "whether or not dexpreopt is running on target_files") 44 // basePath indicates the path where target_files.zip is extracted. 45 basePath = flag.String("base_path", ".", "base path where images and tools are extracted") 46) 47 48type builderContext struct { 49 config android.Config 50} 51 52func (x *builderContext) Config() android.Config { return x.config } 53func (x *builderContext) AddNinjaFileDeps(...string) {} 54func (x *builderContext) Build(android.PackageContext, android.BuildParams) {} 55func (x *builderContext) Rule(android.PackageContext, string, blueprint.RuleParams, ...string) blueprint.Rule { 56 return nil 57} 58 59func main() { 60 flag.Parse() 61 62 usage := func(err string) { 63 if err != "" { 64 fmt.Println(err) 65 flag.Usage() 66 os.Exit(1) 67 } 68 } 69 70 if flag.NArg() > 0 { 71 usage("unrecognized argument " + flag.Arg(0)) 72 } 73 74 if *dexpreoptScriptPath == "" { 75 usage("path to output dexpreopt script is required") 76 } 77 78 if *globalSoongConfigPath == "" { 79 usage("--global_soong configuration file is required") 80 } 81 82 if *globalConfigPath == "" { 83 usage("--global configuration file is required") 84 } 85 86 if *moduleConfigPath == "" { 87 usage("--module configuration file is required") 88 } 89 90 ctx := &builderContext{android.NullConfig(*outDir)} 91 92 globalSoongConfigData, err := ioutil.ReadFile(*globalSoongConfigPath) 93 if err != nil { 94 fmt.Fprintf(os.Stderr, "error reading global Soong config %q: %s\n", *globalSoongConfigPath, err) 95 os.Exit(2) 96 } 97 98 globalSoongConfig, err := dexpreopt.ParseGlobalSoongConfig(ctx, globalSoongConfigData) 99 if err != nil { 100 fmt.Fprintf(os.Stderr, "error parsing global Soong config %q: %s\n", *globalSoongConfigPath, err) 101 os.Exit(2) 102 } 103 104 globalConfigData, err := ioutil.ReadFile(*globalConfigPath) 105 if err != nil { 106 fmt.Fprintf(os.Stderr, "error reading global config %q: %s\n", *globalConfigPath, err) 107 os.Exit(2) 108 } 109 110 globalConfig, err := dexpreopt.ParseGlobalConfig(ctx, globalConfigData) 111 if err != nil { 112 fmt.Fprintf(os.Stderr, "error parsing global config %q: %s\n", *globalConfigPath, err) 113 os.Exit(2) 114 } 115 116 moduleConfigData, err := ioutil.ReadFile(*moduleConfigPath) 117 if err != nil { 118 fmt.Fprintf(os.Stderr, "error reading module config %q: %s\n", *moduleConfigPath, err) 119 os.Exit(2) 120 } 121 122 moduleConfig, err := dexpreopt.ParseModuleConfig(ctx, moduleConfigData) 123 if err != nil { 124 fmt.Fprintf(os.Stderr, "error parsing module config %q: %s\n", *moduleConfigPath, err) 125 os.Exit(2) 126 } 127 128 moduleConfig.DexPath = android.PathForTesting("$1") 129 130 defer func() { 131 if r := recover(); r != nil { 132 switch x := r.(type) { 133 case runtime.Error: 134 panic(x) 135 case error: 136 fmt.Fprintln(os.Stderr, "error:", r) 137 os.Exit(3) 138 default: 139 panic(x) 140 } 141 } 142 }() 143 if *usesTargetFiles { 144 moduleConfig.ManifestPath = android.OptionalPath{} 145 prefix := "dex2oat_result" 146 moduleConfig.BuildPath = android.PathForOutput(ctx, filepath.Join(prefix, moduleConfig.DexLocation)) 147 for i, location := range moduleConfig.PreoptBootClassPathDexLocations { 148 moduleConfig.PreoptBootClassPathDexFiles[i] = android.PathForSource(ctx, *basePath+location) 149 } 150 for i := range moduleConfig.ClassLoaderContexts { 151 for _, v := range moduleConfig.ClassLoaderContexts[i] { 152 v.Host = android.PathForSource(ctx, *basePath+v.Device) 153 } 154 } 155 moduleConfig.EnforceUsesLibraries = false 156 for i, location := range moduleConfig.DexPreoptImageLocationsOnDevice { 157 moduleConfig.DexPreoptImageLocationsOnHost[i] = *basePath + location 158 } 159 } 160 writeScripts(ctx, globalSoongConfig, globalConfig, moduleConfig, *dexpreoptScriptPath) 161} 162 163func writeScripts(ctx android.BuilderContext, globalSoong *dexpreopt.GlobalSoongConfig, 164 global *dexpreopt.GlobalConfig, module *dexpreopt.ModuleConfig, dexpreoptScriptPath string) { 165 write := func(rule *android.RuleBuilder, file string) { 166 script := &bytes.Buffer{} 167 script.WriteString(scriptHeader) 168 for _, c := range rule.Commands() { 169 script.WriteString(c) 170 script.WriteString("\n\n") 171 } 172 173 depFile := &bytes.Buffer{} 174 175 fmt.Fprint(depFile, `: \`+"\n") 176 for _, tool := range rule.Tools() { 177 fmt.Fprintf(depFile, ` %s \`+"\n", tool) 178 } 179 for _, input := range rule.Inputs() { 180 // Assume the rule that ran the script already has a dependency on the input file passed on the 181 // command line. 182 if input.String() != "$1" { 183 fmt.Fprintf(depFile, ` %s \`+"\n", input) 184 } 185 } 186 depFile.WriteString("\n") 187 188 fmt.Fprintln(script, "rm -f $2.d") 189 // Write the output path unescaped so the $2 gets expanded 190 fmt.Fprintln(script, `echo -n $2 > $2.d`) 191 // Write the rest of the depsfile using cat <<'EOF', which will not do any shell expansion on 192 // the contents to preserve backslashes and special characters in filenames. 193 fmt.Fprintf(script, "cat >> $2.d <<'EOF'\n%sEOF\n", depFile.String()) 194 195 err := pathtools.WriteFileIfChanged(file, script.Bytes(), 0755) 196 if err != nil { 197 panic(err) 198 } 199 } 200 dexpreoptRule, err := dexpreopt.GenerateDexpreoptRule(ctx, globalSoong, global, module) 201 if err != nil { 202 panic(err) 203 } 204 // When usesTargetFiles is true, only odex/vdex files are necessary. 205 // So skip redunant processes(such as copying the result to the artifact path, and zipping, and so on.) 206 if *usesTargetFiles { 207 write(dexpreoptRule, dexpreoptScriptPath) 208 return 209 } 210 installDir := module.BuildPath.InSameDir(ctx, "dexpreopt_install") 211 212 dexpreoptRule.Command().FlagWithArg("rm -rf ", installDir.String()) 213 dexpreoptRule.Command().FlagWithArg("mkdir -p ", installDir.String()) 214 215 for _, install := range dexpreoptRule.Installs() { 216 installPath := installDir.Join(ctx, strings.TrimPrefix(install.To, "/")) 217 dexpreoptRule.Command().Text("mkdir -p").Flag(filepath.Dir(installPath.String())) 218 dexpreoptRule.Command().Text("cp -f").Input(install.From).Output(installPath) 219 } 220 dexpreoptRule.Command().Tool(globalSoong.SoongZip). 221 FlagWithArg("-o ", "$2"). 222 FlagWithArg("-C ", installDir.String()). 223 FlagWithArg("-D ", installDir.String()) 224 225 // The written scripts will assume the input is $1 and the output is $2 226 if module.DexPath.String() != "$1" { 227 panic(fmt.Errorf("module.DexPath must be '$1', was %q", module.DexPath)) 228 } 229 230 write(dexpreoptRule, dexpreoptScriptPath) 231} 232 233const scriptHeader = `#!/bin/bash 234 235err() { 236 errno=$? 237 echo "error: $0:$1 exited with status $errno" >&2 238 echo "error in command:" >&2 239 sed -n -e "$1p" $0 >&2 240 if [ "$errno" -ne 0 ]; then 241 exit $errno 242 else 243 exit 1 244 fi 245} 246 247trap 'err $LINENO' ERR 248 249` 250