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 // 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 ctx.toolchain().Bionic() { 150 if !Bool(binary.baseLinker.Properties.Nocrt) { 151 if binary.static() { 152 deps.CrtBegin = "crtbegin_static" 153 } else { 154 deps.CrtBegin = "crtbegin_dynamic" 155 } 156 deps.CrtEnd = "crtend_android" 157 } 158 159 if binary.static() { 160 if ctx.selectedStl() == "libc++_static" { 161 deps.StaticLibs = append(deps.StaticLibs, "libm", "libc") 162 } 163 // static libraries libcompiler_rt, libc and libc_nomalloc need to be linked with 164 // --start-group/--end-group along with libgcc. If they are in deps.StaticLibs, 165 // move them to the beginning of deps.LateStaticLibs 166 var groupLibs []string 167 deps.StaticLibs, groupLibs = filterList(deps.StaticLibs, 168 []string{"libc", "libc_nomalloc", "libcompiler_rt"}) 169 deps.LateStaticLibs = append(groupLibs, deps.LateStaticLibs...) 170 } 171 172 // Embed the linker into host bionic binaries. This is needed to support host bionic, 173 // as the linux kernel requires that the ELF interpreter referenced by PT_INTERP be 174 // either an absolute path, or relative from CWD. To work around this, we extract 175 // the load sections from the runtime linker ELF binary and embed them into each host 176 // bionic binary, omitting the PT_INTERP declaration. The kernel will treat it as a static 177 // binary, and then we use a special entry point to fix up the arguments passed by 178 // the kernel before jumping to the embedded linker. 179 if ctx.Os() == android.LinuxBionic && !binary.static() { 180 deps.DynamicLinker = "linker" 181 deps.LinkerFlagsFile = "host_bionic_linker_flags" 182 } 183 } 184 185 if !binary.static() && inList("libc", deps.StaticLibs) && !ctx.BazelConversionMode() { 186 ctx.ModuleErrorf("statically linking libc to dynamic executable, please remove libc\n" + 187 "from static libs or set static_executable: true") 188 } 189 190 return deps 191} 192 193func (binary *binaryDecorator) isDependencyRoot() bool { 194 // Binaries are always the dependency root. 195 return true 196} 197 198// NewBinary builds and returns a new Module corresponding to a C++ binary. 199// Individual module implementations which comprise a C++ binary should call this function, 200// set some fields on the result, and then call the Init function. 201func NewBinary(hod android.HostOrDeviceSupported) (*Module, *binaryDecorator) { 202 module := newModule(hod, android.MultilibFirst) 203 binary := &binaryDecorator{ 204 baseLinker: NewBaseLinker(module.sanitize), 205 baseInstaller: NewBaseInstaller("bin", "", InstallInSystem), 206 } 207 module.compiler = NewBaseCompiler() 208 module.linker = binary 209 module.installer = binary 210 211 // Allow module to be added as member of an sdk/module_exports. 212 module.sdkMemberTypes = []android.SdkMemberType{ 213 ccBinarySdkMemberType, 214 } 215 return module, binary 216} 217 218// linkerInit initializes dynamic properties of the linker (such as runpath) based 219// on properties of this binary. 220func (binary *binaryDecorator) linkerInit(ctx BaseModuleContext) { 221 binary.baseLinker.linkerInit(ctx) 222 223 if !ctx.toolchain().Bionic() { 224 if ctx.Os() == android.Linux { 225 // Unless explicitly specified otherwise, host static binaries are built with -static 226 // if HostStaticBinaries is true for the product configuration. 227 if binary.Properties.Static_executable == nil && ctx.Config().HostStaticBinaries() { 228 binary.Properties.Static_executable = BoolPtr(true) 229 } 230 } else if !ctx.Fuchsia() { 231 // Static executables are not supported on Darwin or Windows 232 binary.Properties.Static_executable = nil 233 } 234 } 235} 236 237func (binary *binaryDecorator) static() bool { 238 return Bool(binary.Properties.Static_executable) 239} 240 241func (binary *binaryDecorator) staticBinary() bool { 242 return binary.static() 243} 244 245func (binary *binaryDecorator) binary() bool { 246 return true 247} 248 249// linkerFlags returns a Flags object containing linker flags that are defined 250// by this binary, or that are implied by attributes of this binary. These flags are 251// combined with the given flags. 252func (binary *binaryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags { 253 flags = binary.baseLinker.linkerFlags(ctx, flags) 254 255 // Passing -pie to clang for Windows binaries causes a warning that -pie is unused. 256 if ctx.Host() && !ctx.Windows() && !binary.static() { 257 if !ctx.Config().IsEnvTrue("DISABLE_HOST_PIE") { 258 flags.Global.LdFlags = append(flags.Global.LdFlags, "-pie") 259 } 260 } 261 262 // MinGW spits out warnings about -fPIC even for -fpie?!) being ignored because 263 // all code is position independent, and then those warnings get promoted to 264 // errors. 265 if !ctx.Windows() { 266 flags.Global.CFlags = append(flags.Global.CFlags, "-fPIE") 267 } 268 269 if ctx.toolchain().Bionic() { 270 if binary.static() { 271 // Clang driver needs -static to create static executable. 272 // However, bionic/linker uses -shared to overwrite. 273 // Linker for x86 targets does not allow coexistance of -static and -shared, 274 // so we add -static only if -shared is not used. 275 if !inList("-shared", flags.Local.LdFlags) { 276 flags.Global.LdFlags = append(flags.Global.LdFlags, "-static") 277 } 278 279 flags.Global.LdFlags = append(flags.Global.LdFlags, 280 "-nostdlib", 281 "-Bstatic", 282 "-Wl,--gc-sections", 283 ) 284 } else { // not static 285 if flags.DynamicLinker == "" { 286 if binary.Properties.DynamicLinker != "" { 287 flags.DynamicLinker = binary.Properties.DynamicLinker 288 } else { 289 switch ctx.Os() { 290 case android.Android: 291 if ctx.bootstrap() && !ctx.inRecovery() && !ctx.inRamdisk() && !ctx.inVendorRamdisk() { 292 flags.DynamicLinker = "/system/bin/bootstrap/linker" 293 } else { 294 flags.DynamicLinker = "/system/bin/linker" 295 } 296 if flags.Toolchain.Is64Bit() { 297 flags.DynamicLinker += "64" 298 } 299 case android.LinuxBionic: 300 flags.DynamicLinker = "" 301 default: 302 ctx.ModuleErrorf("unknown dynamic linker") 303 } 304 } 305 306 if ctx.Os() == android.LinuxBionic { 307 // Use the dlwrap entry point, but keep _start around so 308 // that it can be used by host_bionic_inject 309 flags.Global.LdFlags = append(flags.Global.LdFlags, 310 "-Wl,--entry=__dlwrap__start", 311 "-Wl,--undefined=_start", 312 ) 313 } 314 } 315 316 flags.Global.LdFlags = append(flags.Global.LdFlags, 317 "-pie", 318 "-nostdlib", 319 "-Bdynamic", 320 "-Wl,--gc-sections", 321 "-Wl,-z,nocopyreloc", 322 ) 323 } 324 } else { // not bionic 325 if binary.static() { 326 flags.Global.LdFlags = append(flags.Global.LdFlags, "-static") 327 } 328 if ctx.Darwin() { 329 flags.Global.LdFlags = append(flags.Global.LdFlags, "-Wl,-headerpad_max_install_names") 330 } 331 } 332 333 return flags 334} 335 336// link registers actions to link this binary, and sets various fields 337// on this binary to reflect information that should be exported up the build 338// tree (for example, exported flags and include paths). 339func (binary *binaryDecorator) link(ctx ModuleContext, 340 flags Flags, deps PathDeps, objs Objects) android.Path { 341 342 fileName := binary.getStem(ctx) + flags.Toolchain.ExecutableSuffix() 343 outputFile := android.PathForModuleOut(ctx, fileName) 344 ret := outputFile 345 346 var linkerDeps android.Paths 347 348 // Add flags from linker flags file. 349 if deps.LinkerFlagsFile.Valid() { 350 flags.Local.LdFlags = append(flags.Local.LdFlags, "$$(cat "+deps.LinkerFlagsFile.String()+")") 351 linkerDeps = append(linkerDeps, deps.LinkerFlagsFile.Path()) 352 } 353 354 if flags.DynamicLinker != "" { 355 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-dynamic-linker,"+flags.DynamicLinker) 356 } else if ctx.toolchain().Bionic() && !binary.static() { 357 flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--no-dynamic-linker") 358 } 359 360 builderFlags := flagsToBuilderFlags(flags) 361 stripFlags := flagsToStripFlags(flags) 362 if binary.stripper.NeedsStrip(ctx) { 363 if ctx.Darwin() { 364 stripFlags.StripUseGnuStrip = true 365 } 366 strippedOutputFile := outputFile 367 outputFile = android.PathForModuleOut(ctx, "unstripped", fileName) 368 binary.stripper.StripExecutableOrSharedLib(ctx, outputFile, strippedOutputFile, stripFlags) 369 } 370 371 binary.unstrippedOutputFile = outputFile 372 373 if String(binary.Properties.Prefix_symbols) != "" { 374 afterPrefixSymbols := outputFile 375 outputFile = android.PathForModuleOut(ctx, "unprefixed", fileName) 376 transformBinaryPrefixSymbols(ctx, String(binary.Properties.Prefix_symbols), outputFile, 377 builderFlags, afterPrefixSymbols) 378 } 379 380 outputFile = maybeInjectBoringSSLHash(ctx, outputFile, binary.Properties.Inject_bssl_hash, fileName) 381 382 // If use_version_lib is true, make an android::build::GetBuildNumber() function available. 383 if Bool(binary.baseLinker.Properties.Use_version_lib) { 384 if ctx.Host() { 385 versionedOutputFile := outputFile 386 outputFile = android.PathForModuleOut(ctx, "unversioned", fileName) 387 binary.injectVersionSymbol(ctx, outputFile, versionedOutputFile) 388 } else { 389 // When dist'ing a library or binary that has use_version_lib set, always 390 // distribute the stamped version, even for the device. 391 versionedOutputFile := android.PathForModuleOut(ctx, "versioned", fileName) 392 binary.distFiles = android.MakeDefaultDistFiles(versionedOutputFile) 393 394 if binary.stripper.NeedsStrip(ctx) { 395 out := android.PathForModuleOut(ctx, "versioned-stripped", fileName) 396 binary.distFiles = android.MakeDefaultDistFiles(out) 397 binary.stripper.StripExecutableOrSharedLib(ctx, versionedOutputFile, out, stripFlags) 398 } 399 400 binary.injectVersionSymbol(ctx, outputFile, versionedOutputFile) 401 } 402 } 403 404 // Handle host bionic linker symbols. 405 if ctx.Os() == android.LinuxBionic && !binary.static() { 406 injectedOutputFile := outputFile 407 outputFile = android.PathForModuleOut(ctx, "prelinker", fileName) 408 409 if !deps.DynamicLinker.Valid() { 410 panic("Non-static host bionic modules must have a dynamic linker") 411 } 412 413 binary.injectHostBionicLinkerSymbols(ctx, outputFile, deps.DynamicLinker.Path(), injectedOutputFile) 414 } 415 416 var sharedLibs android.Paths 417 // Ignore shared libs for static executables. 418 if !binary.static() { 419 sharedLibs = deps.EarlySharedLibs 420 sharedLibs = append(sharedLibs, deps.SharedLibs...) 421 sharedLibs = append(sharedLibs, deps.LateSharedLibs...) 422 linkerDeps = append(linkerDeps, deps.EarlySharedLibsDeps...) 423 linkerDeps = append(linkerDeps, deps.SharedLibsDeps...) 424 linkerDeps = append(linkerDeps, deps.LateSharedLibsDeps...) 425 } 426 427 linkerDeps = append(linkerDeps, objs.tidyFiles...) 428 linkerDeps = append(linkerDeps, flags.LdFlagsDeps...) 429 430 // Register link action. 431 transformObjToDynamicBinary(ctx, objs.objFiles, sharedLibs, deps.StaticLibs, 432 deps.LateStaticLibs, deps.WholeStaticLibs, linkerDeps, deps.CrtBegin, deps.CrtEnd, true, 433 builderFlags, outputFile, nil) 434 435 objs.coverageFiles = append(objs.coverageFiles, deps.StaticLibObjs.coverageFiles...) 436 objs.coverageFiles = append(objs.coverageFiles, deps.WholeStaticLibObjs.coverageFiles...) 437 binary.coverageOutputFile = transformCoverageFilesToZip(ctx, objs, binary.getStem(ctx)) 438 439 // Need to determine symlinks early since some targets (ie APEX) need this 440 // information but will not call 'install' 441 for _, symlink := range binary.Properties.Symlinks { 442 binary.symlinks = append(binary.symlinks, 443 symlink+String(binary.Properties.Suffix)+ctx.toolchain().ExecutableSuffix()) 444 } 445 446 if Bool(binary.Properties.Symlink_preferred_arch) { 447 if String(binary.Properties.Suffix) == "" { 448 ctx.PropertyErrorf("symlink_preferred_arch", "must also specify suffix") 449 } 450 if ctx.TargetPrimary() { 451 // Install a symlink to the preferred architecture 452 symlinkName := binary.getStemWithoutSuffix(ctx) 453 binary.symlinks = append(binary.symlinks, symlinkName) 454 binary.preferredArchSymlink = symlinkName 455 } 456 } 457 458 return ret 459} 460 461func (binary *binaryDecorator) unstrippedOutputFilePath() android.Path { 462 return binary.unstrippedOutputFile 463} 464 465func (binary *binaryDecorator) symlinkList() []string { 466 return binary.symlinks 467} 468 469func (binary *binaryDecorator) nativeCoverage() bool { 470 return true 471} 472 473func (binary *binaryDecorator) coverageOutputFilePath() android.OptionalPath { 474 return binary.coverageOutputFile 475} 476 477// /system/bin/linker -> /apex/com.android.runtime/bin/linker 478func (binary *binaryDecorator) installSymlinkToRuntimeApex(ctx ModuleContext, file android.Path) { 479 dir := binary.baseInstaller.installDir(ctx) 480 dirOnDevice := android.InstallPathToOnDevicePath(ctx, dir) 481 target := "/" + filepath.Join("apex", "com.android.runtime", dir.Base(), file.Base()) 482 483 ctx.InstallAbsoluteSymlink(dir, file.Base(), target) 484 binary.postInstallCmds = append(binary.postInstallCmds, makeSymlinkCmd(dirOnDevice, file.Base(), target)) 485 486 for _, symlink := range binary.symlinks { 487 ctx.InstallAbsoluteSymlink(dir, symlink, target) 488 binary.postInstallCmds = append(binary.postInstallCmds, makeSymlinkCmd(dirOnDevice, symlink, target)) 489 } 490} 491 492func (binary *binaryDecorator) install(ctx ModuleContext, file android.Path) { 493 // Bionic binaries (e.g. linker) is installed to the bootstrap subdirectory. 494 // The original path becomes a symlink to the corresponding file in the 495 // runtime APEX. 496 translatedArch := ctx.Target().NativeBridge == android.NativeBridgeEnabled 497 if InstallToBootstrap(ctx.baseModuleName(), ctx.Config()) && !ctx.Host() && ctx.directlyInAnyApex() && 498 !translatedArch && ctx.apexVariationName() == "" && !ctx.inRamdisk() && !ctx.inRecovery() && 499 !ctx.inVendorRamdisk() { 500 501 if ctx.Device() && isBionic(ctx.baseModuleName()) { 502 binary.installSymlinkToRuntimeApex(ctx, file) 503 } 504 binary.baseInstaller.subDir = "bootstrap" 505 } 506 binary.baseInstaller.install(ctx, file) 507 508 var preferredArchSymlinkPath android.OptionalPath 509 for _, symlink := range binary.symlinks { 510 installedSymlink := ctx.InstallSymlink(binary.baseInstaller.installDir(ctx), symlink, 511 binary.baseInstaller.path) 512 if symlink == binary.preferredArchSymlink { 513 // If this is the preferred arch symlink, save the installed path for use as the 514 // tool path. 515 preferredArchSymlinkPath = android.OptionalPathForPath(installedSymlink) 516 } 517 } 518 519 if ctx.Os().Class == android.Host { 520 // If the binary is multilib with a symlink to the preferred architecture, use the 521 // symlink instead of the binary because that's the more "canonical" name. 522 if preferredArchSymlinkPath.Valid() { 523 binary.toolPath = preferredArchSymlinkPath 524 } else { 525 binary.toolPath = android.OptionalPathForPath(binary.baseInstaller.path) 526 } 527 } 528} 529 530func (binary *binaryDecorator) hostToolPath() android.OptionalPath { 531 return binary.toolPath 532} 533 534func init() { 535 pctx.HostBinToolVariable("hostBionicSymbolsInjectCmd", "host_bionic_inject") 536} 537 538var injectHostBionicSymbols = pctx.AndroidStaticRule("injectHostBionicSymbols", 539 blueprint.RuleParams{ 540 Command: "$hostBionicSymbolsInjectCmd -i $in -l $linker -o $out", 541 CommandDeps: []string{"$hostBionicSymbolsInjectCmd"}, 542 }, "linker") 543 544func (binary *binaryDecorator) injectHostBionicLinkerSymbols(ctx ModuleContext, in, linker android.Path, out android.WritablePath) { 545 ctx.Build(pctx, android.BuildParams{ 546 Rule: injectHostBionicSymbols, 547 Description: "inject host bionic symbols", 548 Input: in, 549 Implicit: linker, 550 Output: out, 551 Args: map[string]string{ 552 "linker": linker.String(), 553 }, 554 }) 555} 556