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 "android/soong/android" 21 22 "github.com/google/blueprint" 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 // override the dynamic linker 46 DynamicLinker string `blueprint:"mutated"` 47 48 // Names of modules to be overridden. Listed modules can only be other binaries 49 // (in Make or Soong). 50 // This does not completely prevent installation of the overridden binaries, but if both 51 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed 52 // from PRODUCT_PACKAGES. 53 Overrides []string 54 55 // Inject boringssl hash into the shared library. This is only intended for use by external/boringssl. 56 Inject_bssl_hash *bool `android:"arch_variant"` 57} 58 59func init() { 60 RegisterBinaryBuildComponents(android.InitRegistrationContext) 61} 62 63func RegisterBinaryBuildComponents(ctx android.RegistrationContext) { 64 ctx.RegisterModuleType("cc_binary", BinaryFactory) 65 ctx.RegisterModuleType("cc_binary_host", BinaryHostFactory) 66} 67 68// cc_binary produces a binary that is runnable on a device. 69func BinaryFactory() android.Module { 70 module, _ := newBinary(android.HostAndDeviceSupported) 71 return module.Init() 72} 73 74// cc_binary_host produces a binary that is runnable on a host. 75func BinaryHostFactory() android.Module { 76 module, _ := newBinary(android.HostSupported) 77 return module.Init() 78} 79 80// 81// Executables 82// 83 84// binaryDecorator is a decorator containing information for C++ binary modules. 85type binaryDecorator struct { 86 *baseLinker 87 *baseInstaller 88 stripper Stripper 89 90 Properties BinaryLinkerProperties 91 92 toolPath android.OptionalPath 93 94 // Location of the linked, unstripped binary 95 unstrippedOutputFile android.Path 96 97 // Names of symlinks to be installed for use in LOCAL_MODULE_SYMLINKS 98 symlinks []string 99 100 // If the module has symlink_preferred_arch set, the name of the symlink to the 101 // binary for the preferred arch. 102 preferredArchSymlink string 103 104 // Output archive of gcno coverage information 105 coverageOutputFile android.OptionalPath 106 107 // Location of the files that should be copied to dist dir when requested 108 distFiles android.TaggedDistFiles 109 110 // Action command lines to run directly after the binary is installed. For example, 111 // may be used to symlink runtime dependencies (such as bionic) alongside installation. 112 postInstallCmds []string 113} 114 115var _ linker = (*binaryDecorator)(nil) 116 117// linkerProps returns the list of individual properties objects relevant 118// for this binary. 119func (binary *binaryDecorator) linkerProps() []interface{} { 120 return append(binary.baseLinker.linkerProps(), 121 &binary.Properties, 122 &binary.stripper.StripProperties) 123 124} 125 126// getStemWithoutSuffix returns the main section of the name to use for the symlink of 127// the main output file of this binary module. This may be derived from the module name 128// or other property overrides. 129// For the full symlink name, the `Suffix` property of a binary module must be appended. 130func (binary *binaryDecorator) getStemWithoutSuffix(ctx BaseModuleContext) string { 131 stem := ctx.baseModuleName() 132 if String(binary.Properties.Stem) != "" { 133 stem = String(binary.Properties.Stem) 134 } 135 136 return stem 137} 138 139// getStem returns the full name to use for the symlink of the main output file of this binary 140// module. This may be derived from the module name and/or other property overrides. 141func (binary *binaryDecorator) getStem(ctx BaseModuleContext) string { 142 return binary.getStemWithoutSuffix(ctx) + String(binary.Properties.Suffix) 143} 144 145// linkerDeps augments and returns the given `deps` to contain dependencies on 146// modules common to most binaries, such as bionic libraries. 147func (binary *binaryDecorator) linkerDeps(ctx DepsContext, deps Deps) Deps { 148 deps = binary.baseLinker.linkerDeps(ctx, deps) 149 if binary.baseLinker.Properties.crt() { 150 if binary.static() { 151 deps.CrtBegin = ctx.toolchain().CrtBeginStaticBinary() 152 deps.CrtEnd = ctx.toolchain().CrtEndStaticBinary() 153 } else { 154 deps.CrtBegin = ctx.toolchain().CrtBeginSharedBinary() 155 deps.CrtEnd = ctx.toolchain().CrtEndSharedBinary() 156 } 157 } 158 159 if binary.static() { 160 deps.StaticLibs = append(deps.StaticLibs, deps.SystemSharedLibs...) 161 } 162 163 if ctx.toolchain().Bionic() { 164 if binary.static() { 165 if ctx.selectedStl() == "libc++_static" { 166 deps.StaticLibs = append(deps.StaticLibs, "libm", "libc") 167 } 168 // static libraries libcompiler_rt, libc and libc_nomalloc need to be linked with 169 // --start-group/--end-group along with libgcc. If they are in deps.StaticLibs, 170 // move them to the beginning of deps.LateStaticLibs 171 var groupLibs []string 172 deps.StaticLibs, groupLibs = filterList(deps.StaticLibs, 173 []string{"libc", "libc_nomalloc", "libcompiler_rt"}) 174 deps.LateStaticLibs = append(groupLibs, deps.LateStaticLibs...) 175 } 176 177 if ctx.Os() == android.LinuxBionic && !binary.static() { 178 deps.DynamicLinker = "linker" 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 190// NewBinary builds and returns a new Module corresponding to a C++ binary. 191// Individual module implementations which comprise a C++ binary should call this function, 192// set some fields on the result, and then call the Init function. 193func NewBinary(hod android.HostOrDeviceSupported) (*Module, *binaryDecorator) { 194 return newBinary(hod) 195} 196 197func newBinary(hod android.HostOrDeviceSupported) (*Module, *binaryDecorator) { 198 module := newModule(hod, android.MultilibFirst) 199 binary := &binaryDecorator{ 200 baseLinker: NewBaseLinker(module.sanitize), 201 baseInstaller: NewBaseInstaller("bin", "", InstallInSystem), 202 } 203 module.compiler = NewBaseCompiler() 204 module.linker = binary 205 module.installer = binary 206 207 // Allow module to be added as member of an sdk/module_exports. 208 module.sdkMemberTypes = []android.SdkMemberType{ 209 ccBinarySdkMemberType, 210 } 211 return module, binary 212} 213 214// linkerInit initializes dynamic properties of the linker (such as runpath) based 215// on properties of this binary. 216func (binary *binaryDecorator) linkerInit(ctx BaseModuleContext) { 217 binary.baseLinker.linkerInit(ctx) 218 219 if ctx.Os().Linux() && ctx.Host() { 220 // Unless explicitly specified otherwise, host static binaries are built with -static 221 // if HostStaticBinaries is true for the product configuration. 222 if binary.Properties.Static_executable == nil && ctx.Config().HostStaticBinaries() { 223 binary.Properties.Static_executable = BoolPtr(true) 224 } 225 } 226 227 if ctx.Darwin() || ctx.Windows() { 228 // Static executables are not supported on Darwin or Windows 229 binary.Properties.Static_executable = nil 230 } 231} 232 233func (binary *binaryDecorator) static() bool { 234 return Bool(binary.Properties.Static_executable) 235} 236 237func (binary *binaryDecorator) staticBinary() bool { 238 return binary.static() 239} 240 241func (binary *binaryDecorator) binary() bool { 242 return true 243} 244 245// linkerFlags returns a Flags object containing linker flags that are defined 246// by this binary, or that are implied by attributes of this binary. These flags are 247// combined with the given flags. 248func (binary *binaryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags { 249 flags = binary.baseLinker.linkerFlags(ctx, flags) 250 251 // Passing -pie to clang for Windows binaries causes a warning that -pie is unused. 252 if ctx.Host() && !ctx.Windows() && !binary.static() { 253 if !ctx.Config().IsEnvTrue("DISABLE_HOST_PIE") { 254 flags.Global.LdFlags = append(flags.Global.LdFlags, "-pie") 255 } 256 } 257 258 // MinGW spits out warnings about -fPIC even for -fpie?!) being ignored because 259 // all code is position independent, and then those warnings get promoted to 260 // errors. 261 if !ctx.Windows() { 262 flags.Global.CFlags = append(flags.Global.CFlags, "-fPIE") 263 } 264 265 if ctx.toolchain().Bionic() { 266 if binary.static() { 267 // Clang driver needs -static to create static executable. 268 // However, bionic/linker uses -shared to overwrite. 269 // Linker for x86 targets does not allow coexistance of -static and -shared, 270 // so we add -static only if -shared is not used. 271 if !inList("-shared", flags.Local.LdFlags) { 272 flags.Global.LdFlags = append(flags.Global.LdFlags, "-static") 273 } 274 275 flags.Global.LdFlags = append(flags.Global.LdFlags, 276 "-nostdlib", 277 "-Bstatic", 278 "-Wl,--gc-sections", 279 ) 280 } else { // not static 281 if flags.DynamicLinker == "" { 282 if binary.Properties.DynamicLinker != "" { 283 flags.DynamicLinker = binary.Properties.DynamicLinker 284 } else { 285 switch ctx.Os() { 286 case android.Android: 287 if ctx.bootstrap() && !ctx.inRecovery() && !ctx.inRamdisk() && !ctx.inVendorRamdisk() { 288 flags.DynamicLinker = "/system/bin/bootstrap/linker" 289 } else { 290 flags.DynamicLinker = "/system/bin/linker" 291 } 292 if flags.Toolchain.Is64Bit() { 293 flags.DynamicLinker += "64" 294 } 295 case android.LinuxBionic: 296 flags.DynamicLinker = "" 297 default: 298 ctx.ModuleErrorf("unknown dynamic linker") 299 } 300 } 301 302 if ctx.Os() == android.LinuxBionic { 303 // Use the dlwrap entry point, but keep _start around so 304 // that it can be used by host_bionic_inject 305 flags.Global.LdFlags = append(flags.Global.LdFlags, 306 "-Wl,--entry=__dlwrap__start", 307 "-Wl,--undefined=_start", 308 ) 309 } 310 } 311 312 flags.Global.LdFlags = append(flags.Global.LdFlags, 313 "-pie", 314 "-nostdlib", 315 "-Bdynamic", 316 "-Wl,--gc-sections", 317 "-Wl,-z,nocopyreloc", 318 ) 319 } 320 } else { // not bionic 321 if binary.static() { 322 flags.Global.LdFlags = append(flags.Global.LdFlags, "-static") 323 } 324 if ctx.Darwin() { 325 flags.Global.LdFlags = append(flags.Global.LdFlags, "-Wl,-headerpad_max_install_names") 326 } 327 } 328 329 return flags 330} 331 332// link registers actions to link this binary, and sets various fields 333// on this binary to reflect information that should be exported up the build 334// tree (for example, exported flags and include paths). 335func (binary *binaryDecorator) link(ctx ModuleContext, 336 flags Flags, deps PathDeps, objs Objects) android.Path { 337 338 fileName := binary.getStem(ctx) + flags.Toolchain.ExecutableSuffix() 339 outputFile := android.PathForModuleOut(ctx, fileName) 340 ret := outputFile 341 342 var linkerDeps android.Paths 343 344 if flags.DynamicLinker != "" { 345 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-dynamic-linker,"+flags.DynamicLinker) 346 } else if (ctx.toolchain().Bionic() || ctx.toolchain().Musl()) && !binary.static() { 347 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--no-dynamic-linker") 348 } 349 350 if ctx.Darwin() && deps.DarwinSecondArchOutput.Valid() { 351 fatOutputFile := outputFile 352 outputFile = android.PathForModuleOut(ctx, "pre-fat", fileName) 353 transformDarwinUniversalBinary(ctx, fatOutputFile, outputFile, deps.DarwinSecondArchOutput.Path()) 354 } 355 356 builderFlags := flagsToBuilderFlags(flags) 357 stripFlags := flagsToStripFlags(flags) 358 if binary.stripper.NeedsStrip(ctx) { 359 if ctx.Darwin() { 360 stripFlags.StripUseGnuStrip = true 361 } 362 strippedOutputFile := outputFile 363 outputFile = android.PathForModuleOut(ctx, "unstripped", fileName) 364 binary.stripper.StripExecutableOrSharedLib(ctx, outputFile, strippedOutputFile, stripFlags) 365 } 366 367 binary.unstrippedOutputFile = outputFile 368 369 if String(binary.Properties.Prefix_symbols) != "" { 370 afterPrefixSymbols := outputFile 371 outputFile = android.PathForModuleOut(ctx, "unprefixed", fileName) 372 transformBinaryPrefixSymbols(ctx, String(binary.Properties.Prefix_symbols), outputFile, 373 builderFlags, afterPrefixSymbols) 374 } 375 376 outputFile = maybeInjectBoringSSLHash(ctx, outputFile, binary.Properties.Inject_bssl_hash, fileName) 377 378 // If use_version_lib is true, make an android::build::GetBuildNumber() function available. 379 if Bool(binary.baseLinker.Properties.Use_version_lib) { 380 if ctx.Host() { 381 versionedOutputFile := outputFile 382 outputFile = android.PathForModuleOut(ctx, "unversioned", fileName) 383 binary.injectVersionSymbol(ctx, outputFile, versionedOutputFile) 384 } else { 385 // When dist'ing a library or binary that has use_version_lib set, always 386 // distribute the stamped version, even for the device. 387 versionedOutputFile := android.PathForModuleOut(ctx, "versioned", fileName) 388 binary.distFiles = android.MakeDefaultDistFiles(versionedOutputFile) 389 390 if binary.stripper.NeedsStrip(ctx) { 391 out := android.PathForModuleOut(ctx, "versioned-stripped", fileName) 392 binary.distFiles = android.MakeDefaultDistFiles(out) 393 binary.stripper.StripExecutableOrSharedLib(ctx, versionedOutputFile, out, stripFlags) 394 } 395 396 binary.injectVersionSymbol(ctx, outputFile, versionedOutputFile) 397 } 398 } 399 400 var validations android.Paths 401 402 // Handle host bionic linker symbols. 403 if ctx.Os() == android.LinuxBionic && !binary.static() { 404 verifyFile := android.PathForModuleOut(ctx, "host_bionic_verify.stamp") 405 406 if !deps.DynamicLinker.Valid() { 407 panic("Non-static host bionic modules must have a dynamic linker") 408 } 409 410 binary.verifyHostBionicLinker(ctx, outputFile, deps.DynamicLinker.Path(), verifyFile) 411 validations = append(validations, verifyFile) 412 } 413 414 var sharedLibs android.Paths 415 // Ignore shared libs for static executables. 416 if !binary.static() { 417 sharedLibs = deps.EarlySharedLibs 418 sharedLibs = append(sharedLibs, deps.SharedLibs...) 419 sharedLibs = append(sharedLibs, deps.LateSharedLibs...) 420 linkerDeps = append(linkerDeps, deps.EarlySharedLibsDeps...) 421 linkerDeps = append(linkerDeps, deps.SharedLibsDeps...) 422 linkerDeps = append(linkerDeps, deps.LateSharedLibsDeps...) 423 linkerDeps = append(linkerDeps, ndkSharedLibDeps(ctx)...) 424 } 425 426 validations = append(validations, objs.tidyDepFiles...) 427 linkerDeps = append(linkerDeps, flags.LdFlagsDeps...) 428 429 if generatedLib := generateRustStaticlib(ctx, deps.RustRlibDeps); generatedLib != nil { 430 deps.StaticLibs = append(deps.StaticLibs, generatedLib) 431 } 432 433 // Register link action. 434 transformObjToDynamicBinary(ctx, objs.objFiles, sharedLibs, deps.StaticLibs, 435 deps.LateStaticLibs, deps.WholeStaticLibs, linkerDeps, deps.CrtBegin, deps.CrtEnd, true, 436 builderFlags, outputFile, nil, validations) 437 438 objs.coverageFiles = append(objs.coverageFiles, deps.StaticLibObjs.coverageFiles...) 439 objs.coverageFiles = append(objs.coverageFiles, deps.WholeStaticLibObjs.coverageFiles...) 440 binary.coverageOutputFile = transformCoverageFilesToZip(ctx, objs, binary.getStem(ctx)) 441 442 // Need to determine symlinks early since some targets (ie APEX) need this 443 // information but will not call 'install' 444 binary.setSymlinkList(ctx) 445 446 return ret 447} 448 449func (binary *binaryDecorator) unstrippedOutputFilePath() android.Path { 450 return binary.unstrippedOutputFile 451} 452 453func (binary *binaryDecorator) strippedAllOutputFilePath() android.Path { 454 panic("Not implemented.") 455} 456 457func (binary *binaryDecorator) setSymlinkList(ctx ModuleContext) { 458 for _, symlink := range binary.Properties.Symlinks { 459 binary.symlinks = append(binary.symlinks, 460 symlink+String(binary.Properties.Suffix)+ctx.toolchain().ExecutableSuffix()) 461 } 462 463 if Bool(binary.Properties.Symlink_preferred_arch) { 464 if String(binary.Properties.Suffix) == "" { 465 ctx.PropertyErrorf("symlink_preferred_arch", "must also specify suffix") 466 } 467 if ctx.TargetPrimary() { 468 // Install a symlink to the preferred architecture 469 symlinkName := binary.getStemWithoutSuffix(ctx) 470 binary.symlinks = append(binary.symlinks, symlinkName) 471 binary.preferredArchSymlink = symlinkName 472 } 473 } 474} 475 476func (binary *binaryDecorator) symlinkList() []string { 477 return binary.symlinks 478} 479 480func (binary *binaryDecorator) nativeCoverage() bool { 481 return true 482} 483 484func (binary *binaryDecorator) coverageOutputFilePath() android.OptionalPath { 485 return binary.coverageOutputFile 486} 487 488// /system/bin/linker -> /apex/com.android.runtime/bin/linker 489func (binary *binaryDecorator) installSymlinkToRuntimeApex(ctx ModuleContext, file android.Path) { 490 dir := binary.baseInstaller.installDir(ctx) 491 dirOnDevice := android.InstallPathToOnDevicePath(ctx, dir) 492 target := "/" + filepath.Join("apex", "com.android.runtime", dir.Base(), file.Base()) 493 494 ctx.InstallAbsoluteSymlink(dir, file.Base(), target) 495 binary.postInstallCmds = append(binary.postInstallCmds, makeSymlinkCmd(dirOnDevice, file.Base(), target)) 496 497 for _, symlink := range binary.symlinks { 498 ctx.InstallAbsoluteSymlink(dir, symlink, target) 499 binary.postInstallCmds = append(binary.postInstallCmds, makeSymlinkCmd(dirOnDevice, symlink, target)) 500 } 501} 502 503func (binary *binaryDecorator) install(ctx ModuleContext, file android.Path) { 504 // Bionic binaries (e.g. linker) is installed to the bootstrap subdirectory. 505 // The original path becomes a symlink to the corresponding file in the 506 // runtime APEX. 507 translatedArch := ctx.Target().NativeBridge == android.NativeBridgeEnabled 508 if InstallToBootstrap(ctx.baseModuleName(), ctx.Config()) && !ctx.Host() && ctx.directlyInAnyApex() && 509 !translatedArch && ctx.apexVariationName() == "" && !ctx.inRamdisk() && !ctx.inRecovery() && 510 !ctx.inVendorRamdisk() { 511 512 if ctx.Device() && isBionic(ctx.baseModuleName()) { 513 binary.installSymlinkToRuntimeApex(ctx, file) 514 } 515 binary.baseInstaller.subDir = "bootstrap" 516 } 517 binary.baseInstaller.install(ctx, file) 518 519 var preferredArchSymlinkPath android.OptionalPath 520 for _, symlink := range binary.symlinks { 521 installedSymlink := ctx.InstallSymlink(binary.baseInstaller.installDir(ctx), symlink, 522 binary.baseInstaller.path) 523 if symlink == binary.preferredArchSymlink { 524 // If this is the preferred arch symlink, save the installed path for use as the 525 // tool path. 526 preferredArchSymlinkPath = android.OptionalPathForPath(installedSymlink) 527 } 528 } 529 530 if ctx.Os().Class == android.Host { 531 // If the binary is multilib with a symlink to the preferred architecture, use the 532 // symlink instead of the binary because that's the more "canonical" name. 533 if preferredArchSymlinkPath.Valid() { 534 binary.toolPath = preferredArchSymlinkPath 535 } else { 536 binary.toolPath = android.OptionalPathForPath(binary.baseInstaller.path) 537 } 538 } 539} 540 541func (binary *binaryDecorator) hostToolPath() android.OptionalPath { 542 return binary.toolPath 543} 544 545func (binary *binaryDecorator) overriddenModules() []string { 546 return binary.Properties.Overrides 547} 548 549func (binary *binaryDecorator) moduleInfoJSON(ctx ModuleContext, moduleInfoJSON *android.ModuleInfoJSON) { 550 moduleInfoJSON.Class = []string{"EXECUTABLES"} 551 binary.baseLinker.moduleInfoJSON(ctx, moduleInfoJSON) 552} 553 554var _ overridable = (*binaryDecorator)(nil) 555 556func init() { 557 pctx.HostBinToolVariable("verifyHostBionicCmd", "host_bionic_verify") 558} 559 560var verifyHostBionic = pctx.AndroidStaticRule("verifyHostBionic", 561 blueprint.RuleParams{ 562 Command: "$verifyHostBionicCmd -i $in -l $linker && touch $out", 563 CommandDeps: []string{"$verifyHostBionicCmd"}, 564 }, "linker") 565 566func (binary *binaryDecorator) verifyHostBionicLinker(ctx ModuleContext, in, linker android.Path, out android.WritablePath) { 567 ctx.Build(pctx, android.BuildParams{ 568 Rule: verifyHostBionic, 569 Description: "verify host bionic", 570 Input: in, 571 Implicit: linker, 572 Output: out, 573 Args: map[string]string{ 574 "linker": linker.String(), 575 }, 576 }) 577} 578