1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
|
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package android
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"github.com/google/blueprint"
"github.com/google/blueprint/pathtools"
)
var absSrcDir string
// PathContext is the subset of a (Module|Singleton)Context required by the
// Path methods.
type PathContext interface {
Config() Config
AddNinjaFileDeps(deps ...string)
}
type PathGlobContext interface {
GlobWithDeps(globPattern string, excludes []string) ([]string, error)
}
var _ PathContext = SingletonContext(nil)
var _ PathContext = ModuleContext(nil)
// "Null" path context is a minimal path context for a given config.
type NullPathContext struct {
config Config
}
func (NullPathContext) AddNinjaFileDeps(...string) {}
func (ctx NullPathContext) Config() Config { return ctx.config }
type ModuleInstallPathContext interface {
BaseModuleContext
InstallInData() bool
InstallInTestcases() bool
InstallInSanitizerDir() bool
InstallInRamdisk() bool
InstallInRecovery() bool
InstallInRoot() bool
InstallBypassMake() bool
InstallForceOS() (*OsType, *ArchType)
}
var _ ModuleInstallPathContext = ModuleContext(nil)
// errorfContext is the interface containing the Errorf method matching the
// Errorf method in blueprint.SingletonContext.
type errorfContext interface {
Errorf(format string, args ...interface{})
}
var _ errorfContext = blueprint.SingletonContext(nil)
// moduleErrorf is the interface containing the ModuleErrorf method matching
// the ModuleErrorf method in blueprint.ModuleContext.
type moduleErrorf interface {
ModuleErrorf(format string, args ...interface{})
}
var _ moduleErrorf = blueprint.ModuleContext(nil)
// reportPathError will register an error with the attached context. It
// attempts ctx.ModuleErrorf for a better error message first, then falls
// back to ctx.Errorf.
func reportPathError(ctx PathContext, err error) {
ReportPathErrorf(ctx, "%s", err.Error())
}
// ReportPathErrorf will register an error with the attached context. It
// attempts ctx.ModuleErrorf for a better error message first, then falls
// back to ctx.Errorf.
func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
if mctx, ok := ctx.(moduleErrorf); ok {
mctx.ModuleErrorf(format, args...)
} else if ectx, ok := ctx.(errorfContext); ok {
ectx.Errorf(format, args...)
} else {
panic(fmt.Sprintf(format, args...))
}
}
func pathContextName(ctx PathContext, module blueprint.Module) string {
if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
return x.ModuleName(module)
} else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
return x.OtherModuleName(module)
}
return "unknown"
}
type Path interface {
// Returns the path in string form
String() string
// Ext returns the extension of the last element of the path
Ext() string
// Base returns the last element of the path
Base() string
// Rel returns the portion of the path relative to the directory it was created from. For
// example, Rel on a PathsForModuleSrc would return the path relative to the module source
// directory, and OutputPath.Join("foo").Rel() would return "foo".
Rel() string
}
// WritablePath is a type of path that can be used as an output for build rules.
type WritablePath interface {
Path
// return the path to the build directory.
buildDir() string
// the writablePath method doesn't directly do anything,
// but it allows a struct to distinguish between whether or not it implements the WritablePath interface
writablePath()
}
type genPathProvider interface {
genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
}
type objPathProvider interface {
objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
}
type resPathProvider interface {
resPathWithName(ctx ModuleContext, name string) ModuleResPath
}
// GenPathWithExt derives a new file path in ctx's generated sources directory
// from the current path, but with the new extension.
func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
if path, ok := p.(genPathProvider); ok {
return path.genPathWithExt(ctx, subdir, ext)
}
ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
return PathForModuleGen(ctx)
}
// ObjPathWithExt derives a new file path in ctx's object directory from the
// current path, but with the new extension.
func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
if path, ok := p.(objPathProvider); ok {
return path.objPathWithExt(ctx, subdir, ext)
}
ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
return PathForModuleObj(ctx)
}
// ResPathWithName derives a new path in ctx's output resource directory, using
// the current path to create the directory name, and the `name` argument for
// the filename.
func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
if path, ok := p.(resPathProvider); ok {
return path.resPathWithName(ctx, name)
}
ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
return PathForModuleRes(ctx)
}
// OptionalPath is a container that may or may not contain a valid Path.
type OptionalPath struct {
valid bool
path Path
}
// OptionalPathForPath returns an OptionalPath containing the path.
func OptionalPathForPath(path Path) OptionalPath {
if path == nil {
return OptionalPath{}
}
return OptionalPath{valid: true, path: path}
}
// Valid returns whether there is a valid path
func (p OptionalPath) Valid() bool {
return p.valid
}
// Path returns the Path embedded in this OptionalPath. You must be sure that
// there is a valid path, since this method will panic if there is not.
func (p OptionalPath) Path() Path {
if !p.valid {
panic("Requesting an invalid path")
}
return p.path
}
// String returns the string version of the Path, or "" if it isn't valid.
func (p OptionalPath) String() string {
if p.valid {
return p.path.String()
} else {
return ""
}
}
// Paths is a slice of Path objects, with helpers to operate on the collection.
type Paths []Path
func (paths Paths) containsPath(path Path) bool {
for _, p := range paths {
if p == path {
return true
}
}
return false
}
// PathsForSource returns Paths rooted from SrcDir
func PathsForSource(ctx PathContext, paths []string) Paths {
ret := make(Paths, len(paths))
for i, path := range paths {
ret[i] = PathForSource(ctx, path)
}
return ret
}
// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
// found in the tree. If any are not found, they are omitted from the list,
// and dependencies are added so that we're re-run when they are added.
func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
ret := make(Paths, 0, len(paths))
for _, path := range paths {
p := ExistentPathForSource(ctx, path)
if p.Valid() {
ret = append(ret, p.Path())
}
}
return ret
}
// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
return PathsForModuleSrcExcludes(ctx, paths, nil)
}
// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
// having missing dependencies.
func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
if ctx.Config().AllowMissingDependencies() {
ctx.AddMissingDependencies(missingDeps)
} else {
for _, m := range missingDeps {
ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
}
}
return ret
}
// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
type OutputPaths []OutputPath
// Paths returns the OutputPaths as a Paths
func (p OutputPaths) Paths() Paths {
if p == nil {
return nil
}
ret := make(Paths, len(p))
for i, path := range p {
ret[i] = path
}
return ret
}
// Strings returns the string forms of the writable paths.
func (p OutputPaths) Strings() []string {
if p == nil {
return nil
}
ret := make([]string, len(p))
for i, path := range p {
ret[i] = path.String()
}
return ret
}
// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
// dependencies.
func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
prefix := pathForModuleSrc(ctx).String()
var expandedExcludes []string
if excludes != nil {
expandedExcludes = make([]string, 0, len(excludes))
}
var missingExcludeDeps []string
for _, e := range excludes {
if m, t := SrcIsModuleWithTag(e); m != "" {
module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
if module == nil {
missingExcludeDeps = append(missingExcludeDeps, m)
continue
}
if outProducer, ok := module.(OutputFileProducer); ok {
outputFiles, err := outProducer.OutputFiles(t)
if err != nil {
ctx.ModuleErrorf("path dependency %q: %s", e, err)
}
expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
} else if t != "" {
ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
} else if srcProducer, ok := module.(SourceFileProducer); ok {
expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
} else {
ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
}
} else {
expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
}
}
if paths == nil {
return nil, missingExcludeDeps
}
var missingDeps []string
expandedSrcFiles := make(Paths, 0, len(paths))
for _, s := range paths {
srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
if depErr, ok := err.(missingDependencyError); ok {
missingDeps = append(missingDeps, depErr.missingDeps...)
} else if err != nil {
reportPathError(ctx, err)
}
expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
}
return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
}
type missingDependencyError struct {
missingDeps []string
}
func (e missingDependencyError) Error() string {
return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
}
func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
excludePaths := func(paths Paths) Paths {
if len(expandedExcludes) == 0 {
return paths
}
remainder := make(Paths, 0, len(paths))
for _, p := range paths {
if !InList(p.String(), expandedExcludes) {
remainder = append(remainder, p)
}
}
return remainder
}
if m, t := SrcIsModuleWithTag(s); m != "" {
module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
if module == nil {
return nil, missingDependencyError{[]string{m}}
}
if outProducer, ok := module.(OutputFileProducer); ok {
outputFiles, err := outProducer.OutputFiles(t)
if err != nil {
return nil, fmt.Errorf("path dependency %q: %s", s, err)
}
return excludePaths(outputFiles), nil
} else if t != "" {
return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
} else if srcProducer, ok := module.(SourceFileProducer); ok {
return excludePaths(srcProducer.Srcs()), nil
} else {
return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
}
} else if pathtools.IsGlob(s) {
paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
} else {
p := pathForModuleSrc(ctx, s)
if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
ReportPathErrorf(ctx, "%s: %s", p, err.Error())
} else if !exists && !ctx.Config().testAllowNonExistentPaths {
ReportPathErrorf(ctx, "module source path %q does not exist", p)
}
if InList(p.String(), expandedExcludes) {
return nil, nil
}
return Paths{p}, nil
}
}
// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
// source directory, but strip the local source directory from the beginning of
// each string. If incDirs is false, strip paths with a trailing '/' from the list.
// It intended for use in globs that only list files that exist, so it allows '$' in
// filenames.
func pathsForModuleSrcFromFullPath(ctx EarlyModuleContext, paths []string, incDirs bool) Paths {
prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
if prefix == "./" {
prefix = ""
}
ret := make(Paths, 0, len(paths))
for _, p := range paths {
if !incDirs && strings.HasSuffix(p, "/") {
continue
}
path := filepath.Clean(p)
if !strings.HasPrefix(path, prefix) {
ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
continue
}
srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
if err != nil {
reportPathError(ctx, err)
continue
}
srcPath.basePath.rel = srcPath.path
ret = append(ret, srcPath)
}
return ret
}
// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
// local source directory. If input is nil, use the default if it exists. If input is empty, returns nil.
func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
if input != nil {
return PathsForModuleSrc(ctx, input)
}
// Use Glob so that if the default doesn't exist, a dependency is added so that when it
// is created, we're run again.
path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
return ctx.Glob(path, nil)
}
// Strings returns the Paths in string form
func (p Paths) Strings() []string {
if p == nil {
return nil
}
ret := make([]string, len(p))
for i, path := range p {
ret[i] = path.String()
}
return ret
}
func CopyOfPaths(paths Paths) Paths {
return append(Paths(nil), paths...)
}
// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
// modifies the Paths slice contents in place, and returns a subslice of the original slice.
func FirstUniquePaths(list Paths) Paths {
// 128 was chosen based on BenchmarkFirstUniquePaths results.
if len(list) > 128 {
return firstUniquePathsMap(list)
}
return firstUniquePathsList(list)
}
// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
// Paths slice contents in place, and returns a subslice of the original slice.
func SortedUniquePaths(list Paths) Paths {
unique := FirstUniquePaths(list)
sort.Slice(unique, func(i, j int) bool {
return unique[i].String() < unique[j].String()
})
return unique
}
func firstUniquePathsList(list Paths) Paths {
k := 0
outer:
for i := 0; i < len(list); i++ {
for j := 0; j < k; j++ {
if list[i] == list[j] {
continue outer
}
}
list[k] = list[i]
k++
}
return list[:k]
}
func firstUniquePathsMap(list Paths) Paths {
k := 0
seen := make(map[Path]bool, len(list))
for i := 0; i < len(list); i++ {
if seen[list[i]] {
continue
}
seen[list[i]] = true
list[k] = list[i]
k++
}
return list[:k]
}
// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
// modifies the Paths slice contents in place, and returns a subslice of the original slice.
func LastUniquePaths(list Paths) Paths {
totalSkip := 0
for i := len(list) - 1; i >= totalSkip; i-- {
skip := 0
for j := i - 1; j >= totalSkip; j-- {
if list[i] == list[j] {
skip++
} else {
list[j+skip] = list[j]
}
}
totalSkip += skip
}
return list[totalSkip:]
}
// ReversePaths returns a copy of a Paths in reverse order.
func ReversePaths(list Paths) Paths {
if list == nil {
return nil
}
ret := make(Paths, len(list))
for i := range list {
ret[i] = list[len(list)-1-i]
}
return ret
}
func indexPathList(s Path, list []Path) int {
for i, l := range list {
if l == s {
return i
}
}
return -1
}
func inPathList(p Path, list []Path) bool {
return indexPathList(p, list) != -1
}
func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
}
func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
for _, l := range list {
if predicate(l) {
filtered = append(filtered, l)
} else {
remainder = append(remainder, l)
}
}
return
}
// HasExt returns true of any of the paths have extension ext, otherwise false
func (p Paths) HasExt(ext string) bool {
for _, path := range p {
if path.Ext() == ext {
return true
}
}
return false
}
// FilterByExt returns the subset of the paths that have extension ext
func (p Paths) FilterByExt(ext string) Paths {
ret := make(Paths, 0, len(p))
for _, path := range p {
if path.Ext() == ext {
ret = append(ret, path)
}
}
return ret
}
// FilterOutByExt returns the subset of the paths that do not have extension ext
func (p Paths) FilterOutByExt(ext string) Paths {
ret := make(Paths, 0, len(p))
for _, path := range p {
if path.Ext() != ext {
ret = append(ret, path)
}
}
return ret
}
// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
// (including subdirectories) are in a contiguous subslice of the list, and can be found in
// O(log(N)) time using a binary search on the directory prefix.
type DirectorySortedPaths Paths
func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
ret := append(DirectorySortedPaths(nil), paths...)
sort.Slice(ret, func(i, j int) bool {
return ret[i].String() < ret[j].String()
})
return ret
}
// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
// that are in the specified directory and its subdirectories.
func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
prefix := filepath.Clean(dir) + "/"
start := sort.Search(len(p), func(i int) bool {
return prefix < p[i].String()
})
ret := p[start:]
end := sort.Search(len(ret), func(i int) bool {
return !strings.HasPrefix(ret[i].String(), prefix)
})
ret = ret[:end]
return Paths(ret)
}
// WritablePaths is a slice of WritablePaths, used for multiple outputs.
type WritablePaths []WritablePath
// Strings returns the string forms of the writable paths.
func (p WritablePaths) Strings() []string {
if p == nil {
return nil
}
ret := make([]string, len(p))
for i, path := range p {
ret[i] = path.String()
}
return ret
}
// Paths returns the WritablePaths as a Paths
func (p WritablePaths) Paths() Paths {
if p == nil {
return nil
}
ret := make(Paths, len(p))
for i, path := range p {
ret[i] = path
}
return ret
}
type basePath struct {
path string
config Config
rel string
}
func (p basePath) Ext() string {
return filepath.Ext(p.path)
}
func (p basePath) Base() string {
return filepath.Base(p.path)
}
func (p basePath) Rel() string {
if p.rel != "" {
return p.rel
}
return p.path
}
func (p basePath) String() string {
return p.path
}
func (p basePath) withRel(rel string) basePath {
p.path = filepath.Join(p.path, rel)
p.rel = rel
return p
}
// SourcePath is a Path representing a file path rooted from SrcDir
type SourcePath struct {
basePath
}
var _ Path = SourcePath{}
func (p SourcePath) withRel(rel string) SourcePath {
p.basePath = p.basePath.withRel(rel)
return p
}
// safePathForSource is for paths that we expect are safe -- only for use by go
// code that is embedding ninja variables in paths
func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
p, err := validateSafePath(pathComponents...)
ret := SourcePath{basePath{p, ctx.Config(), ""}}
if err != nil {
return ret, err
}
// absolute path already checked by validateSafePath
if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
return ret, fmt.Errorf("source path %q is in output", ret.String())
}
return ret, err
}
// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
p, err := validatePath(pathComponents...)
ret := SourcePath{basePath{p, ctx.Config(), ""}}
if err != nil {
return ret, err
}
// absolute path already checked by validatePath
if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
return ret, fmt.Errorf("source path %q is in output", ret.String())
}
return ret, nil
}
// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
// path does not exist.
func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
var files []string
if gctx, ok := ctx.(PathGlobContext); ok {
// Use glob to produce proper dependencies, even though we only want
// a single file.
files, err = gctx.GlobWithDeps(path.String(), nil)
} else {
var deps []string
// We cannot add build statements in this context, so we fall back to
// AddNinjaFileDeps
files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
ctx.AddNinjaFileDeps(deps...)
}
if err != nil {
return false, fmt.Errorf("glob: %s", err.Error())
}
return len(files) > 0, nil
}
// PathForSource joins the provided path components and validates that the result
// neither escapes the source dir nor is in the out dir.
// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
path, err := pathForSource(ctx, pathComponents...)
if err != nil {
reportPathError(ctx, err)
}
if pathtools.IsGlob(path.String()) {
ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
}
if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
exists, err := existsWithDependencies(ctx, path)
if err != nil {
reportPathError(ctx, err)
}
if !exists {
modCtx.AddMissingDependencies([]string{path.String()})
}
} else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
ReportPathErrorf(ctx, "%s: %s", path, err.Error())
} else if !exists && !ctx.Config().testAllowNonExistentPaths {
ReportPathErrorf(ctx, "source path %q does not exist", path)
}
return path
}
// ExistentPathForSource returns an OptionalPath with the SourcePath if the
// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
// so that the ninja file will be regenerated if the state of the path changes.
func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
path, err := pathForSource(ctx, pathComponents...)
if err != nil {
reportPathError(ctx, err)
return OptionalPath{}
}
if pathtools.IsGlob(path.String()) {
ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
return OptionalPath{}
}
exists, err := existsWithDependencies(ctx, path)
if err != nil {
reportPathError(ctx, err)
return OptionalPath{}
}
if !exists {
return OptionalPath{}
}
return OptionalPathForPath(path)
}
func (p SourcePath) String() string {
return filepath.Join(p.config.srcDir, p.path)
}
// Join creates a new SourcePath with paths... joined with the current path. The
// provided paths... may not use '..' to escape from the current path.
func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
path, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
return p.withRel(path)
}
// join is like Join but does less path validation.
func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
path, err := validateSafePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
return p.withRel(path)
}
// OverlayPath returns the overlay for `path' if it exists. This assumes that the
// SourcePath is the path to a resource overlay directory.
func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
var relDir string
if srcPath, ok := path.(SourcePath); ok {
relDir = srcPath.path
} else {
ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
return OptionalPath{}
}
dir := filepath.Join(p.config.srcDir, p.path, relDir)
// Use Glob so that we are run again if the directory is added.
if pathtools.IsGlob(dir) {
ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
}
paths, err := ctx.GlobWithDeps(dir, nil)
if err != nil {
ReportPathErrorf(ctx, "glob: %s", err.Error())
return OptionalPath{}
}
if len(paths) == 0 {
return OptionalPath{}
}
relPath := Rel(ctx, p.config.srcDir, paths[0])
return OptionalPathForPath(PathForSource(ctx, relPath))
}
// OutputPath is a Path representing an intermediates file path rooted from the build directory
type OutputPath struct {
basePath
fullPath string
}
func (p OutputPath) withRel(rel string) OutputPath {
p.basePath = p.basePath.withRel(rel)
p.fullPath = filepath.Join(p.fullPath, rel)
return p
}
func (p OutputPath) WithoutRel() OutputPath {
p.basePath.rel = filepath.Base(p.basePath.path)
return p
}
func (p OutputPath) buildDir() string {
return p.config.buildDir
}
var _ Path = OutputPath{}
var _ WritablePath = OutputPath{}
// toolDepPath is a Path representing a dependency of the build tool.
type toolDepPath struct {
basePath
}
var _ Path = toolDepPath{}
// pathForBuildToolDep returns a toolDepPath representing the given path string.
// There is no validation for the path, as it is "trusted": It may fail
// normal validation checks. For example, it may be an absolute path.
// Only use this function to construct paths for dependencies of the build
// tool invocation.
func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
return toolDepPath{basePath{path, ctx.Config(), ""}}
}
// PathForOutput joins the provided paths and returns an OutputPath that is
// validated to not escape the build dir.
// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
path, err := validatePath(pathComponents...)
if err != nil {
reportPathError(ctx, err)
}
fullPath := filepath.Join(ctx.Config().buildDir, path)
path = fullPath[len(fullPath)-len(path):]
return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
}
// PathsForOutput returns Paths rooted from buildDir
func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
ret := make(WritablePaths, len(paths))
for i, path := range paths {
ret[i] = PathForOutput(ctx, path)
}
return ret
}
func (p OutputPath) writablePath() {}
func (p OutputPath) String() string {
return p.fullPath
}
// Join creates a new OutputPath with paths... joined with the current path. The
// provided paths... may not use '..' to escape from the current path.
func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
path, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
return p.withRel(path)
}
// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
if strings.Contains(ext, "/") {
ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
}
ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
ret.rel = pathtools.ReplaceExtension(p.rel, ext)
return ret
}
// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
path, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
ret := PathForOutput(ctx, filepath.Dir(p.path), path)
ret.rel = filepath.Join(filepath.Dir(p.rel), path)
return ret
}
// PathForIntermediates returns an OutputPath representing the top-level
// intermediates directory.
func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
path, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
return PathForOutput(ctx, ".intermediates", path)
}
var _ genPathProvider = SourcePath{}
var _ objPathProvider = SourcePath{}
var _ resPathProvider = SourcePath{}
// PathForModuleSrc returns a Path representing the paths... under the
// module's local source directory.
func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
p, err := validatePath(pathComponents...)
if err != nil {
reportPathError(ctx, err)
}
paths, err := expandOneSrcPath(ctx, p, nil)
if err != nil {
if depErr, ok := err.(missingDependencyError); ok {
if ctx.Config().AllowMissingDependencies() {
ctx.AddMissingDependencies(depErr.missingDeps)
} else {
ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
}
} else {
reportPathError(ctx, err)
}
return nil
} else if len(paths) == 0 {
ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
return nil
} else if len(paths) > 1 {
ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
}
return paths[0]
}
func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
p, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
path, err := pathForSource(ctx, ctx.ModuleDir(), p)
if err != nil {
reportPathError(ctx, err)
}
path.basePath.rel = p
return path
}
// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
// will return the path relative to subDir in the module's source directory. If any input paths are not located
// inside subDir then a path error will be reported.
func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
paths = append(Paths(nil), paths...)
subDirFullPath := pathForModuleSrc(ctx, subDir)
for i, path := range paths {
rel := Rel(ctx, subDirFullPath.String(), path.String())
paths[i] = subDirFullPath.join(ctx, rel)
}
return paths
}
// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
// module's source directory. If the input path is not located inside subDir then a path error will be reported.
func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
subDirFullPath := pathForModuleSrc(ctx, subDir)
rel := Rel(ctx, subDirFullPath.String(), path.String())
return subDirFullPath.Join(ctx, rel)
}
// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
// valid path if p is non-nil.
func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
if p == nil {
return OptionalPath{}
}
return OptionalPathForPath(PathForModuleSrc(ctx, *p))
}
func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
}
func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
}
func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
// TODO: Use full directory if the new ctx is not the current ctx?
return PathForModuleRes(ctx, p.path, name)
}
// ModuleOutPath is a Path representing a module's output directory.
type ModuleOutPath struct {
OutputPath
}
var _ Path = ModuleOutPath{}
func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
}
func pathForModule(ctx ModuleContext) OutputPath {
return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
}
// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
// reference abi dump for the given module. This is not guaranteed to be valid.
func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
arches := ctx.DeviceConfig().Arches()
if len(arches) == 0 {
panic("device build with no primary arch")
}
currentArch := ctx.Arch()
archNameAndVariant := currentArch.ArchType.String()
if currentArch.ArchVariant != "" {
archNameAndVariant += "_" + currentArch.ArchVariant
}
var dirName string
if isNdk {
dirName = "ndk"
} else if isLlndkOrVndk {
dirName = "vndk"
} else {
dirName = "platform" // opt-in libs
}
binderBitness := ctx.DeviceConfig().BinderBitness()
var ext string
if isGzip {
ext = ".lsdump.gz"
} else {
ext = ".lsdump"
}
return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
version, binderBitness, archNameAndVariant, "source-based",
fileName+ext)
}
// PathForModuleOut returns a Path representing the paths... under the module's
// output directory.
func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
p, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
return ModuleOutPath{
OutputPath: pathForModule(ctx).withRel(p),
}
}
// ModuleGenPath is a Path representing the 'gen' directory in a module's output
// directory. Mainly used for generated sources.
type ModuleGenPath struct {
ModuleOutPath
}
var _ Path = ModuleGenPath{}
var _ genPathProvider = ModuleGenPath{}
var _ objPathProvider = ModuleGenPath{}
// PathForModuleGen returns a Path representing the paths... under the module's
// `gen' directory.
func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
p, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
return ModuleGenPath{
ModuleOutPath: ModuleOutPath{
OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
},
}
}
func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
// TODO: make a different path for local vs remote generated files?
return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
}
func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
}
// ModuleObjPath is a Path representing the 'obj' directory in a module's output
// directory. Used for compiled objects.
type ModuleObjPath struct {
ModuleOutPath
}
var _ Path = ModuleObjPath{}
// PathForModuleObj returns a Path representing the paths... under the module's
// 'obj' directory.
func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
p, err := validatePath(pathComponents...)
if err != nil {
reportPathError(ctx, err)
}
return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
}
// ModuleResPath is a a Path representing the 'res' directory in a module's
// output directory.
type ModuleResPath struct {
ModuleOutPath
}
var _ Path = ModuleResPath{}
// PathForModuleRes returns a Path representing the paths... under the module's
// 'res' directory.
func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
p, err := validatePath(pathComponents...)
if err != nil {
reportPathError(ctx, err)
}
return ModuleResPath{PathForModuleOut(ctx, "res", p)}
}
// InstallPath is a Path representing a installed file path rooted from the build directory
type InstallPath struct {
basePath
baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
}
func (p InstallPath) buildDir() string {
return p.config.buildDir
}
var _ Path = InstallPath{}
var _ WritablePath = InstallPath{}
func (p InstallPath) writablePath() {}
func (p InstallPath) String() string {
return filepath.Join(p.config.buildDir, p.baseDir, p.path)
}
// Join creates a new InstallPath with paths... joined with the current path. The
// provided paths... may not use '..' to escape from the current path.
func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
path, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
return p.withRel(path)
}
func (p InstallPath) withRel(rel string) InstallPath {
p.basePath = p.basePath.withRel(rel)
return p
}
// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
// i.e. out/ instead of out/soong/.
func (p InstallPath) ToMakePath() InstallPath {
p.baseDir = "../"
return p
}
// PathForModuleInstall returns a Path representing the install path for the
// module appended with paths...
func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
os := ctx.Os()
arch := ctx.Arch().ArchType
forceOS, forceArch := ctx.InstallForceOS()
if forceOS != nil {
os = *forceOS
}
if forceArch != nil {
arch = *forceArch
}
partition := modulePartition(ctx, os)
ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
ret = ret.ToMakePath()
}
return ret
}
func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
pathComponents ...string) InstallPath {
var outPaths []string
if os.Class == Device {
outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
} else {
osName := os.String()
if os == Linux {
// instead of linux_glibc
osName = "linux"
}
// SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
// and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
// to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
// Let's keep using x86 for the existing cases until we have a need to support
// other architectures.
archName := arch.String()
if os.Class == Host && (arch == X86_64 || arch == Common) {
archName = "x86"
}
outPaths = []string{"host", osName + "-" + archName, partition}
}
if debug {
outPaths = append([]string{"debug"}, outPaths...)
}
outPaths = append(outPaths, pathComponents...)
path, err := validatePath(outPaths...)
if err != nil {
reportPathError(ctx, err)
}
ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
return ret
}
func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
paths = append([]string{prefix}, paths...)
path, err := validatePath(paths...)
if err != nil {
reportPathError(ctx, err)
}
return InstallPath{basePath{path, ctx.Config(), ""}, ""}
}
func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
return pathForNdkOrSdkInstall(ctx, "ndk", paths)
}
func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
}
func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
return "/" + rel
}
func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
var partition string
if ctx.InstallInTestcases() {
// "testcases" install directory can be used for host or device modules.
partition = "testcases"
} else if os.Class == Device {
if ctx.InstallInData() {
partition = "data"
} else if ctx.InstallInRamdisk() {
if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
partition = "recovery/root/first_stage_ramdisk"
} else {
partition = "ramdisk"
}
if !ctx.InstallInRoot() {
partition += "/system"
}
} else if ctx.InstallInRecovery() {
if ctx.InstallInRoot() {
partition = "recovery/root"
} else {
// the layout of recovery partion is the same as that of system partition
partition = "recovery/root/system"
}
} else if ctx.SocSpecific() {
partition = ctx.DeviceConfig().VendorPath()
} else if ctx.DeviceSpecific() {
partition = ctx.DeviceConfig().OdmPath()
} else if ctx.ProductSpecific() {
partition = ctx.DeviceConfig().ProductPath()
} else if ctx.SystemExtSpecific() {
partition = ctx.DeviceConfig().SystemExtPath()
} else if ctx.InstallInRoot() {
partition = "root"
} else {
partition = "system"
}
if ctx.InstallInSanitizerDir() {
partition = "data/asan/" + partition
}
}
return partition
}
type InstallPaths []InstallPath
// Paths returns the InstallPaths as a Paths
func (p InstallPaths) Paths() Paths {
if p == nil {
return nil
}
ret := make(Paths, len(p))
for i, path := range p {
ret[i] = path
}
return ret
}
// Strings returns the string forms of the install paths.
func (p InstallPaths) Strings() []string {
if p == nil {
return nil
}
ret := make([]string, len(p))
for i, path := range p {
ret[i] = path.String()
}
return ret
}
// validateSafePath validates a path that we trust (may contain ninja variables).
// Ensures that each path component does not attempt to leave its component.
func validateSafePath(pathComponents ...string) (string, error) {
for _, path := range pathComponents {
path := filepath.Clean(path)
if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
return "", fmt.Errorf("Path is outside directory: %s", path)
}
}
// TODO: filepath.Join isn't necessarily correct with embedded ninja
// variables. '..' may remove the entire ninja variable, even if it
// will be expanded to multiple nested directories.
return filepath.Join(pathComponents...), nil
}
// validatePath validates that a path does not include ninja variables, and that
// each path component does not attempt to leave its component. Returns a joined
// version of each path component.
func validatePath(pathComponents ...string) (string, error) {
for _, path := range pathComponents {
if strings.Contains(path, "$") {
return "", fmt.Errorf("Path contains invalid character($): %s", path)
}
}
return validateSafePath(pathComponents...)
}
func PathForPhony(ctx PathContext, phony string) WritablePath {
if strings.ContainsAny(phony, "$/") {
ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
}
return PhonyPath{basePath{phony, ctx.Config(), ""}}
}
type PhonyPath struct {
basePath
}
func (p PhonyPath) writablePath() {}
func (p PhonyPath) buildDir() string {
return p.config.buildDir
}
var _ Path = PhonyPath{}
var _ WritablePath = PhonyPath{}
type testPath struct {
basePath
}
func (p testPath) String() string {
return p.path
}
// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
// within tests.
func PathForTesting(paths ...string) Path {
p, err := validateSafePath(paths...)
if err != nil {
panic(err)
}
return testPath{basePath{path: p, rel: p}}
}
// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
func PathsForTesting(strs ...string) Paths {
p := make(Paths, len(strs))
for i, s := range strs {
p[i] = PathForTesting(s)
}
return p
}
type testPathContext struct {
config Config
}
func (x *testPathContext) Config() Config { return x.config }
func (x *testPathContext) AddNinjaFileDeps(...string) {}
// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
// PathForOutput.
func PathContextForTesting(config Config) PathContext {
return &testPathContext{
config: config,
}
}
// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
// targetPath is not inside basePath.
func Rel(ctx PathContext, basePath string, targetPath string) string {
rel, isRel := MaybeRel(ctx, basePath, targetPath)
if !isRel {
ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
return ""
}
return rel
}
// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
// targetPath is not inside basePath.
func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
rel, isRel, err := maybeRelErr(basePath, targetPath)
if err != nil {
reportPathError(ctx, err)
}
return rel, isRel
}
func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
// filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
return "", false, nil
}
rel, err := filepath.Rel(basePath, targetPath)
if err != nil {
return "", false, err
} else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
return "", false, nil
}
return rel, true, nil
}
// Writes a file to the output directory. Attempting to write directly to the output directory
// will fail due to the sandbox of the soong_build process.
func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
return ioutil.WriteFile(absolutePath(path.String()), data, perm)
}
func absolutePath(path string) string {
if filepath.IsAbs(path) {
return path
}
return filepath.Join(absSrcDir, path)
}
// A DataPath represents the path of a file to be used as data, for example
// a test library to be installed alongside a test.
// The data file should be installed (copied from `<SrcPath>`) to
// `<install_root>/<RelativeInstallPath>/<filename>`, or
// `<install_root>/<filename>` if RelativeInstallPath is empty.
type DataPath struct {
// The path of the data file that should be copied into the data directory
SrcPath Path
// The install path of the data file, relative to the install root.
RelativeInstallPath string
}
|