1// Copyright 2016 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 cc 16 17import ( 18 "path/filepath" 19 20 "github.com/google/blueprint" 21 22 "android/soong/android" 23) 24 25type BinaryLinkerProperties struct { 26 // compile executable with -static 27 Static_executable *bool `android:"arch_variant"` 28 29 // set the name of the output 30 Stem *string `android:"arch_variant"` 31 32 // append to the name of the output 33 Suffix *string `android:"arch_variant"` 34 35 // if set, add an extra objcopy --prefix-symbols= step 36 Prefix_symbols *string 37 38 // if set, install a symlink to the preferred architecture 39 Symlink_preferred_arch *bool `android:"arch_variant"` 40 41 // install symlinks to the binary. Symlink names will have the suffix and the binary 42 // extension (if any) appended 43 Symlinks []string `android:"arch_variant"` 44 45 DynamicLinker string `blueprint:"mutated"` 46 47 // Names of modules to be overridden. Listed modules can only be other binaries 48 // (in Make or Soong). 49 // This does not completely prevent installation of the overridden binaries, but if both 50 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed 51 // from PRODUCT_PACKAGES. 52 Overrides []string 53 54 // Inject boringssl hash into the shared library. This is only intended for use by external/boringssl. 55 Inject_bssl_hash *bool `android:"arch_variant"` 56} 57 58func init() { 59 RegisterBinaryBuildComponents(android.InitRegistrationContext) 60} 61 62func RegisterBinaryBuildComponents(ctx android.RegistrationContext) { 63 ctx.RegisterModuleType("cc_binary", BinaryFactory) 64 ctx.RegisterModuleType("cc_binary_host", binaryHostFactory) 65} 66 67// cc_binary produces a binary that is runnable on a device. 68func BinaryFactory() android.Module { 69 module, _ := NewBinary(android.HostAndDeviceSupported) 70 return module.Init() 71} 72 73// cc_binary_host produces a binary that is runnable on a host. 74func binaryHostFactory() android.Module { 75 module, _ := NewBinary(android.HostSupported) 76 return module.Init() 77} 78 79// 80// Executables 81// 82 83type binaryDecorator struct { 84 *baseLinker 85 *baseInstaller 86 stripper 87 88 Properties BinaryLinkerProperties 89 90 toolPath android.OptionalPath 91 92 // Location of the linked, unstripped binary 93 unstrippedOutputFile android.Path 94 95 // Names of symlinks to be installed for use in LOCAL_MODULE_SYMLINKS 96 symlinks []string 97 98 // Output archive of gcno coverage information 99 coverageOutputFile android.OptionalPath 100 101 // Location of the files that should be copied to dist dir when requested 102 distFiles android.TaggedDistFiles 103 104 post_install_cmds []string 105} 106 107var _ linker = (*binaryDecorator)(nil) 108 109func (binary *binaryDecorator) linkerProps() []interface{} { 110 return append(binary.baseLinker.linkerProps(), 111 &binary.Properties, 112 &binary.stripper.StripProperties) 113 114} 115 116func (binary *binaryDecorator) getStemWithoutSuffix(ctx BaseModuleContext) string { 117 stem := ctx.baseModuleName() 118 if String(binary.Properties.Stem) != "" { 119 stem = String(binary.Properties.Stem) 120 } 121 122 return stem 123} 124 125func (binary *binaryDecorator) getStem(ctx BaseModuleContext) string { 126 return binary.getStemWithoutSuffix(ctx) + String(binary.Properties.Suffix) 127} 128 129func (binary *binaryDecorator) linkerDeps(ctx DepsContext, deps Deps) Deps { 130 deps = binary.baseLinker.linkerDeps(ctx, deps) 131 if ctx.toolchain().Bionic() { 132 if !Bool(binary.baseLinker.Properties.Nocrt) { 133 if !ctx.useSdk() { 134 if binary.static() { 135 deps.CrtBegin = "crtbegin_static" 136 } else { 137 deps.CrtBegin = "crtbegin_dynamic" 138 } 139 deps.CrtEnd = "crtend_android" 140 } else { 141 // TODO(danalbert): Add generation of crt objects. 142 // For `sdk_version: "current"`, we don't actually have a 143 // freshly generated set of CRT objects. Use the last stable 144 // version. 145 version := ctx.sdkVersion() 146 if version == "current" { 147 version = getCurrentNdkPrebuiltVersion(ctx) 148 } 149 150 if binary.static() { 151 deps.CrtBegin = "ndk_crtbegin_static." + version 152 } else { 153 if binary.static() { 154 deps.CrtBegin = "ndk_crtbegin_static." + version 155 } else { 156 deps.CrtBegin = "ndk_crtbegin_dynamic." + version 157 } 158 deps.CrtEnd = "ndk_crtend_android." + version 159 } 160 } 161 } 162 163 if binary.static() { 164 if ctx.selectedStl() == "libc++_static" { 165 deps.StaticLibs = append(deps.StaticLibs, "libm", "libc") 166 } 167 // static libraries libcompiler_rt, libc and libc_nomalloc need to be linked with 168 // --start-group/--end-group along with libgcc. If they are in deps.StaticLibs, 169 // move them to the beginning of deps.LateStaticLibs 170 var groupLibs []string 171 deps.StaticLibs, groupLibs = filterList(deps.StaticLibs, 172 []string{"libc", "libc_nomalloc", "libcompiler_rt"}) 173 deps.LateStaticLibs = append(groupLibs, deps.LateStaticLibs...) 174 } 175 176 if ctx.Os() == android.LinuxBionic && !binary.static() { 177 deps.DynamicLinker = "linker" 178 deps.LinkerFlagsFile = "host_bionic_linker_flags" 179 } 180 } 181 182 if !binary.static() && inList("libc", deps.StaticLibs) { 183 ctx.ModuleErrorf("statically linking libc to dynamic executable, please remove libc\n" + 184 "from static libs or set static_executable: true") 185 } 186 187 return deps 188} 189 190func (binary *binaryDecorator) isDependencyRoot() bool { 191 return true 192} 193 194func NewBinary(hod android.HostOrDeviceSupported) (*Module, *binaryDecorator) { 195 module := newModule(hod, android.MultilibFirst) 196 binary := &binaryDecorator{ 197 baseLinker: NewBaseLinker(module.sanitize), 198 baseInstaller: NewBaseInstaller("bin", "", InstallInSystem), 199 } 200 module.compiler = NewBaseCompiler() 201 module.linker = binary 202 module.installer = binary 203 204 // Allow module to be added as member of an sdk/module_exports. 205 module.sdkMemberTypes = []android.SdkMemberType{ 206 ccBinarySdkMemberType, 207 } 208 return module, binary 209} 210 211func (binary *binaryDecorator) linkerInit(ctx BaseModuleContext) { 212 binary.baseLinker.linkerInit(ctx) 213 214 if !ctx.toolchain().Bionic() { 215 if ctx.Os() == android.Linux { 216 if binary.Properties.Static_executable == nil && ctx.Config().HostStaticBinaries() { 217 binary.Properties.Static_executable = BoolPtr(true) 218 } 219 } else if !ctx.Fuchsia() { 220 // Static executables are not supported on Darwin or Windows 221 binary.Properties.Static_executable = nil 222 } 223 } 224} 225 226func (binary *binaryDecorator) static() bool { 227 return Bool(binary.Properties.Static_executable) 228} 229 230func (binary *binaryDecorator) staticBinary() bool { 231 return binary.static() 232} 233 234func (binary *binaryDecorator) binary() bool { 235 return true 236} 237 238func (binary *binaryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags { 239 flags = binary.baseLinker.linkerFlags(ctx, flags) 240 241 if ctx.Host() && !ctx.Windows() && !binary.static() { 242 if !ctx.Config().IsEnvTrue("DISABLE_HOST_PIE") { 243 flags.Global.LdFlags = append(flags.Global.LdFlags, "-pie") 244 } 245 } 246 247 // MinGW spits out warnings about -fPIC even for -fpie?!) being ignored because 248 // all code is position independent, and then those warnings get promoted to 249 // errors. 250 if !ctx.Windows() { 251 flags.Global.CFlags = append(flags.Global.CFlags, "-fPIE") 252 } 253 254 if ctx.toolchain().Bionic() { 255 if binary.static() { 256 // Clang driver needs -static to create static executable. 257 // However, bionic/linker uses -shared to overwrite. 258 // Linker for x86 targets does not allow coexistance of -static and -shared, 259 // so we add -static only if -shared is not used. 260 if !inList("-shared", flags.Local.LdFlags) { 261 flags.Global.LdFlags = append(flags.Global.LdFlags, "-static") 262 } 263 264 flags.Global.LdFlags = append(flags.Global.LdFlags, 265 "-nostdlib", 266 "-Bstatic", 267 "-Wl,--gc-sections", 268 ) 269 } else { 270 if flags.DynamicLinker == "" { 271 if binary.Properties.DynamicLinker != "" { 272 flags.DynamicLinker = binary.Properties.DynamicLinker 273 } else { 274 switch ctx.Os() { 275 case android.Android: 276 if ctx.bootstrap() && !ctx.inRecovery() && !ctx.inRamdisk() { 277 flags.DynamicLinker = "/system/bin/bootstrap/linker" 278 } else { 279 flags.DynamicLinker = "/system/bin/linker" 280 } 281 if flags.Toolchain.Is64Bit() { 282 flags.DynamicLinker += "64" 283 } 284 case android.LinuxBionic: 285 flags.DynamicLinker = "" 286 default: 287 ctx.ModuleErrorf("unknown dynamic linker") 288 } 289 } 290 291 if ctx.Os() == android.LinuxBionic { 292 // Use the dlwrap entry point, but keep _start around so 293 // that it can be used by host_bionic_inject 294 flags.Global.LdFlags = append(flags.Global.LdFlags, 295 "-Wl,--entry=__dlwrap__start", 296 "-Wl,--undefined=_start", 297 ) 298 } 299 } 300 301 flags.Global.LdFlags = append(flags.Global.LdFlags, 302 "-pie", 303 "-nostdlib", 304 "-Bdynamic", 305 "-Wl,--gc-sections", 306 "-Wl,-z,nocopyreloc", 307 ) 308 } 309 } else { 310 if binary.static() { 311 flags.Global.LdFlags = append(flags.Global.LdFlags, "-static") 312 } 313 if ctx.Darwin() { 314 flags.Global.LdFlags = append(flags.Global.LdFlags, "-Wl,-headerpad_max_install_names") 315 } 316 } 317 318 return flags 319} 320 321func (binary *binaryDecorator) link(ctx ModuleContext, 322 flags Flags, deps PathDeps, objs Objects) android.Path { 323 324 fileName := binary.getStem(ctx) + flags.Toolchain.ExecutableSuffix() 325 outputFile := android.PathForModuleOut(ctx, fileName) 326 ret := outputFile 327 328 var linkerDeps android.Paths 329 330 if deps.LinkerFlagsFile.Valid() { 331 flags.Local.LdFlags = append(flags.Local.LdFlags, "$$(cat "+deps.LinkerFlagsFile.String()+")") 332 linkerDeps = append(linkerDeps, deps.LinkerFlagsFile.Path()) 333 } 334 335 if flags.DynamicLinker != "" { 336 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-dynamic-linker,"+flags.DynamicLinker) 337 } else if ctx.toolchain().Bionic() && !binary.static() { 338 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--no-dynamic-linker") 339 } 340 341 builderFlags := flagsToBuilderFlags(flags) 342 343 if binary.stripper.needsStrip(ctx) { 344 if ctx.Darwin() { 345 builderFlags.stripUseGnuStrip = true 346 } 347 strippedOutputFile := outputFile 348 outputFile = android.PathForModuleOut(ctx, "unstripped", fileName) 349 binary.stripper.stripExecutableOrSharedLib(ctx, outputFile, strippedOutputFile, builderFlags) 350 } 351 352 binary.unstrippedOutputFile = outputFile 353 354 if String(binary.Properties.Prefix_symbols) != "" { 355 afterPrefixSymbols := outputFile 356 outputFile = android.PathForModuleOut(ctx, "unprefixed", fileName) 357 TransformBinaryPrefixSymbols(ctx, String(binary.Properties.Prefix_symbols), outputFile, 358 flagsToBuilderFlags(flags), afterPrefixSymbols) 359 } 360 361 outputFile = maybeInjectBoringSSLHash(ctx, outputFile, binary.Properties.Inject_bssl_hash, fileName) 362 363 if Bool(binary.baseLinker.Properties.Use_version_lib) { 364 if ctx.Host() { 365 versionedOutputFile := outputFile 366 outputFile = android.PathForModuleOut(ctx, "unversioned", fileName) 367 binary.injectVersionSymbol(ctx, outputFile, versionedOutputFile) 368 } else { 369 versionedOutputFile := android.PathForModuleOut(ctx, "versioned", fileName) 370 binary.distFiles = android.MakeDefaultDistFiles(versionedOutputFile) 371 372 if binary.stripper.needsStrip(ctx) { 373 out := android.PathForModuleOut(ctx, "versioned-stripped", fileName) 374 binary.distFiles = android.MakeDefaultDistFiles(out) 375 binary.stripper.stripExecutableOrSharedLib(ctx, versionedOutputFile, out, builderFlags) 376 } 377 378 binary.injectVersionSymbol(ctx, outputFile, versionedOutputFile) 379 } 380 } 381 382 if ctx.Os() == android.LinuxBionic && !binary.static() { 383 injectedOutputFile := outputFile 384 outputFile = android.PathForModuleOut(ctx, "prelinker", fileName) 385 386 if !deps.DynamicLinker.Valid() { 387 panic("Non-static host bionic modules must have a dynamic linker") 388 } 389 390 binary.injectHostBionicLinkerSymbols(ctx, outputFile, deps.DynamicLinker.Path(), injectedOutputFile) 391 } 392 393 var sharedLibs android.Paths 394 // Ignore shared libs for static executables. 395 if !binary.static() { 396 sharedLibs = deps.EarlySharedLibs 397 sharedLibs = append(sharedLibs, deps.SharedLibs...) 398 sharedLibs = append(sharedLibs, deps.LateSharedLibs...) 399 linkerDeps = append(linkerDeps, deps.EarlySharedLibsDeps...) 400 linkerDeps = append(linkerDeps, deps.SharedLibsDeps...) 401 linkerDeps = append(linkerDeps, deps.LateSharedLibsDeps...) 402 } 403 404 linkerDeps = append(linkerDeps, objs.tidyFiles...) 405 linkerDeps = append(linkerDeps, flags.LdFlagsDeps...) 406 407 TransformObjToDynamicBinary(ctx, objs.objFiles, sharedLibs, deps.StaticLibs, 408 deps.LateStaticLibs, deps.WholeStaticLibs, linkerDeps, deps.CrtBegin, deps.CrtEnd, true, 409 builderFlags, outputFile, nil) 410 411 objs.coverageFiles = append(objs.coverageFiles, deps.StaticLibObjs.coverageFiles...) 412 objs.coverageFiles = append(objs.coverageFiles, deps.WholeStaticLibObjs.coverageFiles...) 413 binary.coverageOutputFile = TransformCoverageFilesToZip(ctx, objs, binary.getStem(ctx)) 414 415 // Need to determine symlinks early since some targets (ie APEX) need this 416 // information but will not call 'install' 417 for _, symlink := range binary.Properties.Symlinks { 418 binary.symlinks = append(binary.symlinks, 419 symlink+String(binary.Properties.Suffix)+ctx.toolchain().ExecutableSuffix()) 420 } 421 422 if Bool(binary.Properties.Symlink_preferred_arch) { 423 if String(binary.Properties.Suffix) == "" { 424 ctx.PropertyErrorf("symlink_preferred_arch", "must also specify suffix") 425 } 426 if ctx.TargetPrimary() { 427 binary.symlinks = append(binary.symlinks, binary.getStemWithoutSuffix(ctx)) 428 } 429 } 430 431 return ret 432} 433 434func (binary *binaryDecorator) unstrippedOutputFilePath() android.Path { 435 return binary.unstrippedOutputFile 436} 437 438func (binary *binaryDecorator) symlinkList() []string { 439 return binary.symlinks 440} 441 442func (binary *binaryDecorator) nativeCoverage() bool { 443 return true 444} 445 446func (binary *binaryDecorator) coverageOutputFilePath() android.OptionalPath { 447 return binary.coverageOutputFile 448} 449 450// /system/bin/linker -> /apex/com.android.runtime/bin/linker 451func (binary *binaryDecorator) installSymlinkToRuntimeApex(ctx ModuleContext, file android.Path) { 452 dir := binary.baseInstaller.installDir(ctx) 453 dirOnDevice := android.InstallPathToOnDevicePath(ctx, dir) 454 target := "/" + filepath.Join("apex", "com.android.runtime", dir.Base(), file.Base()) 455 456 ctx.InstallAbsoluteSymlink(dir, file.Base(), target) 457 binary.post_install_cmds = append(binary.post_install_cmds, makeSymlinkCmd(dirOnDevice, file.Base(), target)) 458 459 for _, symlink := range binary.symlinks { 460 ctx.InstallAbsoluteSymlink(dir, symlink, target) 461 binary.post_install_cmds = append(binary.post_install_cmds, makeSymlinkCmd(dirOnDevice, symlink, target)) 462 } 463} 464 465func (binary *binaryDecorator) install(ctx ModuleContext, file android.Path) { 466 // Bionic binaries (e.g. linker) is installed to the bootstrap subdirectory. 467 // The original path becomes a symlink to the corresponding file in the 468 // runtime APEX. 469 translatedArch := ctx.Target().NativeBridge == android.NativeBridgeEnabled 470 if InstallToBootstrap(ctx.baseModuleName(), ctx.Config()) && !translatedArch && ctx.apexName() == "" && !ctx.inRamdisk() && !ctx.inRecovery() { 471 if ctx.Device() && isBionic(ctx.baseModuleName()) { 472 binary.installSymlinkToRuntimeApex(ctx, file) 473 } 474 binary.baseInstaller.subDir = "bootstrap" 475 } 476 binary.baseInstaller.install(ctx, file) 477 for _, symlink := range binary.symlinks { 478 ctx.InstallSymlink(binary.baseInstaller.installDir(ctx), symlink, binary.baseInstaller.path) 479 } 480 481 if ctx.Os().Class == android.Host { 482 binary.toolPath = android.OptionalPathForPath(binary.baseInstaller.path) 483 } 484} 485 486func (binary *binaryDecorator) hostToolPath() android.OptionalPath { 487 return binary.toolPath 488} 489 490func init() { 491 pctx.HostBinToolVariable("hostBionicSymbolsInjectCmd", "host_bionic_inject") 492} 493 494var injectHostBionicSymbols = pctx.AndroidStaticRule("injectHostBionicSymbols", 495 blueprint.RuleParams{ 496 Command: "$hostBionicSymbolsInjectCmd -i $in -l $linker -o $out", 497 CommandDeps: []string{"$hostBionicSymbolsInjectCmd"}, 498 }, "linker") 499 500func (binary *binaryDecorator) injectHostBionicLinkerSymbols(ctx ModuleContext, in, linker android.Path, out android.WritablePath) { 501 ctx.Build(pctx, android.BuildParams{ 502 Rule: injectHostBionicSymbols, 503 Description: "inject host bionic symbols", 504 Input: in, 505 Implicit: linker, 506 Output: out, 507 Args: map[string]string{ 508 "linker": linker.String(), 509 }, 510 }) 511} 512