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
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
)
// Initialization for any invocation.
// The usual variables.
var (
goarch string
gorootBin string
gorootBinGo string
gohostarch string
gohostos string
goos string
goarm string
go386 string
goamd64 string
gomips string
gomips64 string
goppc64 string
goroot string
goroot_final string
goextlinkenabled string
gogcflags string // For running built compiler
goldflags string
goexperiment string
workdir string
tooldir string
oldgoos string
oldgoarch string
oldgocache string
exe string
defaultcc map[string]string
defaultcxx map[string]string
defaultpkgconfig string
defaultldso string
rebuildall bool
noOpt bool
isRelease bool
vflag int // verbosity
)
// The known architectures.
var okgoarch = []string{
"386",
"amd64",
"arm",
"arm64",
"loong64",
"mips",
"mipsle",
"mips64",
"mips64le",
"ppc64",
"ppc64le",
"riscv64",
"s390x",
"sparc64",
"wasm",
}
// The known operating systems.
var okgoos = []string{
"darwin",
"dragonfly",
"illumos",
"ios",
"js",
"wasip1",
"linux",
"android",
"solaris",
"freebsd",
"nacl", // keep;
"netbsd",
"openbsd",
"plan9",
"windows",
"aix",
}
// find reports the first index of p in l[0:n], or else -1.
func find(p string, l []string) int {
for i, s := range l {
if p == s {
return i
}
}
return -1
}
// xinit handles initialization of the various global state, like goroot and goarch.
func xinit() {
b := os.Getenv("GOROOT")
if b == "" {
fatalf("$GOROOT must be set")
}
goroot = filepath.Clean(b)
gorootBin = pathf("%s/bin", goroot)
// Don't run just 'go' because the build infrastructure
// runs cmd/dist inside go/bin often, and on Windows
// it will be found in the current directory and refuse to exec.
// All exec calls rewrite "go" into gorootBinGo.
gorootBinGo = pathf("%s/bin/go", goroot)
b = os.Getenv("GOROOT_FINAL")
if b == "" {
b = goroot
}
goroot_final = b
b = os.Getenv("GOOS")
if b == "" {
b = gohostos
}
goos = b
if find(goos, okgoos) < 0 {
fatalf("unknown $GOOS %s", goos)
}
b = os.Getenv("GOARM")
if b == "" {
b = xgetgoarm()
}
goarm = b
b = os.Getenv("GO386")
if b == "" {
b = "sse2"
}
go386 = b
b = os.Getenv("GOAMD64")
if b == "" {
b = "v1"
}
goamd64 = b
b = os.Getenv("GOMIPS")
if b == "" {
b = "hardfloat"
}
gomips = b
b = os.Getenv("GOMIPS64")
if b == "" {
b = "hardfloat"
}
gomips64 = b
b = os.Getenv("GOPPC64")
if b == "" {
b = "power8"
}
goppc64 = b
if p := pathf("%s/src/all.bash", goroot); !isfile(p) {
fatalf("$GOROOT is not set correctly or not exported\n"+
"\tGOROOT=%s\n"+
"\t%s does not exist", goroot, p)
}
b = os.Getenv("GOHOSTARCH")
if b != "" {
gohostarch = b
}
if find(gohostarch, okgoarch) < 0 {
fatalf("unknown $GOHOSTARCH %s", gohostarch)
}
b = os.Getenv("GOARCH")
if b == "" {
b = gohostarch
}
goarch = b
if find(goarch, okgoarch) < 0 {
fatalf("unknown $GOARCH %s", goarch)
}
b = os.Getenv("GO_EXTLINK_ENABLED")
if b != "" {
if b != "0" && b != "1" {
fatalf("unknown $GO_EXTLINK_ENABLED %s", b)
}
goextlinkenabled = b
}
goexperiment = os.Getenv("GOEXPERIMENT")
// TODO(mdempsky): Validate known experiments?
gogcflags = os.Getenv("BOOT_GO_GCFLAGS")
goldflags = os.Getenv("BOOT_GO_LDFLAGS")
defaultcc = compilerEnv("CC", "")
defaultcxx = compilerEnv("CXX", "")
b = os.Getenv("PKG_CONFIG")
if b == "" {
b = "pkg-config"
}
defaultpkgconfig = b
defaultldso = os.Getenv("GO_LDSO")
// For tools being invoked but also for os.ExpandEnv.
os.Setenv("GO386", go386)
os.Setenv("GOAMD64", goamd64)
os.Setenv("GOARCH", goarch)
os.Setenv("GOARM", goarm)
os.Setenv("GOHOSTARCH", gohostarch)
os.Setenv("GOHOSTOS", gohostos)
os.Setenv("GOOS", goos)
os.Setenv("GOMIPS", gomips)
os.Setenv("GOMIPS64", gomips64)
os.Setenv("GOPPC64", goppc64)
os.Setenv("GOROOT", goroot)
os.Setenv("GOROOT_FINAL", goroot_final)
// Set GOBIN to GOROOT/bin. The meaning of GOBIN has drifted over time
// (see https://go.dev/issue/3269, https://go.dev/cl/183058,
// https://go.dev/issue/31576). Since we want binaries installed by 'dist' to
// always go to GOROOT/bin anyway.
os.Setenv("GOBIN", gorootBin)
// Make the environment more predictable.
os.Setenv("LANG", "C")
os.Setenv("LANGUAGE", "en_US.UTF8")
os.Unsetenv("GO111MODULE")
os.Setenv("GOENV", "off")
os.Unsetenv("GOFLAGS")
os.Setenv("GOWORK", "off")
workdir = xworkdir()
if err := os.WriteFile(pathf("%s/go.mod", workdir), []byte("module bootstrap"), 0666); err != nil {
fatalf("cannot write stub go.mod: %s", err)
}
xatexit(rmworkdir)
tooldir = pathf("%s/pkg/tool/%s_%s", goroot, gohostos, gohostarch)
goversion := findgoversion()
isRelease = strings.HasPrefix(goversion, "release.") || strings.HasPrefix(goversion, "go")
}
// compilerEnv returns a map from "goos/goarch" to the
// compiler setting to use for that platform.
// The entry for key "" covers any goos/goarch not explicitly set in the map.
// For example, compilerEnv("CC", "gcc") returns the C compiler settings
// read from $CC, defaulting to gcc.
//
// The result is a map because additional environment variables
// can be set to change the compiler based on goos/goarch settings.
// The following applies to all envNames but CC is assumed to simplify
// the presentation.
//
// If no environment variables are set, we use def for all goos/goarch.
// $CC, if set, applies to all goos/goarch but is overridden by the following.
// $CC_FOR_TARGET, if set, applies to all goos/goarch except gohostos/gohostarch,
// but is overridden by the following.
// If gohostos=goos and gohostarch=goarch, then $CC_FOR_TARGET applies even for gohostos/gohostarch.
// $CC_FOR_goos_goarch, if set, applies only to goos/goarch.
func compilerEnv(envName, def string) map[string]string {
m := map[string]string{"": def}
if env := os.Getenv(envName); env != "" {
m[""] = env
}
if env := os.Getenv(envName + "_FOR_TARGET"); env != "" {
if gohostos != goos || gohostarch != goarch {
m[gohostos+"/"+gohostarch] = m[""]
}
m[""] = env
}
for _, goos := range okgoos {
for _, goarch := range okgoarch {
if env := os.Getenv(envName + "_FOR_" + goos + "_" + goarch); env != "" {
m[goos+"/"+goarch] = env
}
}
}
return m
}
// clangos lists the operating systems where we prefer clang to gcc.
var clangos = []string{
"darwin", "ios", // macOS 10.9 and later require clang
"freebsd", // FreeBSD 10 and later do not ship gcc
"openbsd", // OpenBSD ships with GCC 4.2, which is now quite old.
}
// compilerEnvLookup returns the compiler settings for goos/goarch in map m.
// kind is "CC" or "CXX".
func compilerEnvLookup(kind string, m map[string]string, goos, goarch string) string {
if !needCC() {
return ""
}
if cc := m[goos+"/"+goarch]; cc != "" {
return cc
}
if cc := m[""]; cc != "" {
return cc
}
for _, os := range clangos {
if goos == os {
if kind == "CXX" {
return "clang++"
}
return "clang"
}
}
if kind == "CXX" {
return "g++"
}
return "gcc"
}
// rmworkdir deletes the work directory.
func rmworkdir() {
if vflag > 1 {
errprintf("rm -rf %s\n", workdir)
}
xremoveall(workdir)
}
// Remove trailing spaces.
func chomp(s string) string {
return strings.TrimRight(s, " \t\r\n")
}
// findgoversion determines the Go version to use in the version string.
// It also parses any other metadata found in the version file.
func findgoversion() string {
// The $GOROOT/VERSION file takes priority, for distributions
// without the source repo.
path := pathf("%s/VERSION", goroot)
if isfile(path) {
b := chomp(readfile(path))
// Starting in Go 1.21 the VERSION file starts with the
// version on a line by itself but then can contain other
// metadata about the release, one item per line.
if i := strings.Index(b, "\n"); i >= 0 {
rest := b[i+1:]
b = chomp(b[:i])
for _, line := range strings.Split(rest, "\n") {
f := strings.Fields(line)
if len(f) == 0 {
continue
}
switch f[0] {
default:
fatalf("VERSION: unexpected line: %s", line)
case "time":
if len(f) != 2 {
fatalf("VERSION: unexpected time line: %s", line)
}
_, err := time.Parse(time.RFC3339, f[1])
if err != nil {
fatalf("VERSION: bad time: %s", err)
}
}
}
}
// Commands such as "dist version > VERSION" will cause
// the shell to create an empty VERSION file and set dist's
// stdout to its fd. dist in turn looks at VERSION and uses
// its content if available, which is empty at this point.
// Only use the VERSION file if it is non-empty.
if b != "" {
return b
}
}
// The $GOROOT/VERSION.cache file is a cache to avoid invoking
// git every time we run this command. Unlike VERSION, it gets
// deleted by the clean command.
path = pathf("%s/VERSION.cache", goroot)
if isfile(path) {
return chomp(readfile(path))
}
// Show a nicer error message if this isn't a Git repo.
if !isGitRepo() {
fatalf("FAILED: not a Git repo; must put a VERSION file in $GOROOT")
}
// Otherwise, use Git.
//
// Include 1.x base version, hash, and date in the version.
//
// Note that we lightly parse internal/goversion/goversion.go to
// obtain the base version. We can't just import the package,
// because cmd/dist is built with a bootstrap GOROOT which could
// be an entirely different version of Go. We assume
// that the file contains "const Version = <Integer>".
goversionSource := readfile(pathf("%s/src/internal/goversion/goversion.go", goroot))
m := regexp.MustCompile(`(?m)^const Version = (\d+)`).FindStringSubmatch(goversionSource)
if m == nil {
fatalf("internal/goversion/goversion.go does not contain 'const Version = ...'")
}
version := fmt.Sprintf("devel go1.%s-", m[1])
version += chomp(run(goroot, CheckExit, "git", "log", "-n", "1", "--format=format:%h %cd", "HEAD"))
// Cache version.
writefile(version, path, 0)
return version
}
// isGitRepo reports whether the working directory is inside a Git repository.
func isGitRepo() bool {
// NB: simply checking the exit code of `git rev-parse --git-dir` would
// suffice here, but that requires deviating from the infrastructure
// provided by `run`.
gitDir := chomp(run(goroot, 0, "git", "rev-parse", "--git-dir"))
if !filepath.IsAbs(gitDir) {
gitDir = filepath.Join(goroot, gitDir)
}
return isdir(gitDir)
}
/*
* Initial tree setup.
*/
// The old tools that no longer live in $GOBIN or $GOROOT/bin.
var oldtool = []string{
"5a", "5c", "5g", "5l",
"6a", "6c", "6g", "6l",
"8a", "8c", "8g", "8l",
"9a", "9c", "9g", "9l",
"6cov",
"6nm",
"6prof",
"cgo",
"ebnflint",
"goapi",
"gofix",
"goinstall",
"gomake",
"gopack",
"gopprof",
"gotest",
"gotype",
"govet",
"goyacc",
"quietgcc",
}
// Unreleased directories (relative to $GOROOT) that should
// not be in release branches.
var unreleased = []string{
"src/cmd/newlink",
"src/cmd/objwriter",
"src/debug/goobj",
"src/old",
}
// setup sets up the tree for the initial build.
func setup() {
// Create bin directory.
if p := pathf("%s/bin", goroot); !isdir(p) {
xmkdir(p)
}
// Create package directory.
if p := pathf("%s/pkg", goroot); !isdir(p) {
xmkdir(p)
}
goosGoarch := pathf("%s/pkg/%s_%s", goroot, gohostos, gohostarch)
if rebuildall {
xremoveall(goosGoarch)
}
xmkdirall(goosGoarch)
xatexit(func() {
if files := xreaddir(goosGoarch); len(files) == 0 {
xremove(goosGoarch)
}
})
if goos != gohostos || goarch != gohostarch {
p := pathf("%s/pkg/%s_%s", goroot, goos, goarch)
if rebuildall {
xremoveall(p)
}
xmkdirall(p)
}
// Create object directory.
// We used to use it for C objects.
// Now we use it for the build cache, to separate dist's cache
// from any other cache the user might have, and for the location
// to build the bootstrap versions of the standard library.
obj := pathf("%s/pkg/obj", goroot)
if !isdir(obj) {
xmkdir(obj)
}
xatexit(func() { xremove(obj) })
// Create build cache directory.
objGobuild := pathf("%s/pkg/obj/go-build", goroot)
if rebuildall {
xremoveall(objGobuild)
}
xmkdirall(objGobuild)
xatexit(func() { xremoveall(objGobuild) })
// Create directory for bootstrap versions of standard library .a files.
objGoBootstrap := pathf("%s/pkg/obj/go-bootstrap", goroot)
if rebuildall {
xremoveall(objGoBootstrap)
}
xmkdirall(objGoBootstrap)
xatexit(func() { xremoveall(objGoBootstrap) })
// Create tool directory.
// We keep it in pkg/, just like the object directory above.
if rebuildall {
xremoveall(tooldir)
}
xmkdirall(tooldir)
// Remove tool binaries from before the tool/gohostos_gohostarch
xremoveall(pathf("%s/bin/tool", goroot))
// Remove old pre-tool binaries.
for _, old := range oldtool {
xremove(pathf("%s/bin/%s", goroot, old))
}
// Special release-specific setup.
if isRelease {
// Make sure release-excluded things are excluded.
for _, dir := range unreleased {
if p := pathf("%s/%s", goroot, dir); isdir(p) {
fatalf("%s should not exist in release build", p)
}
}
}
}
/*
* Tool building
*/
// mustLinkExternal is a copy of internal/platform.MustLinkExternal,
// duplicated here to avoid version skew in the MustLinkExternal function
// during bootstrapping.
func mustLinkExternal(goos, goarch string, cgoEnabled bool) bool {
if cgoEnabled {
switch goarch {
case "loong64", "mips", "mipsle", "mips64", "mips64le":
// Internally linking cgo is incomplete on some architectures.
// https://golang.org/issue/14449
return true
case "arm64":
if goos == "windows" {
// windows/arm64 internal linking is not implemented.
return true
}
case "ppc64":
// Big Endian PPC64 cgo internal linking is not implemented for aix or linux.
if goos == "aix" || goos == "linux" {
return true
}
}
switch goos {
case "android":
return true
case "dragonfly":
// It seems that on Dragonfly thread local storage is
// set up by the dynamic linker, so internal cgo linking
// doesn't work. Test case is "go test runtime/cgo".
return true
}
}
switch goos {
case "android":
if goarch != "arm64" {
return true
}
case "ios":
if goarch == "arm64" {
return true
}
}
return false
}
// depsuffix records the allowed suffixes for source files.
var depsuffix = []string{
".s",
".go",
}
// gentab records how to generate some trivial files.
// Files listed here should also be listed in ../distpack/pack.go's srcArch.Remove list.
var gentab = []struct {
pkg string // Relative to $GOROOT/src
file string
gen func(dir, file string)
}{
{"go/build", "zcgo.go", mkzcgo},
{"cmd/go/internal/cfg", "zdefaultcc.go", mkzdefaultcc},
{"runtime/internal/sys", "zversion.go", mkzversion},
{"time/tzdata", "zzipdata.go", mktzdata},
}
// installed maps from a dir name (as given to install) to a chan
// closed when the dir's package is installed.
var installed = make(map[string]chan struct{})
var installedMu sync.Mutex
func install(dir string) {
<-startInstall(dir)
}
func startInstall(dir string) chan struct{} {
installedMu.Lock()
ch := installed[dir]
if ch == nil {
ch = make(chan struct{})
installed[dir] = ch
go runInstall(dir, ch)
}
installedMu.Unlock()
return ch
}
// runInstall installs the library, package, or binary associated with pkg,
// which is relative to $GOROOT/src.
func runInstall(pkg string, ch chan struct{}) {
if pkg == "net" || pkg == "os/user" || pkg == "crypto/x509" {
fatalf("go_bootstrap cannot depend on cgo package %s", pkg)
}
defer close(ch)
if pkg == "unsafe" {
return
}
if vflag > 0 {
if goos != gohostos || goarch != gohostarch {
errprintf("%s (%s/%s)\n", pkg, goos, goarch)
} else {
errprintf("%s\n", pkg)
}
}
workdir := pathf("%s/%s", workdir, pkg)
xmkdirall(workdir)
var clean []string
defer func() {
for _, name := range clean {
xremove(name)
}
}()
// dir = full path to pkg.
dir := pathf("%s/src/%s", goroot, pkg)
name := filepath.Base(dir)
// ispkg predicts whether the package should be linked as a binary, based
// on the name. There should be no "main" packages in vendor, since
// 'go mod vendor' will only copy imported packages there.
ispkg := !strings.HasPrefix(pkg, "cmd/") || strings.Contains(pkg, "/internal/") || strings.Contains(pkg, "/vendor/")
// Start final link command line.
// Note: code below knows that link.p[targ] is the target.
var (
link []string
targ int
ispackcmd bool
)
if ispkg {
// Go library (package).
ispackcmd = true
link = []string{"pack", packagefile(pkg)}
targ = len(link) - 1
xmkdirall(filepath.Dir(link[targ]))
} else {
// Go command.
elem := name
if elem == "go" {
elem = "go_bootstrap"
}
link = []string{pathf("%s/link", tooldir)}
if goos == "android" {
link = append(link, "-buildmode=pie")
}
if goldflags != "" {
link = append(link, goldflags)
}
link = append(link, "-extld="+compilerEnvLookup("CC", defaultcc, goos, goarch))
link = append(link, "-L="+pathf("%s/pkg/obj/go-bootstrap/%s_%s", goroot, goos, goarch))
link = append(link, "-o", pathf("%s/%s%s", tooldir, elem, exe))
targ = len(link) - 1
}
ttarg := mtime(link[targ])
// Gather files that are sources for this target.
// Everything in that directory, and any target-specific
// additions.
files := xreaddir(dir)
// Remove files beginning with . or _,
// which are likely to be editor temporary files.
// This is the same heuristic build.ScanDir uses.
// There do exist real C files beginning with _,
// so limit that check to just Go files.
files = filter(files, func(p string) bool {
return !strings.HasPrefix(p, ".") && (!strings.HasPrefix(p, "_") || !strings.HasSuffix(p, ".go"))
})
// Add generated files for this package.
for _, gt := range gentab {
if gt.pkg == pkg {
files = append(files, gt.file)
}
}
files = uniq(files)
// Convert to absolute paths.
for i, p := range files {
if !filepath.IsAbs(p) {
files[i] = pathf("%s/%s", dir, p)
}
}
// Is the target up-to-date?
var gofiles, sfiles []string
stale := rebuildall
files = filter(files, func(p string) bool {
for _, suf := range depsuffix {
if strings.HasSuffix(p, suf) {
goto ok
}
}
return false
ok:
t := mtime(p)
if !t.IsZero() && !strings.HasSuffix(p, ".a") && !shouldbuild(p, pkg) {
return false
}
if strings.HasSuffix(p, ".go") {
gofiles = append(gofiles, p)
} else if strings.HasSuffix(p, ".s") {
sfiles = append(sfiles, p)
}
if t.After(ttarg) {
stale = true
}
return true
})
// If there are no files to compile, we're done.
if len(files) == 0 {
return
}
if !stale {
return
}
// For package runtime, copy some files into the work space.
if pkg == "runtime" {
xmkdirall(pathf("%s/pkg/include", goroot))
// For use by assembly and C files.
copyfile(pathf("%s/pkg/include/textflag.h", goroot),
pathf("%s/src/runtime/textflag.h", goroot), 0)
copyfile(pathf("%s/pkg/include/funcdata.h", goroot),
pathf("%s/src/runtime/funcdata.h", goroot), 0)
copyfile(pathf("%s/pkg/include/asm_ppc64x.h", goroot),
pathf("%s/src/runtime/asm_ppc64x.h", goroot), 0)
copyfile(pathf("%s/pkg/include/asm_amd64.h", goroot),
pathf("%s/src/runtime/asm_amd64.h", goroot), 0)
}
// Generate any missing files; regenerate existing ones.
for _, gt := range gentab {
if gt.pkg != pkg {
continue
}
p := pathf("%s/%s", dir, gt.file)
if vflag > 1 {
errprintf("generate %s\n", p)
}
gt.gen(dir, p)
// Do not add generated file to clean list.
// In runtime, we want to be able to
// build the package with the go tool,
// and it assumes these generated files already
// exist (it does not know how to build them).
// The 'clean' command can remove
// the generated files.
}
// Resolve imported packages to actual package paths.
// Make sure they're installed.
importMap := make(map[string]string)
for _, p := range gofiles {
for _, imp := range readimports(p) {
if imp == "C" {
fatalf("%s imports C", p)
}
importMap[imp] = resolveVendor(imp, dir)
}
}
sortedImports := make([]string, 0, len(importMap))
for imp := range importMap {
sortedImports = append(sortedImports, imp)
}
sort.Strings(sortedImports)
for _, dep := range importMap {
if dep == "C" {
fatalf("%s imports C", pkg)
}
startInstall(dep)
}
for _, dep := range importMap {
install(dep)
}
if goos != gohostos || goarch != gohostarch {
// We've generated the right files; the go command can do the build.
if vflag > 1 {
errprintf("skip build for cross-compile %s\n", pkg)
}
return
}
asmArgs := []string{
pathf("%s/asm", tooldir),
"-I", workdir,
"-I", pathf("%s/pkg/include", goroot),
"-D", "GOOS_" + goos,
"-D", "GOARCH_" + goarch,
"-D", "GOOS_GOARCH_" + goos + "_" + goarch,
"-p", pkg,
}
if goarch == "mips" || goarch == "mipsle" {
// Define GOMIPS_value from gomips.
asmArgs = append(asmArgs, "-D", "GOMIPS_"+gomips)
}
if goarch == "mips64" || goarch == "mips64le" {
// Define GOMIPS64_value from gomips64.
asmArgs = append(asmArgs, "-D", "GOMIPS64_"+gomips64)
}
if goarch == "ppc64" || goarch == "ppc64le" {
// We treat each powerpc version as a superset of functionality.
switch goppc64 {
case "power10":
asmArgs = append(asmArgs, "-D", "GOPPC64_power10")
fallthrough
case "power9":
asmArgs = append(asmArgs, "-D", "GOPPC64_power9")
fallthrough
default: // This should always be power8.
asmArgs = append(asmArgs, "-D", "GOPPC64_power8")
}
}
goasmh := pathf("%s/go_asm.h", workdir)
// Collect symabis from assembly code.
var symabis string
if len(sfiles) > 0 {
symabis = pathf("%s/symabis", workdir)
var wg sync.WaitGroup
asmabis := append(asmArgs[:len(asmArgs):len(asmArgs)], "-gensymabis", "-o", symabis)
asmabis = append(asmabis, sfiles...)
if err := os.WriteFile(goasmh, nil, 0666); err != nil {
fatalf("cannot write empty go_asm.h: %s", err)
}
bgrun(&wg, dir, asmabis...)
bgwait(&wg)
}
// Build an importcfg file for the compiler.
buf := &bytes.Buffer{}
for _, imp := range sortedImports {
if imp == "unsafe" {
continue
}
dep := importMap[imp]
if imp != dep {
fmt.Fprintf(buf, "importmap %s=%s\n", imp, dep)
}
fmt.Fprintf(buf, "packagefile %s=%s\n", dep, packagefile(dep))
}
importcfg := pathf("%s/importcfg", workdir)
if err := os.WriteFile(importcfg, buf.Bytes(), 0666); err != nil {
fatalf("cannot write importcfg file: %v", err)
}
var archive string
// The next loop will compile individual non-Go files.
// Hand the Go files to the compiler en masse.
// For packages containing assembly, this writes go_asm.h, which
// the assembly files will need.
pkgName := pkg
if strings.HasPrefix(pkg, "cmd/") && strings.Count(pkg, "/") == 1 {
pkgName = "main"
}
b := pathf("%s/_go_.a", workdir)
clean = append(clean, b)
if !ispackcmd {
link = append(link, b)
} else {
archive = b
}
// Compile Go code.
compile := []string{pathf("%s/compile", tooldir), "-std", "-pack", "-o", b, "-p", pkgName, "-importcfg", importcfg}
if gogcflags != "" {
compile = append(compile, strings.Fields(gogcflags)...)
}
if len(sfiles) > 0 {
compile = append(compile, "-asmhdr", goasmh)
}
if symabis != "" {
compile = append(compile, "-symabis", symabis)
}
if goos == "android" {
compile = append(compile, "-shared")
}
compile = append(compile, gofiles...)
var wg sync.WaitGroup
// We use bgrun and immediately wait for it instead of calling run() synchronously.
// This executes all jobs through the bgwork channel and allows the process
// to exit cleanly in case an error occurs.
bgrun(&wg, dir, compile...)
bgwait(&wg)
// Compile the files.
for _, p := range sfiles {
// Assembly file for a Go package.
compile := asmArgs[:len(asmArgs):len(asmArgs)]
doclean := true
b := pathf("%s/%s", workdir, filepath.Base(p))
// Change the last character of the output file (which was c or s).
b = b[:len(b)-1] + "o"
compile = append(compile, "-o", b, p)
bgrun(&wg, dir, compile...)
link = append(link, b)
if doclean {
clean = append(clean, b)
}
}
bgwait(&wg)
if ispackcmd {
xremove(link[targ])
dopack(link[targ], archive, link[targ+1:])
return
}
// Remove target before writing it.
xremove(link[targ])
bgrun(&wg, "", link...)
bgwait(&wg)
}
// packagefile returns the path to a compiled .a file for the given package
// path. Paths may need to be resolved with resolveVendor first.
func packagefile(pkg string) string {
return pathf("%s/pkg/obj/go-bootstrap/%s_%s/%s.a", goroot, goos, goarch, pkg)
}
// unixOS is the set of GOOS values matched by the "unix" build tag.
// This is the same list as in go/build/syslist.go and
// cmd/go/internal/imports/build.go.
var unixOS = map[string]bool{
"aix": true,
"android": true,
"darwin": true,
"dragonfly": true,
"freebsd": true,
"hurd": true,
"illumos": true,
"ios": true,
"linux": true,
"netbsd": true,
"openbsd": true,
"solaris": true,
}
// matchtag reports whether the tag matches this build.
func matchtag(tag string) bool {
switch tag {
case "gc", "cmd_go_bootstrap", "go1.1":
return true
case "linux":
return goos == "linux" || goos == "android"
case "solaris":
return goos == "solaris" || goos == "illumos"
case "darwin":
return goos == "darwin" || goos == "ios"
case goos, goarch:
return true
case "unix":
return unixOS[goos]
default:
return false
}
}
// shouldbuild reports whether we should build this file.
// It applies the same rules that are used with context tags
// in package go/build, except it's less picky about the order
// of GOOS and GOARCH.
// We also allow the special tag cmd_go_bootstrap.
// See ../go/bootstrap.go and package go/build.
func shouldbuild(file, pkg string) bool {
// Check file name for GOOS or GOARCH.
name := filepath.Base(file)
excluded := func(list []string, ok string) bool {
for _, x := range list {
if x == ok || (ok == "android" && x == "linux") || (ok == "illumos" && x == "solaris") || (ok == "ios" && x == "darwin") {
continue
}
i := strings.Index(name, x)
if i <= 0 || name[i-1] != '_' {
continue
}
i += len(x)
if i == len(name) || name[i] == '.' || name[i] == '_' {
return true
}
}
return false
}
if excluded(okgoos, goos) || excluded(okgoarch, goarch) {
return false
}
// Omit test files.
if strings.Contains(name, "_test") {
return false
}
// Check file contents for //go:build lines.
for _, p := range strings.Split(readfile(file), "\n") {
p = strings.TrimSpace(p)
if p == "" {
continue
}
code := p
i := strings.Index(code, "//")
if i > 0 {
code = strings.TrimSpace(code[:i])
}
if code == "package documentation" {
return false
}
if code == "package main" && pkg != "cmd/go" && pkg != "cmd/cgo" {
return false
}
if !strings.HasPrefix(p, "//") {
break
}
if strings.HasPrefix(p, "//go:build ") {
matched, err := matchexpr(p[len("//go:build "):])
if err != nil {
errprintf("%s: %v", file, err)
}
return matched
}
}
return true
}
// copyfile copies the file src to dst, via memory (so only good for small files).
func copyfile(dst, src string, flag int) {
if vflag > 1 {
errprintf("cp %s %s\n", src, dst)
}
writefile(readfile(src), dst, flag)
}
// dopack copies the package src to dst,
// appending the files listed in extra.
// The archive format is the traditional Unix ar format.
func dopack(dst, src string, extra []string) {
bdst := bytes.NewBufferString(readfile(src))
for _, file := range extra {
b := readfile(file)
// find last path element for archive member name
i := strings.LastIndex(file, "/") + 1
j := strings.LastIndex(file, `\`) + 1
if i < j {
i = j
}
fmt.Fprintf(bdst, "%-16.16s%-12d%-6d%-6d%-8o%-10d`\n", file[i:], 0, 0, 0, 0644, len(b))
bdst.WriteString(b)
if len(b)&1 != 0 {
bdst.WriteByte(0)
}
}
writefile(bdst.String(), dst, 0)
}
func clean() {
generated := []byte(generatedHeader)
// Remove generated source files.
filepath.WalkDir(pathf("%s/src", goroot), func(path string, d fs.DirEntry, err error) error {
switch {
case err != nil:
// ignore
case d.IsDir() && (d.Name() == "vendor" || d.Name() == "testdata"):
return filepath.SkipDir
case d.IsDir() && d.Name() != "dist":
// Remove generated binary named for directory, but not dist out from under us.
exe := filepath.Join(path, d.Name())
if info, err := os.Stat(exe); err == nil && !info.IsDir() {
xremove(exe)
}
xremove(exe + ".exe")
case !d.IsDir() && strings.HasPrefix(d.Name(), "z"):
// Remove generated file, identified by marker string.
head := make([]byte, 512)
if f, err := os.Open(path); err == nil {
io.ReadFull(f, head)
f.Close()
}
if bytes.HasPrefix(head, generated) {
xremove(path)
}
}
return nil
})
if rebuildall {
// Remove object tree.
xremoveall(pathf("%s/pkg/obj/%s_%s", goroot, gohostos, gohostarch))
// Remove installed packages and tools.
xremoveall(pathf("%s/pkg/%s_%s", goroot, gohostos, gohostarch))
xremoveall(pathf("%s/pkg/%s_%s", goroot, goos, goarch))
xremoveall(pathf("%s/pkg/%s_%s_race", goroot, gohostos, gohostarch))
xremoveall(pathf("%s/pkg/%s_%s_race", goroot, goos, goarch))
xremoveall(tooldir)
// Remove cached version info.
xremove(pathf("%s/VERSION.cache", goroot))
// Remove distribution packages.
xremoveall(pathf("%s/pkg/distpack", goroot))
}
}
/*
* command implementations
*/
// The env command prints the default environment.
func cmdenv() {
path := flag.Bool("p", false, "emit updated PATH")
plan9 := flag.Bool("9", gohostos == "plan9", "emit plan 9 syntax")
windows := flag.Bool("w", gohostos == "windows", "emit windows syntax")
xflagparse(0)
format := "%s=\"%s\";\n" // Include ; to separate variables when 'dist env' output is used with eval.
switch {
case *plan9:
format = "%s='%s'\n"
case *windows:
format = "set %s=%s\r\n"
}
xprintf(format, "GO111MODULE", "")
xprintf(format, "GOARCH", goarch)
xprintf(format, "GOBIN", gorootBin)
xprintf(format, "GODEBUG", os.Getenv("GODEBUG"))
xprintf(format, "GOENV", "off")
xprintf(format, "GOFLAGS", "")
xprintf(format, "GOHOSTARCH", gohostarch)
xprintf(format, "GOHOSTOS", gohostos)
xprintf(format, "GOOS", goos)
xprintf(format, "GOPROXY", os.Getenv("GOPROXY"))
xprintf(format, "GOROOT", goroot)
xprintf(format, "GOTMPDIR", os.Getenv("GOTMPDIR"))
xprintf(format, "GOTOOLDIR", tooldir)
if goarch == "arm" {
xprintf(format, "GOARM", goarm)
}
if goarch == "386" {
xprintf(format, "GO386", go386)
}
if goarch == "amd64" {
xprintf(format, "GOAMD64", goamd64)
}
if goarch == "mips" || goarch == "mipsle" {
xprintf(format, "GOMIPS", gomips)
}
if goarch == "mips64" || goarch == "mips64le" {
xprintf(format, "GOMIPS64", gomips64)
}
if goarch == "ppc64" || goarch == "ppc64le" {
xprintf(format, "GOPPC64", goppc64)
}
xprintf(format, "GOWORK", "off")
if *path {
sep := ":"
if gohostos == "windows" {
sep = ";"
}
xprintf(format, "PATH", fmt.Sprintf("%s%s%s", gorootBin, sep, os.Getenv("PATH")))
// Also include $DIST_UNMODIFIED_PATH with the original $PATH
// for the internal needs of "dist banner", along with export
// so that it reaches the dist process. See its comment below.
var exportFormat string
if !*windows && !*plan9 {
exportFormat = "export " + format
} else {
exportFormat = format
}
xprintf(exportFormat, "DIST_UNMODIFIED_PATH", os.Getenv("PATH"))
}
}
var (
timeLogEnabled = os.Getenv("GOBUILDTIMELOGFILE") != ""
timeLogMu sync.Mutex
timeLogFile *os.File
timeLogStart time.Time
)
func timelog(op, name string) {
if !timeLogEnabled {
return
}
timeLogMu.Lock()
defer timeLogMu.Unlock()
if timeLogFile == nil {
f, err := os.OpenFile(os.Getenv("GOBUILDTIMELOGFILE"), os.O_RDWR|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 100)
n, _ := f.Read(buf)
s := string(buf[:n])
if i := strings.Index(s, "\n"); i >= 0 {
s = s[:i]
}
i := strings.Index(s, " start")
if i < 0 {
log.Fatalf("time log %s does not begin with start line", os.Getenv("GOBUILDTIMELOGFILE"))
}
t, err := time.Parse(time.UnixDate, s[:i])
if err != nil {
log.Fatalf("cannot parse time log line %q: %v", s, err)
}
timeLogStart = t
timeLogFile = f
}
t := time.Now()
fmt.Fprintf(timeLogFile, "%s %+.1fs %s %s\n", t.Format(time.UnixDate), t.Sub(timeLogStart).Seconds(), op, name)
}
// toolenv returns the environment to use when building commands in cmd.
//
// This is a function instead of a variable because the exact toolenv depends
// on the GOOS and GOARCH, and (at least for now) those are modified in place
// to switch between the host and target configurations when cross-compiling.
func toolenv() []string {
var env []string
if !mustLinkExternal(goos, goarch, false) {
// Unless the platform requires external linking,
// we disable cgo to get static binaries for cmd/go and cmd/pprof,
// so that they work on systems without the same dynamic libraries
// as the original build system.
env = append(env, "CGO_ENABLED=0")
}
if isRelease || os.Getenv("GO_BUILDER_NAME") != "" {
// Add -trimpath for reproducible builds of releases.
// Include builders so that -trimpath is well-tested ahead of releases.
// Do not include local development, so that people working in the
// main branch for day-to-day work on the Go toolchain itself can
// still have full paths for stack traces for compiler crashes and the like.
env = append(env, "GOFLAGS=-trimpath -ldflags=-w -gcflags=cmd/...=-dwarf=false")
}
return env
}
var toolchain = []string{"cmd/asm", "cmd/cgo", "cmd/compile", "cmd/link"}
// The bootstrap command runs a build from scratch,
// stopping at having installed the go_bootstrap command.
//
// WARNING: This command runs after cmd/dist is built with the Go bootstrap toolchain.
// It rebuilds and installs cmd/dist with the new toolchain, so other
// commands (like "go tool dist test" in run.bash) can rely on bug fixes
// made since the Go bootstrap version, but this function cannot.
func cmdbootstrap() {
timelog("start", "dist bootstrap")
defer timelog("end", "dist bootstrap")
var debug, distpack, force, noBanner, noClean bool
flag.BoolVar(&rebuildall, "a", rebuildall, "rebuild all")
flag.BoolVar(&debug, "d", debug, "enable debugging of bootstrap process")
flag.BoolVar(&distpack, "distpack", distpack, "write distribution files to pkg/distpack")
flag.BoolVar(&force, "force", force, "build even if the port is marked as broken")
flag.BoolVar(&noBanner, "no-banner", noBanner, "do not print banner")
flag.BoolVar(&noClean, "no-clean", noClean, "print deprecation warning")
xflagparse(0)
if noClean {
xprintf("warning: --no-clean is deprecated and has no effect; use 'go install std cmd' instead\n")
}
// Don't build broken ports by default.
if broken[goos+"/"+goarch] && !force {
fatalf("build stopped because the port %s/%s is marked as broken\n\n"+
"Use the -force flag to build anyway.\n", goos, goarch)
}
// Set GOPATH to an internal directory. We shouldn't actually
// need to store files here, since the toolchain won't
// depend on modules outside of vendor directories, but if
// GOPATH points somewhere else (e.g., to GOROOT), the
// go tool may complain.
os.Setenv("GOPATH", pathf("%s/pkg/obj/gopath", goroot))
// Use a build cache separate from the default user one.
// Also one that will be wiped out during startup, so that
// make.bash really does start from a clean slate.
oldgocache = os.Getenv("GOCACHE")
os.Setenv("GOCACHE", pathf("%s/pkg/obj/go-build", goroot))
// Disable GOEXPERIMENT when building toolchain1 and
// go_bootstrap. We don't need any experiments for the
// bootstrap toolchain, and this lets us avoid duplicating the
// GOEXPERIMENT-related build logic from cmd/go here. If the
// bootstrap toolchain is < Go 1.17, it will ignore this
// anyway since GOEXPERIMENT is baked in; otherwise it will
// pick it up from the environment we set here. Once we're
// using toolchain1 with dist as the build system, we need to
// override this to keep the experiments assumed by the
// toolchain and by dist consistent. Once go_bootstrap takes
// over the build process, we'll set this back to the original
// GOEXPERIMENT.
os.Setenv("GOEXPERIMENT", "none")
if debug {
// cmd/buildid is used in debug mode.
toolchain = append(toolchain, "cmd/buildid")
}
if isdir(pathf("%s/src/pkg", goroot)) {
fatalf("\n\n"+
"The Go package sources have moved to $GOROOT/src.\n"+
"*** %s still exists. ***\n"+
"It probably contains stale files that may confuse the build.\n"+
"Please (check what's there and) remove it and try again.\n"+
"See https://golang.org/s/go14nopkg\n",
pathf("%s/src/pkg", goroot))
}
if rebuildall {
clean()
}
setup()
timelog("build", "toolchain1")
checkCC()
bootstrapBuildTools()
// Remember old content of $GOROOT/bin for comparison below.
oldBinFiles, err := filepath.Glob(pathf("%s/bin/*", goroot))
if err != nil {
fatalf("glob: %v", err)
}
// For the main bootstrap, building for host os/arch.
oldgoos = goos
oldgoarch = goarch
goos = gohostos
goarch = gohostarch
os.Setenv("GOHOSTARCH", gohostarch)
os.Setenv("GOHOSTOS", gohostos)
os.Setenv("GOARCH", goarch)
os.Setenv("GOOS", goos)
timelog("build", "go_bootstrap")
xprintf("Building Go bootstrap cmd/go (go_bootstrap) using Go toolchain1.\n")
install("runtime") // dependency not visible in sources; also sets up textflag.h
install("time/tzdata") // no dependency in sources; creates generated file
install("cmd/go")
if vflag > 0 {
xprintf("\n")
}
gogcflags = os.Getenv("GO_GCFLAGS") // we were using $BOOT_GO_GCFLAGS until now
setNoOpt()
goldflags = os.Getenv("GO_LDFLAGS") // we were using $BOOT_GO_LDFLAGS until now
goBootstrap := pathf("%s/go_bootstrap", tooldir)
if debug {
run("", ShowOutput|CheckExit, pathf("%s/compile", tooldir), "-V=full")
copyfile(pathf("%s/compile1", tooldir), pathf("%s/compile", tooldir), writeExec)
}
// To recap, so far we have built the new toolchain
// (cmd/asm, cmd/cgo, cmd/compile, cmd/link)
// using the Go bootstrap toolchain and go command.
// Then we built the new go command (as go_bootstrap)
// using the new toolchain and our own build logic (above).
//
// toolchain1 = mk(new toolchain, go1.17 toolchain, go1.17 cmd/go)
// go_bootstrap = mk(new cmd/go, toolchain1, cmd/dist)
//
// The toolchain1 we built earlier is built from the new sources,
// but because it was built using cmd/go it has no build IDs.
// The eventually installed toolchain needs build IDs, so we need
// to do another round:
//
// toolchain2 = mk(new toolchain, toolchain1, go_bootstrap)
//
timelog("build", "toolchain2")
if vflag > 0 {
xprintf("\n")
}
xprintf("Building Go toolchain2 using go_bootstrap and Go toolchain1.\n")
os.Setenv("CC", compilerEnvLookup("CC", defaultcc, goos, goarch))
// Now that cmd/go is in charge of the build process, enable GOEXPERIMENT.
os.Setenv("GOEXPERIMENT", goexperiment)
// No need to enable PGO for toolchain2.
goInstall(toolenv(), goBootstrap, append([]string{"-pgo=off"}, toolchain...)...)
if debug {
run("", ShowOutput|CheckExit, pathf("%s/compile", tooldir), "-V=full")
copyfile(pathf("%s/compile2", tooldir), pathf("%s/compile", tooldir), writeExec)
}
// Toolchain2 should be semantically equivalent to toolchain1,
// but it was built using the newly built compiler instead of the Go bootstrap compiler,
// so it should at the least run faster. Also, toolchain1 had no build IDs
// in the binaries, while toolchain2 does. In non-release builds, the
// toolchain's build IDs feed into constructing the build IDs of built targets,
// so in non-release builds, everything now looks out-of-date due to
// toolchain2 having build IDs - that is, due to the go command seeing
// that there are new compilers. In release builds, the toolchain's reported
// version is used in place of the build ID, and the go command does not
// see that change from toolchain1 to toolchain2, so in release builds,
// nothing looks out of date.
// To keep the behavior the same in both non-release and release builds,
// we force-install everything here.
//
// toolchain3 = mk(new toolchain, toolchain2, go_bootstrap)
//
timelog("build", "toolchain3")
if vflag > 0 {
xprintf("\n")
}
xprintf("Building Go toolchain3 using go_bootstrap and Go toolchain2.\n")
goInstall(toolenv(), goBootstrap, append([]string{"-a"}, toolchain...)...)
if debug {
run("", ShowOutput|CheckExit, pathf("%s/compile", tooldir), "-V=full")
copyfile(pathf("%s/compile3", tooldir), pathf("%s/compile", tooldir), writeExec)
}
// Now that toolchain3 has been built from scratch, its compiler and linker
// should have accurate build IDs suitable for caching.
// Now prime the build cache with the rest of the standard library for
// testing, and so that the user can run 'go install std cmd' to quickly
// iterate on local changes without waiting for a full rebuild.
if _, err := os.Stat(pathf("%s/VERSION", goroot)); err == nil {
// If we have a VERSION file, then we use the Go version
// instead of build IDs as a cache key, and there is no guarantee
// that code hasn't changed since the last time we ran a build
// with this exact VERSION file (especially if someone is working
// on a release branch). We must not fall back to the shared build cache
// in this case. Leave $GOCACHE alone.
} else {
os.Setenv("GOCACHE", oldgocache)
}
if goos == oldgoos && goarch == oldgoarch {
// Common case - not setting up for cross-compilation.
timelog("build", "toolchain")
if vflag > 0 {
xprintf("\n")
}
xprintf("Building packages and commands for %s/%s.\n", goos, goarch)
} else {
// GOOS/GOARCH does not match GOHOSTOS/GOHOSTARCH.
// Finish GOHOSTOS/GOHOSTARCH installation and then
// run GOOS/GOARCH installation.
timelog("build", "host toolchain")
if vflag > 0 {
xprintf("\n")
}
xprintf("Building commands for host, %s/%s.\n", goos, goarch)
goInstall(toolenv(), goBootstrap, "cmd")
checkNotStale(toolenv(), goBootstrap, "cmd")
checkNotStale(toolenv(), gorootBinGo, "cmd")
timelog("build", "target toolchain")
if vflag > 0 {
xprintf("\n")
}
goos = oldgoos
goarch = oldgoarch
os.Setenv("GOOS", goos)
os.Setenv("GOARCH", goarch)
os.Setenv("CC", compilerEnvLookup("CC", defaultcc, goos, goarch))
xprintf("Building packages and commands for target, %s/%s.\n", goos, goarch)
}
goInstall(nil, goBootstrap, "std")
goInstall(toolenv(), goBootstrap, "cmd")
checkNotStale(toolenv(), goBootstrap, toolchain...)
checkNotStale(nil, goBootstrap, "std")
checkNotStale(toolenv(), goBootstrap, "cmd")
checkNotStale(nil, gorootBinGo, "std")
checkNotStale(toolenv(), gorootBinGo, "cmd")
if debug {
run("", ShowOutput|CheckExit, pathf("%s/compile", tooldir), "-V=full")
checkNotStale(toolenv(), goBootstrap, toolchain...)
copyfile(pathf("%s/compile4", tooldir), pathf("%s/compile", tooldir), writeExec)
}
// Check that there are no new files in $GOROOT/bin other than
// go and gofmt and $GOOS_$GOARCH (target bin when cross-compiling).
binFiles, err := filepath.Glob(pathf("%s/bin/*", goroot))
if err != nil {
fatalf("glob: %v", err)
}
ok := map[string]bool{}
for _, f := range oldBinFiles {
ok[f] = true
}
for _, f := range binFiles {
if gohostos == "darwin" && filepath.Base(f) == ".DS_Store" {
continue // unfortunate but not unexpected
}
elem := strings.TrimSuffix(filepath.Base(f), ".exe")
if !ok[f] && elem != "go" && elem != "gofmt" && elem != goos+"_"+goarch {
fatalf("unexpected new file in $GOROOT/bin: %s", elem)
}
}
// Remove go_bootstrap now that we're done.
xremove(pathf("%s/go_bootstrap"+exe, tooldir))
if goos == "android" {
// Make sure the exec wrapper will sync a fresh $GOROOT to the device.
xremove(pathf("%s/go_android_exec-adb-sync-status", os.TempDir()))
}
if wrapperPath := wrapperPathFor(goos, goarch); wrapperPath != "" {
oldcc := os.Getenv("CC")
os.Setenv("GOOS", gohostos)
os.Setenv("GOARCH", gohostarch)
os.Setenv("CC", compilerEnvLookup("CC", defaultcc, gohostos, gohostarch))
goCmd(nil, gorootBinGo, "build", "-o", pathf("%s/go_%s_%s_exec%s", gorootBin, goos, goarch, exe), wrapperPath)
// Restore environment.
// TODO(elias.naur): support environment variables in goCmd?
os.Setenv("GOOS", goos)
os.Setenv("GOARCH", goarch)
os.Setenv("CC", oldcc)
}
if distpack {
xprintf("Packaging archives for %s/%s.\n", goos, goarch)
run("", ShowOutput|CheckExit, pathf("%s/distpack", tooldir))
}
// Print trailing banner unless instructed otherwise.
if !noBanner {
banner()
}
}
func wrapperPathFor(goos, goarch string) string {
switch {
case goos == "android":
if gohostos != "android" {
return pathf("%s/misc/go_android_exec/main.go", goroot)
}
case goos == "ios":
if gohostos != "ios" {
return pathf("%s/misc/ios/go_ios_exec.go", goroot)
}
}
return ""
}
func goInstall(env []string, goBinary string, args ...string) {
goCmd(env, goBinary, "install", args...)
}
func appendCompilerFlags(args []string) []string {
if gogcflags != "" {
args = append(args, "-gcflags=all="+gogcflags)
}
if goldflags != "" {
args = append(args, "-ldflags=all="+goldflags)
}
return args
}
func goCmd(env []string, goBinary string, cmd string, args ...string) {
goCmd := []string{goBinary, cmd}
if noOpt {
goCmd = append(goCmd, "-tags=noopt")
}
goCmd = appendCompilerFlags(goCmd)
if vflag > 0 {
goCmd = append(goCmd, "-v")
}
// Force only one process at a time on vx32 emulation.
if gohostos == "plan9" && os.Getenv("sysname") == "vx32" {
goCmd = append(goCmd, "-p=1")
}
runEnv(workdir, ShowOutput|CheckExit, env, append(goCmd, args...)...)
}
func checkNotStale(env []string, goBinary string, targets ...string) {
goCmd := []string{goBinary, "list"}
if noOpt {
goCmd = append(goCmd, "-tags=noopt")
}
goCmd = appendCompilerFlags(goCmd)
goCmd = append(goCmd, "-f={{if .Stale}}\tSTALE {{.ImportPath}}: {{.StaleReason}}{{end}}")
out := runEnv(workdir, CheckExit, env, append(goCmd, targets...)...)
if strings.Contains(out, "\tSTALE ") {
os.Setenv("GODEBUG", "gocachehash=1")
for _, target := range []string{"runtime/internal/sys", "cmd/dist", "cmd/link"} {
if strings.Contains(out, "STALE "+target) {
run(workdir, ShowOutput|CheckExit, goBinary, "list", "-f={{.ImportPath}} {{.Stale}}", target)
break
}
}
fatalf("unexpected stale targets reported by %s list -gcflags=\"%s\" -ldflags=\"%s\" for %v (consider rerunning with GOMAXPROCS=1 GODEBUG=gocachehash=1):\n%s", goBinary, gogcflags, goldflags, targets, out)
}
}
// Cannot use go/build directly because cmd/dist for a new release
// builds against an old release's go/build, which may be out of sync.
// To reduce duplication, we generate the list for go/build from this.
//
// We list all supported platforms in this list, so that this is the
// single point of truth for supported platforms. This list is used
// by 'go tool dist list'.
var cgoEnabled = map[string]bool{
"aix/ppc64": true,
"darwin/amd64": true,
"darwin/arm64": true,
"dragonfly/amd64": true,
"freebsd/386": true,
"freebsd/amd64": true,
"freebsd/arm": true,
"freebsd/arm64": true,
"freebsd/riscv64": true,
"illumos/amd64": true,
"linux/386": true,
"linux/amd64": true,
"linux/arm": true,
"linux/arm64": true,
"linux/loong64": true,
"linux/ppc64": false,
"linux/ppc64le": true,
"linux/mips": true,
"linux/mipsle": true,
"linux/mips64": true,
"linux/mips64le": true,
"linux/riscv64": true,
"linux/s390x": true,
"linux/sparc64": true,
"android/386": true,
"android/amd64": true,
"android/arm": true,
"android/arm64": true,
"ios/arm64": true,
"ios/amd64": true,
"js/wasm": false,
"wasip1/wasm": false,
"netbsd/386": true,
"netbsd/amd64": true,
"netbsd/arm": true,
"netbsd/arm64": true,
"openbsd/386": true,
"openbsd/amd64": true,
"openbsd/arm": true,
"openbsd/arm64": true,
"openbsd/mips64": true,
"openbsd/ppc64": false,
"openbsd/riscv64": false,
"plan9/386": false,
"plan9/amd64": false,
"plan9/arm": false,
"solaris/amd64": true,
"windows/386": true,
"windows/amd64": true,
"windows/arm": false,
"windows/arm64": true,
}
// List of platforms that are marked as broken ports.
// These require -force flag to build, and also
// get filtered out of cgoEnabled for 'dist list'.
// See go.dev/issue/56679.
var broken = map[string]bool{
"linux/sparc64": true, // An incomplete port. See CL 132155.
"openbsd/mips64": true, // Broken: go.dev/issue/58110.
"openbsd/riscv64": true, // An incomplete port: go.dev/issue/55999.
}
// List of platforms which are first class ports. See go.dev/issue/38874.
var firstClass = map[string]bool{
"darwin/amd64": true,
"darwin/arm64": true,
"linux/386": true,
"linux/amd64": true,
"linux/arm": true,
"linux/arm64": true,
"windows/386": true,
"windows/amd64": true,
}
// We only need CC if cgo is forced on, or if the platform requires external linking.
// Otherwise the go command will automatically disable it.
func needCC() bool {
return os.Getenv("CGO_ENABLED") == "1" || mustLinkExternal(gohostos, gohostarch, false)
}
func checkCC() {
if !needCC() {
return
}
cc1 := defaultcc[""]
if cc1 == "" {
cc1 = "gcc"
for _, os := range clangos {
if gohostos == os {
cc1 = "clang"
break
}
}
}
cc, err := quotedSplit(cc1)
if err != nil {
fatalf("split CC: %v", err)
}
var ccHelp = append(cc, "--help")
if output, err := exec.Command(ccHelp[0], ccHelp[1:]...).CombinedOutput(); err != nil {
outputHdr := ""
if len(output) > 0 {
outputHdr = "\nCommand output:\n\n"
}
fatalf("cannot invoke C compiler %q: %v\n\n"+
"Go needs a system C compiler for use with cgo.\n"+
"To set a C compiler, set CC=the-compiler.\n"+
"To disable cgo, set CGO_ENABLED=0.\n%s%s", cc, err, outputHdr, output)
}
}
func defaulttarg() string {
// xgetwd might return a path with symlinks fully resolved, and if
// there happens to be symlinks in goroot, then the hasprefix test
// will never succeed. Instead, we use xrealwd to get a canonical
// goroot/src before the comparison to avoid this problem.
pwd := xgetwd()
src := pathf("%s/src/", goroot)
real_src := xrealwd(src)
if !strings.HasPrefix(pwd, real_src) {
fatalf("current directory %s is not under %s", pwd, real_src)
}
pwd = pwd[len(real_src):]
// guard against xrealwd returning the directory without the trailing /
pwd = strings.TrimPrefix(pwd, "/")
return pwd
}
// Install installs the list of packages named on the command line.
func cmdinstall() {
xflagparse(-1)
if flag.NArg() == 0 {
install(defaulttarg())
}
for _, arg := range flag.Args() {
install(arg)
}
}
// Clean deletes temporary objects.
func cmdclean() {
xflagparse(0)
clean()
}
// Banner prints the 'now you've installed Go' banner.
func cmdbanner() {
xflagparse(0)
banner()
}
func banner() {
if vflag > 0 {
xprintf("\n")
}
xprintf("---\n")
xprintf("Installed Go for %s/%s in %s\n", goos, goarch, goroot)
xprintf("Installed commands in %s\n", gorootBin)
if !xsamefile(goroot_final, goroot) {
// If the files are to be moved, don't check that gobin
// is on PATH; assume they know what they are doing.
} else if gohostos == "plan9" {
// Check that GOROOT/bin is bound before /bin.
pid := strings.Replace(readfile("#c/pid"), " ", "", -1)
ns := fmt.Sprintf("/proc/%s/ns", pid)
if !strings.Contains(readfile(ns), fmt.Sprintf("bind -b %s /bin", gorootBin)) {
xprintf("*** You need to bind %s before /bin.\n", gorootBin)
}
} else {
// Check that GOROOT/bin appears in $PATH.
pathsep := ":"
if gohostos == "windows" {
pathsep = ";"
}
path := os.Getenv("PATH")
if p, ok := os.LookupEnv("DIST_UNMODIFIED_PATH"); ok {
// Scripts that modify $PATH and then run dist should also provide
// dist with an unmodified copy of $PATH via $DIST_UNMODIFIED_PATH.
// Use it here when determining if the user still needs to update
// their $PATH. See go.dev/issue/42563.
path = p
}
if !strings.Contains(pathsep+path+pathsep, pathsep+gorootBin+pathsep) {
xprintf("*** You need to add %s to your PATH.\n", gorootBin)
}
}
if !xsamefile(goroot_final, goroot) {
xprintf("\n"+
"The binaries expect %s to be copied or moved to %s\n",
goroot, goroot_final)
}
}
// Version prints the Go version.
func cmdversion() {
xflagparse(0)
xprintf("%s\n", findgoversion())
}
// cmdlist lists all supported platforms.
func cmdlist() {
jsonFlag := flag.Bool("json", false, "produce JSON output")
brokenFlag := flag.Bool("broken", false, "include broken ports")
xflagparse(0)
var plats []string
for p := range cgoEnabled {
if broken[p] && !*brokenFlag {
continue
}
plats = append(plats, p)
}
sort.Strings(plats)
if !*jsonFlag {
for _, p := range plats {
xprintf("%s\n", p)
}
return
}
type jsonResult struct {
GOOS string
GOARCH string
CgoSupported bool
FirstClass bool
Broken bool `json:",omitempty"`
}
var results []jsonResult
for _, p := range plats {
fields := strings.Split(p, "/")
results = append(results, jsonResult{
GOOS: fields[0],
GOARCH: fields[1],
CgoSupported: cgoEnabled[p],
FirstClass: firstClass[p],
Broken: broken[p],
})
}
out, err := json.MarshalIndent(results, "", "\t")
if err != nil {
fatalf("json marshal error: %v", err)
}
if _, err := os.Stdout.Write(out); err != nil {
fatalf("write failed: %v", err)
}
}
func setNoOpt() {
for _, gcflag := range strings.Split(gogcflags, " ") {
if gcflag == "-N" || gcflag == "-l" {
noOpt = true
break
}
}
}
|