xref: /aosp_15_r20/external/toolchain-utils/compiler_wrapper/sysroot_flag.go (revision 760c253c1ed00ce9abd48f8546f08516e57485fe)
1// Copyright 2019 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package main
6
7import (
8	"path/filepath"
9	"strings"
10)
11
12const skipSysrootAutodetectionFlag = "--cros-skip-wrapper-sysroot-autodetection"
13
14func processSysrootFlag(builder *commandBuilder) {
15	hadSkipSysrootMagicFlag := false
16	fromUser := false
17	userSysroot := ""
18	builder.transformArgs(func(arg builderArg) string {
19		switch {
20		// In rare cases (e.g., glibc), we want all sysroot autodetection logic to be
21		// disabled. This flag can be passed to disable that.
22		case arg.value == skipSysrootAutodetectionFlag:
23			hadSkipSysrootMagicFlag = true
24			return ""
25
26		case arg.fromUser && strings.HasPrefix(arg.value, "--sysroot="):
27			fromUser = true
28			sysrootArg := strings.Split(arg.value, "=")
29			if len(sysrootArg) == 2 {
30				userSysroot = sysrootArg[1]
31			}
32			return arg.value
33
34		default:
35			return arg.value
36		}
37	})
38
39	if hadSkipSysrootMagicFlag {
40		return
41	}
42
43	sysroot, syrootPresent := builder.env.getenv("SYSROOT")
44	if syrootPresent {
45		builder.updateEnv("SYSROOT=")
46	}
47	if sysroot == "" {
48		// Use the bundled sysroot by default.
49		sysroot = filepath.Join(builder.rootPath, "usr", builder.target.target)
50	}
51	if !fromUser {
52		builder.addPreUserArgs("--sysroot=" + sysroot)
53	} else {
54		sysroot = userSysroot
55	}
56
57	libdir := "-L" + sysroot + "/usr/lib"
58	if strings.Contains(builder.target.target, "64") {
59		libdir += "64"
60	}
61	builder.addPostUserArgs(libdir)
62}
63