File size: 64,442 Bytes
61bba11 | 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 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 | // Copyright 2016 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 (
"bufio"
"bytes"
"debug/elf"
"debug/macho"
"debug/pe"
"errors"
"internal/abi"
"internal/platform"
"internal/testenv"
"internal/xcoff"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"testing"
"unsafe"
imacho "cmd/internal/macho"
"cmd/internal/objfile"
"cmd/internal/sys"
)
// TestMain allows this test binary to run as a -toolexec wrapper for
// the 'go' command. If LINK_TEST_TOOLEXEC is set, TestMain runs the
// binary as if it were cmd/link, and otherwise runs the requested
// tool as a subprocess.
//
// This allows the test to verify the behavior of the current contents of the
// cmd/link package even if the installed cmd/link binary is stale.
func TestMain(m *testing.M) {
// Are we running as a toolexec wrapper? If so then run either
// the correct tool or this executable itself (for the linker).
// Running as toolexec wrapper.
if os.Getenv("LINK_TEST_TOOLEXEC") != "" {
if strings.TrimSuffix(filepath.Base(os.Args[1]), ".exe") == "link" {
// Running as a -toolexec linker, and the tool is cmd/link.
// Substitute this test binary for the linker.
os.Args = os.Args[1:]
main()
os.Exit(0)
}
// Running some other tool.
cmd := exec.Command(os.Args[1], os.Args[2:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
os.Exit(1)
}
os.Exit(0)
}
// Are we being asked to run as the linker (without toolexec)?
// If so then kick off main.
if os.Getenv("LINK_TEST_EXEC_LINKER") != "" {
main()
os.Exit(0)
}
if testExe, err := os.Executable(); err == nil {
// on wasm, some phones, we expect an error from os.Executable()
testLinker = testExe
}
// Not running as a -toolexec wrapper or as a linker executable.
// Just run the tests.
os.Exit(m.Run())
}
// testLinker is the path of the test executable being run.
// This is used by [TestScript].
var testLinker string
// goCmd returns a [*exec.Cmd] that runs the go tool using
// the current linker sources rather than the installed linker.
// The first element of the args parameter should be the go subcommand
// to run, such as "build" or "run". It must be a subcommand that
// takes the go command's build flags.
func goCmd(t *testing.T, args ...string) *exec.Cmd {
goArgs := []string{args[0], "-toolexec", testenv.Executable(t)}
args = append(goArgs, args[1:]...)
cmd := testenv.Command(t, testenv.GoToolPath(t), args...)
cmd = testenv.CleanCmdEnv(cmd)
cmd.Env = append(cmd.Env, "LINK_TEST_TOOLEXEC=1")
return cmd
}
// linkCmd returns a [*exec.Cmd] that runs the linker built from
// the current sources. This is like "go tool link", but runs the
// current linker rather than the installed one.
func linkCmd(t *testing.T, args ...string) *exec.Cmd {
// Set up the arguments that TestMain looks for.
args = append([]string{"link"}, args...)
cmd := testenv.Command(t, testenv.Executable(t), args...)
cmd = testenv.CleanCmdEnv(cmd)
cmd.Env = append(cmd.Env, "LINK_TEST_TOOLEXEC=1")
return cmd
}
var AuthorPaidByTheColumnInch struct {
fog int `text:"London. Michaelmas term lately over, and the Lord Chancellor sitting in Lincoln’s Inn Hall. Implacable November weather. As much mud in the streets as if the waters had but newly retired from the face of the earth, and it would not be wonderful to meet a Megalosaurus, forty feet long or so, waddling like an elephantine lizard up Holborn Hill. Smoke lowering down from chimney-pots, making a soft black drizzle, with flakes of soot in it as big as full-grown snowflakes—gone into mourning, one might imagine, for the death of the sun. Dogs, undistinguishable in mire. Horses, scarcely better; splashed to their very blinkers. Foot passengers, jostling one another’s umbrellas in a general infection of ill temper, and losing their foot-hold at street-corners, where tens of thousands of other foot passengers have been slipping and sliding since the day broke (if this day ever broke), adding new deposits to the crust upon crust of mud, sticking at those points tenaciously to the pavement, and accumulating at compound interest. Fog everywhere. Fog up the river, where it flows among green aits and meadows; fog down the river, where it rolls defiled among the tiers of shipping and the waterside pollutions of a great (and dirty) city. Fog on the Essex marshes, fog on the Kentish heights. Fog creeping into the cabooses of collier-brigs; fog lying out on the yards and hovering in the rigging of great ships; fog drooping on the gunwales of barges and small boats. Fog in the eyes and throats of ancient Greenwich pensioners, wheezing by the firesides of their wards; fog in the stem and bowl of the afternoon pipe of the wrathful skipper, down in his close cabin; fog cruelly pinching the toes and fingers of his shivering little ‘prentice boy on deck. Chance people on the bridges peeping over the parapets into a nether sky of fog, with fog all round them, as if they were up in a balloon and hanging in the misty clouds. Gas looming through the fog in divers places in the streets, much as the sun may, from the spongey fields, be seen to loom by husbandman and ploughboy. Most of the shops lighted two hours before their time—as the gas seems to know, for it has a haggard and unwilling look. The raw afternoon is rawest, and the dense fog is densest, and the muddy streets are muddiest near that leaden-headed old obstruction, appropriate ornament for the threshold of a leaden-headed old corporation, Temple Bar. And hard by Temple Bar, in Lincoln’s Inn Hall, at the very heart of the fog, sits the Lord High Chancellor in his High Court of Chancery."`
wind int `text:"It was grand to see how the wind awoke, and bent the trees, and drove the rain before it like a cloud of smoke; and to hear the solemn thunder, and to see the lightning; and while thinking with awe of the tremendous powers by which our little lives are encompassed, to consider how beneficent they are, and how upon the smallest flower and leaf there was already a freshness poured from all this seeming rage, which seemed to make creation new again."`
jarndyce int `text:"Jarndyce and Jarndyce drones on. This scarecrow of a suit has, over the course of time, become so complicated, that no man alive knows what it means. The parties to it understand it least; but it has been observed that no two Chancery lawyers can talk about it for five minutes, without coming to a total disagreement as to all the premises. Innumerable children have been born into the cause; innumerable young people have married into it; innumerable old people have died out of it. Scores of persons have deliriously found themselves made parties in Jarndyce and Jarndyce, without knowing how or why; whole families have inherited legendary hatreds with the suit. The little plaintiff or defendant, who was promised a new rocking-horse when Jarndyce and Jarndyce should be settled, has grown up, possessed himself of a real horse, and trotted away into the other world. Fair wards of court have faded into mothers and grandmothers; a long procession of Chancellors has come in and gone out; the legion of bills in the suit have been transformed into mere bills of mortality; there are not three Jarndyces left upon the earth perhaps, since old Tom Jarndyce in despair blew his brains out at a coffee-house in Chancery Lane; but Jarndyce and Jarndyce still drags its dreary length before the Court, perennially hopeless."`
principle int `text:"The one great principle of the English law is, to make business for itself. There is no other principle distinctly, certainly, and consistently maintained through all its narrow turnings. Viewed by this light it becomes a coherent scheme, and not the monstrous maze the laity are apt to think it. Let them but once clearly perceive that its grand principle is to make business for itself at their expense, and surely they will cease to grumble."`
}
func TestLargeSymName(t *testing.T) {
// The compiler generates a symbol name using the string form of the
// type. This tests that the linker can read symbol names larger than
// the bufio buffer. Issue #15104.
_ = AuthorPaidByTheColumnInch
}
func TestIssue21703(t *testing.T) {
t.Parallel()
testenv.MustHaveGoBuild(t)
// N.B. the build below explictly doesn't pass through
// -asan/-msan/-race, so we don't care about those.
testenv.MustInternalLink(t, testenv.NoSpecialBuildTypes)
const source = `
package main
const X = "\n!\n"
func main() {}
`
tmpdir := t.TempDir()
main := filepath.Join(tmpdir, "main.go")
err := os.WriteFile(main, []byte(source), 0666)
if err != nil {
t.Fatalf("failed to write main.go: %v\n", err)
}
importcfgfile := filepath.Join(tmpdir, "importcfg")
testenv.WriteImportcfg(t, importcfgfile, nil, main)
cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-importcfg="+importcfgfile, "-p=main", "main.go")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("failed to compile main.go: %v, output: %s\n", err, out)
}
cmd = linkCmd(t, "-importcfg="+importcfgfile, "main.o")
cmd.Dir = tmpdir
out, err = cmd.CombinedOutput()
if err != nil {
if runtime.GOOS == "android" && runtime.GOARCH == "arm64" {
testenv.SkipFlaky(t, 58806)
}
t.Fatalf("failed to link main.o: %v, output: %s\n", err, out)
}
}
// TestIssue28429 ensures that the linker does not attempt to link
// sections not named *.o. Such sections may be used by a build system
// to, for example, save facts produced by a modular static analysis
// such as golang.org/x/tools/go/analysis.
func TestIssue28429(t *testing.T) {
t.Parallel()
testenv.MustHaveGoBuild(t)
// N.B. go build below explictly doesn't pass through
// -asan/-msan/-race, so we don't care about those.
testenv.MustInternalLink(t, testenv.NoSpecialBuildTypes)
tmpdir := t.TempDir()
write := func(name, content string) {
err := os.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0666)
if err != nil {
t.Fatal(err)
}
}
runGo := func(args ...string) {
cmd := testenv.Command(t, testenv.GoToolPath(t), args...)
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("'go %s' failed: %v, output: %s",
strings.Join(args, " "), err, out)
}
}
// Compile a main package.
write("main.go", "package main; func main() {}")
importcfgfile := filepath.Join(tmpdir, "importcfg")
testenv.WriteImportcfg(t, importcfgfile, nil, filepath.Join(tmpdir, "main.go"))
runGo("tool", "compile", "-importcfg="+importcfgfile, "-p=main", "main.go")
runGo("tool", "pack", "c", "main.a", "main.o")
// Add an extra section with a short, non-.o name.
// This simulates an alternative build system.
write(".facts", "this is not an object file")
runGo("tool", "pack", "r", "main.a", ".facts")
// Verify that the linker does not attempt
// to compile the extra section.
cmd := linkCmd(t, "-importcfg="+importcfgfile, "main.a")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
if runtime.GOOS == "android" && runtime.GOARCH == "arm64" {
testenv.SkipFlaky(t, 58806)
}
t.Fatalf("linker failed: %v, output %s", err, out)
}
}
func TestUnresolved(t *testing.T) {
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
write := func(name, content string) {
err := os.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0666)
if err != nil {
t.Fatal(err)
}
}
// Test various undefined references. Because of issue #29852,
// this used to give confusing error messages because the
// linker would find an undefined reference to "zero" created
// by the runtime package.
write("go.mod", "module testunresolved\n")
write("main.go", `package main
func main() {
x()
}
func x()
`)
write("main.s", `
TEXT ·x(SB),0,$0
MOVD zero<>(SB), AX
MOVD zero(SB), AX
MOVD ·zero(SB), AX
RET
`)
cmd := goCmd(t, "build")
cmd.Dir = tmpdir
cmd.Env = append(cmd.Env,
"GOARCH=amd64", "GOOS=linux", "GOPATH="+filepath.Join(tmpdir, "_gopath"))
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected build to fail, but it succeeded")
}
out = regexp.MustCompile("(?m)^#.*\n").ReplaceAll(out, nil)
got := string(out)
want := `main.x: relocation target zero not defined
main.x: relocation target zero not defined
main.x: relocation target main.zero not defined
`
if want != got {
t.Fatalf("want:\n%sgot:\n%s", want, got)
}
}
func TestIssue33979(t *testing.T) {
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
// N.B. go build below explictly doesn't pass through
// -asan/-msan/-race, so we don't care about those.
testenv.MustInternalLink(t, testenv.SpecialBuildTypes{Cgo: true})
t.Parallel()
tmpdir := t.TempDir()
write := func(name, content string) {
err := os.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0666)
if err != nil {
t.Fatal(err)
}
}
run := func(name string, args ...string) string {
cmd := testenv.Command(t, name, args...)
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("'go %s' failed: %v, output: %s", strings.Join(args, " "), err, out)
}
return string(out)
}
runGo := func(args ...string) string {
return run(testenv.GoToolPath(t), args...)
}
// Test object with undefined reference that was not generated
// by Go, resulting in an SXREF symbol being loaded during linking.
// Because of issue #33979, the SXREF symbol would be found during
// error reporting, resulting in confusing error messages.
write("main.go", `package main
func main() {
x()
}
func x()
`)
// The following assembly must work on all architectures.
write("x.s", `
TEXT ·x(SB),0,$0
CALL foo(SB)
RET
`)
write("x.c", `
void undefined();
void foo() {
undefined();
}
`)
cc := strings.TrimSpace(runGo("env", "CC"))
cflags := strings.Fields(runGo("env", "GOGCCFLAGS"))
importcfgfile := filepath.Join(tmpdir, "importcfg")
testenv.WriteImportcfg(t, importcfgfile, nil, "runtime")
// Compile, assemble and pack the Go and C code.
runGo("tool", "asm", "-p=main", "-gensymabis", "-o", "symabis", "x.s")
runGo("tool", "compile", "-importcfg="+importcfgfile, "-symabis", "symabis", "-p=main", "-o", "x1.o", "main.go")
runGo("tool", "asm", "-p=main", "-o", "x2.o", "x.s")
run(cc, append(cflags, "-c", "-o", "x3.o", "x.c")...)
runGo("tool", "pack", "c", "x.a", "x1.o", "x2.o", "x3.o")
// Now attempt to link using the internal linker.
cmd := linkCmd(t, "-importcfg="+importcfgfile, "-linkmode=internal", "x.a")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("expected link to fail, but it succeeded")
}
re := regexp.MustCompile(`(?m)^main\(.*text\): relocation target undefined not defined$`)
if !re.Match(out) {
t.Fatalf("got:\n%q\nwant:\n%s", out, re)
}
}
func TestBuildForTvOS(t *testing.T) {
testenv.MustHaveCGO(t)
testenv.MustHaveGoBuild(t)
// Only run this on darwin, where we can cross build for tvOS.
if runtime.GOOS != "darwin" {
t.Skip("skipping on non-darwin platform")
}
if testing.Short() && testenv.Builder() == "" {
t.Skip("skipping in -short mode with $GO_BUILDER_NAME empty")
}
if err := testenv.Command(t, "xcrun", "--help").Run(); err != nil {
t.Skipf("error running xcrun, required for iOS cross build: %v", err)
}
t.Parallel()
sdkPath, err := testenv.Command(t, "xcrun", "--sdk", "appletvos", "--show-sdk-path").Output()
if err != nil {
t.Skip("failed to locate appletvos SDK, skipping")
}
CC := []string{
"clang",
"-arch",
"arm64",
"-isysroot", strings.TrimSpace(string(sdkPath)),
"-mtvos-version-min=12.0",
"-fembed-bitcode",
}
CGO_LDFLAGS := []string{"-framework", "CoreFoundation"}
lib := filepath.Join("testdata", "testBuildFortvOS", "lib.go")
tmpDir := t.TempDir()
ar := filepath.Join(tmpDir, "lib.a")
cmd := goCmd(t, "build", "-buildmode=c-archive", "-o", ar, lib)
env := []string{
"CGO_ENABLED=1",
"GOOS=ios",
"GOARCH=arm64",
"CC=" + strings.Join(CC, " "),
"CGO_CFLAGS=", // ensure CGO_CFLAGS does not contain any flags. Issue #35459
"CGO_LDFLAGS=" + strings.Join(CGO_LDFLAGS, " "),
}
cmd.Env = append(cmd.Env, env...)
t.Logf("%q %v", env, cmd)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
}
link := testenv.Command(t, CC[0], CC[1:]...)
link.Args = append(link.Args, CGO_LDFLAGS...)
link.Args = append(link.Args, "-o", filepath.Join(tmpDir, "a.out")) // Avoid writing to package directory.
link.Args = append(link.Args, ar, filepath.Join("testdata", "testBuildFortvOS", "main.m"))
t.Log(link)
if out, err := link.CombinedOutput(); err != nil {
t.Fatalf("%v: %v:\n%s", link.Args, err, out)
}
}
var testXFlagSrc = `
package main
var X = "hello"
var Z = [99999]int{99998:12345} // make it large enough to be mmaped
func main() { println(X) }
`
func TestXFlag(t *testing.T) {
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "main.go")
err := os.WriteFile(src, []byte(testXFlagSrc), 0666)
if err != nil {
t.Fatal(err)
}
cmd := goCmd(t, "build", "-ldflags=-X=main.X=meow", "-o", filepath.Join(tmpdir, "main"), src)
if out, err := cmd.CombinedOutput(); err != nil {
t.Errorf("%v: %v:\n%s", cmd.Args, err, out)
}
}
var trivialSrc = `
package main
func main() { }
`
func TestMachOBuildVersion(t *testing.T) {
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "main.go")
err := os.WriteFile(src, []byte(trivialSrc), 0666)
if err != nil {
t.Fatal(err)
}
exe := filepath.Join(tmpdir, "main")
cmd := goCmd(t, "build", "-ldflags=-linkmode=internal", "-o", exe, src)
cmd.Env = append(cmd.Env,
"CGO_ENABLED=0",
"GOOS=darwin",
"GOARCH=amd64",
)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
}
exef, err := os.Open(exe)
if err != nil {
t.Fatal(err)
}
defer exef.Close()
exem, err := macho.NewFile(exef)
if err != nil {
t.Fatal(err)
}
found := false
checkMin := func(ver uint32) {
major, minor, patch := (ver>>16)&0xff, (ver>>8)&0xff, (ver>>0)&0xff
if major < 12 {
t.Errorf("LC_BUILD_VERSION version %d.%d.%d < 12.0.0", major, minor, patch)
}
}
for _, cmd := range exem.Loads {
raw := cmd.Raw()
type_ := exem.ByteOrder.Uint32(raw)
if type_ != imacho.LC_BUILD_VERSION {
continue
}
osVer := exem.ByteOrder.Uint32(raw[12:])
checkMin(osVer)
sdkVer := exem.ByteOrder.Uint32(raw[16:])
checkMin(sdkVer)
found = true
break
}
if !found {
t.Errorf("no LC_BUILD_VERSION load command found")
}
}
func TestMachOUUID(t *testing.T) {
testenv.MustHaveGoBuild(t)
if runtime.GOOS != "darwin" {
t.Skip("this is only for darwin")
}
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "main.go")
err := os.WriteFile(src, []byte(trivialSrc), 0666)
if err != nil {
t.Fatal(err)
}
extractUUID := func(exe string) string {
exem, err := macho.Open(exe)
if err != nil {
t.Fatal(err)
}
defer exem.Close()
for _, cmd := range exem.Loads {
raw := cmd.Raw()
type_ := exem.ByteOrder.Uint32(raw)
if type_ != imacho.LC_UUID {
continue
}
return string(raw[8:24])
}
return ""
}
tests := []struct{ name, ldflags, expect string }{
{"default", "", "gobuildid"},
{"gobuildid", "-B=gobuildid", "gobuildid"},
{"specific", "-B=0x0123456789ABCDEF0123456789ABCDEF", "\x01\x23\x45\x67\x89\xAB\xCD\xEF\x01\x23\x45\x67\x89\xAB\xCD\xEF"},
{"none", "-B=none", ""},
}
if testenv.HasCGO() {
for _, test := range tests {
t1 := test
t1.name += "_external"
t1.ldflags += " -linkmode=external"
tests = append(tests, t1)
}
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
exe := filepath.Join(tmpdir, test.name)
cmd := goCmd(t, "build", "-ldflags="+test.ldflags, "-o", exe, src)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
}
uuid := extractUUID(exe)
if test.expect == "gobuildid" {
// Go buildid is not known in source code. Check UUID is present,
// and satisfies UUIDv3.
if uuid == "" {
t.Fatal("expect nonempty UUID, got empty")
}
// The version number is the high 4 bits of byte 6.
if uuid[6]>>4 != 3 {
t.Errorf("expect v3 UUID, got %X (version %d)", uuid, uuid[6]>>4)
}
} else if uuid != test.expect {
t.Errorf("UUID mismatch: got %X, want %X", uuid, test.expect)
}
})
}
}
const Issue34788src = `
package blah
func Blah(i int) int {
a := [...]int{1, 2, 3, 4, 5, 6, 7, 8}
return a[i&7]
}
`
func TestIssue34788Android386TLSSequence(t *testing.T) {
testenv.MustHaveGoBuild(t)
// This is a cross-compilation test, so it doesn't make
// sense to run it on every GOOS/GOARCH combination. Limit
// the test to amd64 + darwin/linux.
if runtime.GOARCH != "amd64" ||
(runtime.GOOS != "darwin" && runtime.GOOS != "linux") {
t.Skip("skipping on non-{linux,darwin}/amd64 platform")
}
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "blah.go")
err := os.WriteFile(src, []byte(Issue34788src), 0666)
if err != nil {
t.Fatal(err)
}
obj := filepath.Join(tmpdir, "blah.o")
cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-p=blah", "-o", obj, src)
cmd.Env = append(os.Environ(), "GOARCH=386", "GOOS=android")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("failed to compile blah.go: %v, output: %s\n", err, out)
}
// Run objdump on the resulting object.
cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "objdump", obj)
out, oerr := cmd.CombinedOutput()
if oerr != nil {
t.Fatalf("failed to objdump blah.o: %v, output: %s\n", oerr, out)
}
// Sift through the output; we should not be seeing any R_TLS_LE relocs.
scanner := bufio.NewScanner(bytes.NewReader(out))
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "R_TLS_LE") {
t.Errorf("objdump output contains unexpected R_TLS_LE reloc: %s", line)
}
}
}
const testStrictDupGoSrc = `
package main
func f()
func main() { f() }
`
const testStrictDupAsmSrc1 = `
#include "textflag.h"
TEXT ·f(SB), NOSPLIT|DUPOK, $0-0
RET
`
const testStrictDupAsmSrc2 = `
#include "textflag.h"
TEXT ·f(SB), NOSPLIT|DUPOK, $0-0
JMP 0(PC)
`
const testStrictDupAsmSrc3 = `
#include "textflag.h"
GLOBL ·rcon(SB), RODATA|DUPOK, $64
`
const testStrictDupAsmSrc4 = `
#include "textflag.h"
GLOBL ·rcon(SB), RODATA|DUPOK, $32
`
func TestStrictDup(t *testing.T) {
// Check that -strictdups flag works.
testenv.MustHaveGoBuild(t)
asmfiles := []struct {
fname string
payload string
}{
{"a", testStrictDupAsmSrc1},
{"b", testStrictDupAsmSrc2},
{"c", testStrictDupAsmSrc3},
{"d", testStrictDupAsmSrc4},
}
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "x.go")
err := os.WriteFile(src, []byte(testStrictDupGoSrc), 0666)
if err != nil {
t.Fatal(err)
}
for _, af := range asmfiles {
src = filepath.Join(tmpdir, af.fname+".s")
err = os.WriteFile(src, []byte(af.payload), 0666)
if err != nil {
t.Fatal(err)
}
}
src = filepath.Join(tmpdir, "go.mod")
err = os.WriteFile(src, []byte("module teststrictdup\n"), 0666)
if err != nil {
t.Fatal(err)
}
cmd := goCmd(t, "build", "-ldflags=-strictdups=1")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Errorf("linking with -strictdups=1 failed: %v\n%s", err, string(out))
}
if !bytes.Contains(out, []byte("mismatched payload")) {
t.Errorf("unexpected output:\n%s", out)
}
cmd = goCmd(t, "build", "-ldflags=-strictdups=2")
cmd.Dir = tmpdir
out, err = cmd.CombinedOutput()
if err == nil {
t.Errorf("linking with -strictdups=2 did not fail")
}
// NB: on amd64 we get the 'new length' error, on arm64 the 'different
// contents' error.
if !(bytes.Contains(out, []byte("mismatched payload: new length")) ||
bytes.Contains(out, []byte("mismatched payload: same length but different contents"))) ||
!bytes.Contains(out, []byte("mismatched payload: different sizes")) {
t.Errorf("unexpected output:\n%s", out)
}
}
const testFuncAlignSrc = `
package main
import (
"fmt"
)
func alignPc()
var alignPcFnAddr uintptr
func main() {
if alignPcFnAddr % 512 != 0 {
fmt.Printf("expected 512 bytes alignment, got %v\n", alignPcFnAddr)
} else {
fmt.Printf("PASS")
}
}
`
var testFuncAlignAsmSources = map[string]string{
"arm64": `
#include "textflag.h"
TEXT ·alignPc(SB),NOSPLIT, $0-0
MOVD $2, R0
PCALIGN $512
MOVD $3, R1
RET
GLOBL ·alignPcFnAddr(SB),RODATA,$8
DATA ·alignPcFnAddr(SB)/8,$·alignPc(SB)
`,
"loong64": `
#include "textflag.h"
TEXT ·alignPc(SB),NOSPLIT, $0-0
MOVV $2, R4
PCALIGN $512
MOVV $3, R5
RET
GLOBL ·alignPcFnAddr(SB),RODATA,$8
DATA ·alignPcFnAddr(SB)/8,$·alignPc(SB)
`,
}
// TestFuncAlign verifies that the address of a function can be aligned
// with a specific value on arm64 and loong64.
func TestFuncAlign(t *testing.T) {
testFuncAlignAsmSrc := testFuncAlignAsmSources[runtime.GOARCH]
if len(testFuncAlignAsmSrc) == 0 || runtime.GOOS != "linux" {
t.Skip("skipping on non-linux/{arm64,loong64} platform")
}
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "go.mod")
err := os.WriteFile(src, []byte("module cmd/link/TestFuncAlign/falign"), 0666)
if err != nil {
t.Fatal(err)
}
src = filepath.Join(tmpdir, "falign.go")
err = os.WriteFile(src, []byte(testFuncAlignSrc), 0666)
if err != nil {
t.Fatal(err)
}
src = filepath.Join(tmpdir, "falign.s")
err = os.WriteFile(src, []byte(testFuncAlignAsmSrc), 0666)
if err != nil {
t.Fatal(err)
}
cmd := goCmd(t, "build", "-o", "falign")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Errorf("build failed: %v", err)
}
cmd = testenv.Command(t, tmpdir+"/falign")
out, err = cmd.CombinedOutput()
if err != nil {
t.Errorf("failed to run with err %v, output: %s", err, out)
}
if string(out) != "PASS" {
t.Errorf("unexpected output: %s\n", out)
}
}
const testFuncAlignOptionSrc = `
package main
//go:noinline
func foo() {
}
//go:noinline
func bar() {
}
//go:noinline
func baz() {
}
func main() {
foo()
bar()
baz()
}
`
// TestFuncAlignOption verifies that the -funcalign option changes the function alignment
func TestFuncAlignOption(t *testing.T) {
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "falign.go")
err := os.WriteFile(src, []byte(testFuncAlignOptionSrc), 0666)
if err != nil {
t.Fatal(err)
}
alignTest := func(align uint64) {
exeName := "falign.exe"
cmd := goCmd(t, "build", "-ldflags=-funcalign="+strconv.FormatUint(align, 10), "-o", exeName, "falign.go")
cmd.Dir = tmpdir
out, err := cmd.CombinedOutput()
if err != nil {
t.Errorf("build failed: %v \n%s", err, out)
}
exe := filepath.Join(tmpdir, exeName)
cmd = testenv.Command(t, exe)
out, err = cmd.CombinedOutput()
if err != nil {
t.Errorf("failed to run with err %v, output: %s", err, out)
}
// Check function alignment
f, err := objfile.Open(exe)
if err != nil {
t.Fatalf("failed to open file:%v\n", err)
}
defer f.Close()
fname := map[string]bool{"_main.foo": false,
"_main.bar": false,
"_main.baz": false}
syms, err := f.Symbols()
if err != nil {
t.Errorf("failed to get symbols with err %v", err)
}
for _, s := range syms {
fn := s.Name
if _, ok := fname[fn]; !ok {
fn = "_" + s.Name
if _, ok := fname[fn]; !ok {
continue
}
}
if s.Addr%align != 0 {
t.Fatalf("unaligned function: %s %x. Expected alignment: %d\n", fn, s.Addr, align)
}
fname[fn] = true
}
for k, v := range fname {
if !v {
t.Fatalf("function %s not found\n", k)
}
}
}
alignTest(16)
alignTest(32)
}
const testTrampSrc = `
package main
import "fmt"
func main() {
fmt.Println("hello")
defer func(){
if e := recover(); e == nil {
panic("did not panic")
}
}()
f1()
}
// Test deferreturn trampolines. See issue #39049.
func f1() { defer f2() }
func f2() { panic("XXX") }
`
func TestTrampoline(t *testing.T) {
// Test that trampoline insertion works as expected.
// For stress test, we set -debugtramp=2 flag, which sets a very low
// threshold for trampoline generation, and essentially all cross-package
// calls will use trampolines.
buildmodes := []string{"default"}
switch runtime.GOARCH {
case "arm", "arm64", "ppc64", "loong64":
case "ppc64le":
// Trampolines are generated differently when internal linking PIE, test them too.
buildmodes = append(buildmodes, "pie")
default:
t.Skipf("trampoline insertion is not implemented on %s", runtime.GOARCH)
}
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "hello.go")
err := os.WriteFile(src, []byte(testTrampSrc), 0666)
if err != nil {
t.Fatal(err)
}
exe := filepath.Join(tmpdir, "hello.exe")
for _, mode := range buildmodes {
cmd := goCmd(t, "build", "-buildmode="+mode, "-ldflags=-debugtramp=2", "-o", exe, src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("build (%s) failed: %v\n%s", mode, err, out)
}
cmd = testenv.Command(t, exe)
out, err = cmd.CombinedOutput()
if err != nil {
t.Errorf("executable failed to run (%s): %v\n%s", mode, err, out)
}
if string(out) != "hello\n" {
t.Errorf("unexpected output (%s):\n%s", mode, out)
}
out, err = testenv.Command(t, testenv.GoToolPath(t), "tool", "nm", exe).CombinedOutput()
if err != nil {
t.Errorf("nm failure: %s\n%s\n", err, string(out))
}
if ok, _ := regexp.Match("T runtime.deferreturn(\\+0)?-tramp0", out); !ok {
t.Errorf("Trampoline T runtime.deferreturn(+0)?-tramp0 is missing")
}
}
}
const testTrampCgoSrc = `
package main
// #include <stdio.h>
// void CHello() { printf("hello\n"); fflush(stdout); }
import "C"
func main() {
C.CHello()
}
`
func TestTrampolineCgo(t *testing.T) {
// Test that trampoline insertion works for cgo code.
// For stress test, we set -debugtramp=2 flag, which sets a very low
// threshold for trampoline generation, and essentially all cross-package
// calls will use trampolines.
buildmodes := []string{"default"}
switch runtime.GOARCH {
case "arm", "arm64", "ppc64", "loong64":
case "ppc64le":
// Trampolines are generated differently when internal linking PIE, test them too.
buildmodes = append(buildmodes, "pie")
default:
t.Skipf("trampoline insertion is not implemented on %s", runtime.GOARCH)
}
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "hello.go")
err := os.WriteFile(src, []byte(testTrampCgoSrc), 0666)
if err != nil {
t.Fatal(err)
}
exe := filepath.Join(tmpdir, "hello.exe")
for _, mode := range buildmodes {
cmd := goCmd(t, "build", "-buildmode="+mode, "-ldflags=-debugtramp=2", "-o", exe, src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("build (%s) failed: %v\n%s", mode, err, out)
}
cmd = testenv.Command(t, exe)
out, err = cmd.CombinedOutput()
if err != nil {
t.Errorf("executable failed to run (%s): %v\n%s", mode, err, out)
}
if string(out) != "hello\n" && string(out) != "hello\r\n" {
t.Errorf("unexpected output (%s):\n%s", mode, out)
}
// Test internal linking mode.
if !testenv.CanInternalLink(true) {
continue
}
cmd = goCmd(t, "build", "-buildmode="+mode, "-ldflags=-debugtramp=2 -linkmode=internal", "-o", exe, src)
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("build (%s) failed: %v\n%s", mode, err, out)
}
cmd = testenv.Command(t, exe)
out, err = cmd.CombinedOutput()
if err != nil {
t.Errorf("executable failed to run (%s): %v\n%s", mode, err, out)
}
if string(out) != "hello\n" && string(out) != "hello\r\n" {
t.Errorf("unexpected output (%s):\n%s", mode, out)
}
}
}
func TestIndexMismatch(t *testing.T) {
// Test that index mismatch will cause a link-time error (not run-time error).
// This shouldn't happen with "go build". We invoke the compiler and the linker
// manually, and try to "trick" the linker with an inconsistent object file.
testenv.MustHaveGoBuild(t)
// N.B. the build below explictly doesn't pass through
// -asan/-msan/-race, so we don't care about those.
testenv.MustInternalLink(t, testenv.NoSpecialBuildTypes)
t.Parallel()
tmpdir := t.TempDir()
aSrc := filepath.Join("testdata", "testIndexMismatch", "a.go")
bSrc := filepath.Join("testdata", "testIndexMismatch", "b.go")
mSrc := filepath.Join("testdata", "testIndexMismatch", "main.go")
aObj := filepath.Join(tmpdir, "a.o")
mObj := filepath.Join(tmpdir, "main.o")
exe := filepath.Join(tmpdir, "main.exe")
importcfgFile := filepath.Join(tmpdir, "runtime.importcfg")
testenv.WriteImportcfg(t, importcfgFile, nil, "runtime")
importcfgWithAFile := filepath.Join(tmpdir, "witha.importcfg")
testenv.WriteImportcfg(t, importcfgWithAFile, map[string]string{"a": aObj}, "runtime")
// Build a program with main package importing package a.
cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-importcfg="+importcfgFile, "-p=a", "-o", aObj, aSrc)
t.Log(cmd)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("compiling a.go failed: %v\n%s", err, out)
}
cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-importcfg="+importcfgWithAFile, "-p=main", "-I", tmpdir, "-o", mObj, mSrc)
t.Log(cmd)
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("compiling main.go failed: %v\n%s", err, out)
}
cmd = linkCmd(t, "-importcfg="+importcfgWithAFile, "-L", tmpdir, "-o", exe, mObj)
t.Log(cmd)
out, err = cmd.CombinedOutput()
if err != nil {
if runtime.GOOS == "android" && runtime.GOARCH == "arm64" {
testenv.SkipFlaky(t, 58806)
}
t.Errorf("linking failed: %v\n%s", err, out)
}
// Now, overwrite a.o with the object of b.go. This should
// result in an index mismatch.
cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-importcfg="+importcfgFile, "-p=a", "-o", aObj, bSrc)
t.Log(cmd)
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("compiling a.go failed: %v\n%s", err, out)
}
cmd = linkCmd(t, "-importcfg="+importcfgWithAFile, "-L", tmpdir, "-o", exe, mObj)
t.Log(cmd)
out, err = cmd.CombinedOutput()
if err == nil {
t.Fatalf("linking didn't fail")
}
if !bytes.Contains(out, []byte("fingerprint mismatch")) {
t.Errorf("did not see expected error message. out:\n%s", out)
}
}
func TestPErsrcBinutils(t *testing.T) {
// Test that PE rsrc section is handled correctly (issue 39658).
testenv.MustHaveGoBuild(t)
if (runtime.GOARCH != "386" && runtime.GOARCH != "amd64") || runtime.GOOS != "windows" {
// This test is limited to amd64 and 386, because binutils is limited as such
t.Skipf("this is only for windows/amd64 and windows/386")
}
t.Parallel()
tmpdir := t.TempDir()
pkgdir := filepath.Join("testdata", "pe-binutils")
exe := filepath.Join(tmpdir, "a.exe")
cmd := goCmd(t, "build", "-o", exe)
cmd.Dir = pkgdir
// cmd.Env = append(os.Environ(), "GOOS=windows", "GOARCH=amd64") // uncomment if debugging in a cross-compiling environment
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("building failed: %v, output:\n%s", err, out)
}
// Check that the binary contains the rsrc data
b, err := os.ReadFile(exe)
if err != nil {
t.Fatalf("reading output failed: %v", err)
}
if !bytes.Contains(b, []byte("Hello Gophers!")) {
t.Fatalf("binary does not contain expected content")
}
}
func TestPErsrcLLVM(t *testing.T) {
// Test that PE rsrc section is handled correctly (issue 39658).
testenv.MustHaveGoBuild(t)
if runtime.GOOS != "windows" {
t.Skipf("this is a windows-only test")
}
t.Parallel()
tmpdir := t.TempDir()
pkgdir := filepath.Join("testdata", "pe-llvm")
exe := filepath.Join(tmpdir, "a.exe")
cmd := goCmd(t, "build", "-o", exe)
cmd.Dir = pkgdir
// cmd.Env = append(os.Environ(), "GOOS=windows", "GOARCH=amd64") // uncomment if debugging in a cross-compiling environment
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("building failed: %v, output:\n%s", err, out)
}
// Check that the binary contains the rsrc data
b, err := os.ReadFile(exe)
if err != nil {
t.Fatalf("reading output failed: %v", err)
}
if !bytes.Contains(b, []byte("resname RCDATA a.rc")) {
t.Fatalf("binary does not contain expected content")
}
}
func TestContentAddressableSymbols(t *testing.T) {
// Test that the linker handles content-addressable symbols correctly.
testenv.MustHaveGoBuild(t)
t.Parallel()
src := filepath.Join("testdata", "testHashedSyms", "p.go")
cmd := goCmd(t, "run", src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Errorf("command %s failed: %v\n%s", cmd, err, out)
}
}
func TestReadOnly(t *testing.T) {
// Test that read-only data is indeed read-only.
testenv.MustHaveGoBuild(t)
t.Parallel()
src := filepath.Join("testdata", "testRO", "x.go")
cmd := goCmd(t, "run", src)
out, err := cmd.CombinedOutput()
if err == nil {
t.Errorf("running test program did not fail. output:\n%s", out)
}
}
const testIssue38554Src = `
package main
type T [10<<20]byte
//go:noinline
func f() T {
return T{} // compiler will make a large stmp symbol, but not used.
}
func main() {
x := f()
println(x[1])
}
`
func TestIssue38554(t *testing.T) {
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "x.go")
err := os.WriteFile(src, []byte(testIssue38554Src), 0666)
if err != nil {
t.Fatalf("failed to write source file: %v", err)
}
exe := filepath.Join(tmpdir, "x.exe")
cmd := goCmd(t, "build", "-o", exe, src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("build failed: %v\n%s", err, out)
}
fi, err := os.Stat(exe)
if err != nil {
t.Fatalf("failed to stat output file: %v", err)
}
// The test program is not much different from a helloworld, which is
// typically a little over 1 MB. We allow 5 MB. If the bad stmp is live,
// it will be over 10 MB.
const want = 5 << 20
if got := fi.Size(); got > want {
t.Errorf("binary too big: got %d, want < %d", got, want)
}
}
const testIssue42396src = `
package main
//go:noinline
//go:nosplit
func callee(x int) {
}
func main() {
callee(9)
}
`
func TestIssue42396(t *testing.T) {
testenv.MustHaveGoBuild(t)
if !platform.RaceDetectorSupported(runtime.GOOS, runtime.GOARCH) {
t.Skip("no race detector support")
}
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "main.go")
err := os.WriteFile(src, []byte(testIssue42396src), 0666)
if err != nil {
t.Fatalf("failed to write source file: %v", err)
}
exe := filepath.Join(tmpdir, "main.exe")
cmd := goCmd(t, "build", "-gcflags=-race", "-o", exe, src)
out, err := cmd.CombinedOutput()
if err == nil {
t.Fatalf("build unexpectedly succeeded")
}
// Check to make sure that we see a reasonable error message
// and not a panic.
if strings.Contains(string(out), "panic:") {
t.Fatalf("build should not fail with panic:\n%s", out)
}
const want = "reference to undefined builtin"
if !strings.Contains(string(out), want) {
t.Fatalf("error message incorrect: expected it to contain %q but instead got:\n%s\n", want, out)
}
}
const testLargeRelocSrc = `
package main
var x = [1<<25]byte{1<<23: 23, 1<<24: 24}
var addr = [...]*byte{
&x[1<<23-1],
&x[1<<23],
&x[1<<23+1],
&x[1<<24-1],
&x[1<<24],
&x[1<<24+1],
}
func main() {
// check relocations in instructions
check(x[1<<23-1], 0)
check(x[1<<23], 23)
check(x[1<<23+1], 0)
check(x[1<<24-1], 0)
check(x[1<<24], 24)
check(x[1<<24+1], 0)
// check absolute address relocations in data
check(*addr[0], 0)
check(*addr[1], 23)
check(*addr[2], 0)
check(*addr[3], 0)
check(*addr[4], 24)
check(*addr[5], 0)
}
func check(x, y byte) {
if x != y {
panic("FAIL")
}
}
`
func TestLargeReloc(t *testing.T) {
// Test that large relocation addend is handled correctly.
// In particular, on darwin/arm64 when external linking,
// Mach-O relocation has only 24-bit addend. See issue #42738.
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "x.go")
err := os.WriteFile(src, []byte(testLargeRelocSrc), 0666)
if err != nil {
t.Fatalf("failed to write source file: %v", err)
}
cmd := goCmd(t, "run", src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Errorf("build failed: %v. output:\n%s", err, out)
}
if testenv.HasCGO() { // currently all targets that support cgo can external link
cmd = goCmd(t, "run", "-ldflags=-linkmode=external", src)
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("build failed: %v. output:\n%s", err, out)
}
}
}
func TestUnlinkableObj(t *testing.T) {
// Test that the linker emits an error with unlinkable object.
testenv.MustHaveGoBuild(t)
t.Parallel()
if true /* was buildcfg.Experiment.Unified */ {
t.Skip("TODO(mdempsky): Fix ICE when importing unlinkable objects for GOEXPERIMENT=unified")
}
tmpdir := t.TempDir()
xSrc := filepath.Join(tmpdir, "x.go")
pSrc := filepath.Join(tmpdir, "p.go")
xObj := filepath.Join(tmpdir, "x.o")
pObj := filepath.Join(tmpdir, "p.o")
exe := filepath.Join(tmpdir, "x.exe")
importcfgfile := filepath.Join(tmpdir, "importcfg")
testenv.WriteImportcfg(t, importcfgfile, map[string]string{"p": pObj})
err := os.WriteFile(xSrc, []byte("package main\nimport _ \"p\"\nfunc main() {}\n"), 0666)
if err != nil {
t.Fatalf("failed to write source file: %v", err)
}
err = os.WriteFile(pSrc, []byte("package p\n"), 0666)
if err != nil {
t.Fatalf("failed to write source file: %v", err)
}
cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-importcfg="+importcfgfile, "-o", pObj, pSrc) // without -p
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("compile p.go failed: %v. output:\n%s", err, out)
}
cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-importcfg="+importcfgfile, "-p=main", "-o", xObj, xSrc)
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("compile x.go failed: %v. output:\n%s", err, out)
}
cmd = linkCmd(t, "-importcfg="+importcfgfile, "-o", exe, xObj)
out, err = cmd.CombinedOutput()
if err == nil {
t.Fatalf("link did not fail")
}
if !bytes.Contains(out, []byte("unlinkable object")) {
t.Errorf("did not see expected error message. out:\n%s", out)
}
// It is okay to omit -p for (only) main package.
cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-importcfg="+importcfgfile, "-p=p", "-o", pObj, pSrc)
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("compile p.go failed: %v. output:\n%s", err, out)
}
cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-importcfg="+importcfgfile, "-o", xObj, xSrc) // without -p
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("compile failed: %v. output:\n%s", err, out)
}
cmd = linkCmd(t, "-importcfg="+importcfgfile, "-o", exe, xObj)
out, err = cmd.CombinedOutput()
if err != nil {
t.Errorf("link failed: %v. output:\n%s", err, out)
}
}
func TestExtLinkCmdlineDeterminism(t *testing.T) {
// Test that we pass flags in deterministic order to the external linker
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t) // this test requires -linkmode=external
t.Parallel()
// test source code, with some cgo exports
testSrc := `
package main
import "C"
//export F1
func F1() {}
//export F2
func F2() {}
//export F3
func F3() {}
func main() {}
`
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "x.go")
if err := os.WriteFile(src, []byte(testSrc), 0666); err != nil {
t.Fatal(err)
}
exe := filepath.Join(tmpdir, "x.exe")
// Use a deterministic tmp directory so the temporary file paths are
// deterministic.
linktmp := filepath.Join(tmpdir, "linktmp")
if err := os.Mkdir(linktmp, 0777); err != nil {
t.Fatal(err)
}
// Link with -v -linkmode=external to see the flags we pass to the
// external linker.
ldflags := "-ldflags=-v -linkmode=external -tmpdir=" + linktmp
var out0 []byte
for i := 0; i < 5; i++ {
cmd := goCmd(t, "build", ldflags, "-o", exe, src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("build failed: %v, output:\n%s", err, out)
}
if err := os.Remove(exe); err != nil {
t.Fatal(err)
}
// extract the "host link" invocation
j := bytes.Index(out, []byte("\nhost link:"))
if j == -1 {
t.Fatalf("host link step not found, output:\n%s", out)
}
out = out[j+1:]
k := bytes.Index(out, []byte("\n"))
if k == -1 {
t.Fatalf("no newline after host link, output:\n%s", out)
}
out = out[:k]
// filter out output file name, which is passed by the go
// command and is nondeterministic.
fs := bytes.Fields(out)
for i, f := range fs {
if bytes.Equal(f, []byte(`"-o"`)) && i+1 < len(fs) {
fs[i+1] = []byte("a.out")
break
}
}
out = bytes.Join(fs, []byte{' '})
if i == 0 {
out0 = out
continue
}
if !bytes.Equal(out0, out) {
t.Fatalf("output differ:\n%s\n==========\n%s", out0, out)
}
}
}
// TestResponseFile tests that creating a response file to pass to the
// external linker works correctly.
func TestResponseFile(t *testing.T) {
t.Parallel()
testenv.MustHaveGoBuild(t)
// This test requires -linkmode=external. Currently all
// systems that support cgo support -linkmode=external.
testenv.MustHaveCGO(t)
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "x.go")
if err := os.WriteFile(src, []byte(`package main; import "C"; func main() {}`), 0666); err != nil {
t.Fatal(err)
}
// We don't use goCmd here, as -toolexec doesn't use response files.
// This test is more for the go command than the linker anyhow.
cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-o", "output", "x.go")
cmd.Dir = tmpdir
// Add enough arguments to push cmd/link into creating a response file.
var sb strings.Builder
sb.WriteString(`'-ldflags=all="-extldflags=`)
for i := 0; i < sys.ExecArgLengthLimit/len("-g"); i++ {
if i > 0 {
sb.WriteString(" ")
}
sb.WriteString("-g")
}
sb.WriteString(`"'`)
cmd = testenv.CleanCmdEnv(cmd)
cmd.Env = append(cmd.Env, "GOFLAGS="+sb.String())
out, err := cmd.CombinedOutput()
if len(out) > 0 {
t.Logf("%s", out)
}
if err != nil {
t.Error(err)
}
}
func TestDynimportVar(t *testing.T) {
// Test that we can access dynamically imported variables.
// Currently darwin only.
if runtime.GOOS != "darwin" {
t.Skip("skip on non-darwin platform")
}
testenv.MustHaveGoBuild(t)
testenv.MustHaveCGO(t)
t.Parallel()
tmpdir := t.TempDir()
exe := filepath.Join(tmpdir, "a.exe")
src := filepath.Join("testdata", "dynimportvar", "main.go")
for _, mode := range []string{"internal", "external"} {
cmd := goCmd(t, "build", "-ldflags=-linkmode="+mode, "-o", exe, src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("build (linkmode=%s) failed: %v\n%s", mode, err, out)
}
cmd = testenv.Command(t, exe)
out, err = cmd.CombinedOutput()
if err != nil {
t.Errorf("executable failed to run (%s): %v\n%s", mode, err, out)
}
}
}
const helloSrc = `
package main
var X = 42
var Y int
func main() { println("hello", X, Y) }
`
func TestFlagS(t *testing.T) {
// Test that the -s flag strips the symbol table.
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
exe := filepath.Join(tmpdir, "a.exe")
src := filepath.Join(tmpdir, "a.go")
err := os.WriteFile(src, []byte(helloSrc), 0666)
if err != nil {
t.Fatal(err)
}
modes := []string{"auto"}
if testenv.HasCGO() {
modes = append(modes, "external")
}
// check a text symbol, a data symbol, and a BSS symbol
syms := []string{"main.main", "main.X", "main.Y"}
for _, mode := range modes {
cmd := goCmd(t, "build", "-ldflags=-s -linkmode="+mode, "-o", exe, src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("build (linkmode=%s) failed: %v\n%s", mode, err, out)
}
cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "nm", exe)
out, err = cmd.CombinedOutput()
if err != nil {
if _, ok := errors.AsType[*exec.ExitError](err); !ok {
// Error exit is fine as it may have no symbols.
// On darwin we need to emit dynamic symbol references so it
// actually has some symbols, and nm succeeds.
t.Errorf("(mode=%s) go tool nm failed: %v\n%s", mode, err, out)
}
}
for _, s := range syms {
if bytes.Contains(out, []byte(s)) {
t.Errorf("(mode=%s): unexpected symbol %s", mode, s)
}
}
}
}
func TestRandLayout(t *testing.T) {
// Test that the -randlayout flag randomizes function order and
// generates a working binary.
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "hello.go")
err := os.WriteFile(src, []byte(trivialSrc), 0666)
if err != nil {
t.Fatal(err)
}
var syms [2]string
for i, seed := range []string{"123", "456"} {
exe := filepath.Join(tmpdir, "hello"+seed+".exe")
cmd := goCmd(t, "build", "-ldflags=-randlayout="+seed, "-o", exe, src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("seed=%v: build failed: %v\n%s", seed, err, out)
}
cmd = testenv.Command(t, exe)
err = cmd.Run()
if err != nil {
t.Fatalf("seed=%v: executable failed to run: %v\n%s", seed, err, out)
}
cmd = testenv.Command(t, testenv.GoToolPath(t), "tool", "nm", exe)
out, err = cmd.CombinedOutput()
if err != nil {
t.Fatalf("seed=%v: fail to run \"go tool nm\": %v\n%s", seed, err, out)
}
syms[i] = string(out)
}
if syms[0] == syms[1] {
t.Errorf("randlayout with different seeds produced same layout:\n%s\n===\n\n%s", syms[0], syms[1])
}
}
func TestCheckLinkname(t *testing.T) {
// Test that code containing blocked linknames does not build.
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
tests := []struct {
src string
ok bool
}{
// use (instantiation) of public API is ok
{"ok.go", true},
// push linkname is ok
{"push.go", true},
// using a linknamed variable to reference an assembly
// function in the same package is ok
{"textvar", true},
// pull linkname of blocked symbol is not ok
{"coro.go", false},
{"coro_var.go", false},
// assembly reference is not ok
{"coro_asm", false},
// pull-only linkname is not ok
{"coro2.go", false},
// pull linkname of a builtin symbol is not ok
{"builtin.go", false},
{"addmoduledata.go", false},
{"freegc.go", false},
// legacy bad linkname is ok, for now
{"fastrand.go", true},
{"badlinkname.go", true},
}
for _, test := range tests {
test := test
t.Run(test.src, func(t *testing.T) {
t.Parallel()
src := "./testdata/linkname/" + test.src
exe := filepath.Join(tmpdir, test.src+".exe")
cmd := goCmd(t, "build", "-o", exe, src)
out, err := cmd.CombinedOutput()
if test.ok && err != nil {
t.Errorf("build failed unexpectedly: %v:\n%s", err, out)
}
if !test.ok && err == nil {
t.Errorf("build succeeded unexpectedly: %v:\n%s", err, out)
}
})
}
}
func TestLinknameBSS(t *testing.T) {
// Test that the linker chooses the right one as the definition
// for linknamed variables. See issue #72032.
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join("testdata", "linkname", "sched.go")
exe := filepath.Join(tmpdir, "sched.exe")
cmd := goCmd(t, "build", "-o", exe, src)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("build failed unexpectedly: %v:\n%s", err, out)
}
// Check the symbol size.
f, err := objfile.Open(exe)
if err != nil {
t.Fatalf("fail to open executable: %v", err)
}
defer f.Close()
syms, err := f.Symbols()
if err != nil {
t.Fatalf("fail to get symbols: %v", err)
}
found := false
for _, s := range syms {
if s.Name == "runtime.sched" || s.Name == "_runtime.sched" {
found = true
if s.Size < 100 {
// As of Go 1.25 (Mar 2025), runtime.sched has 6848 bytes on
// darwin/arm64. It should always be larger than 100 bytes on
// all platforms.
t.Errorf("runtime.sched symbol size too small: want > 100, got %d", s.Size)
}
}
}
if !found {
t.Errorf("runtime.sched symbol not found")
}
// Executable should run.
cmd = testenv.Command(t, exe)
out, err = cmd.CombinedOutput()
if err != nil {
t.Errorf("executable failed to run: %v\n%s", err, out)
}
}
// setValueFromBytes copies from a []byte to a variable.
// This is used to get correctly aligned values in TestFuncdataPlacement.
func setValueFromBytes[T any](p *T, s []byte) {
copy(unsafe.Slice((*byte)(unsafe.Pointer(p)), unsafe.Sizeof(*p)), s)
}
// Test that all funcdata values are stored in the .gopclntab section.
// This is pretty ugly as there is no API for accessing this data.
// This test will have to be updated when the data formats change.
func TestFuncdataPlacement(t *testing.T) {
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "x.go")
if err := os.WriteFile(src, []byte(trivialSrc), 0o444); err != nil {
t.Fatal(err)
}
exe := filepath.Join(tmpdir, "x.exe")
cmd := goCmd(t, "build", "-o", exe, src)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("build failed; %v, output:\n%s", err, out)
}
// We want to find the funcdata in the executable.
// We look at the section table to find the .gopclntab section,
// which starts with the pcHeader.
// That will give us the table of functions,
// which we can use to find the funcdata.
ef, _ := elf.Open(exe)
mf, _ := macho.Open(exe)
pf, _ := pe.Open(exe)
xf, _ := xcoff.Open(exe)
// TODO: plan9
if ef == nil && mf == nil && pf == nil && xf == nil {
t.Skip("unrecognized executable file format")
}
const moddataSymName = "runtime.firstmoduledata"
const gofuncSymName = "go:func.*"
var (
pclntab []byte
pclntabAddr uint64
pclntabEnd uint64
moddataAddr uint64
moddataBytes []byte
gofuncAddr uint64
imageBase uint64
)
switch {
case ef != nil:
defer ef.Close()
syms, err := ef.Symbols()
if err != nil {
t.Fatal(err)
}
for _, sym := range syms {
switch sym.Name {
case moddataSymName:
moddataAddr = sym.Value
case gofuncSymName:
gofuncAddr = sym.Value
}
}
for _, sec := range ef.Sections {
if sec.Name == ".gopclntab" {
data, err := sec.Data()
if err != nil {
t.Fatal(err)
}
pclntab = data
pclntabAddr = sec.Addr
pclntabEnd = sec.Addr + sec.Size
}
if sec.Flags&elf.SHF_ALLOC != 0 && moddataAddr >= sec.Addr && moddataAddr < sec.Addr+sec.Size {
data, err := sec.Data()
if err != nil {
t.Fatal(err)
}
moddataBytes = data[moddataAddr-sec.Addr:]
}
}
case mf != nil:
defer mf.Close()
for _, sym := range mf.Symtab.Syms {
switch sym.Name {
case moddataSymName:
moddataAddr = sym.Value
case gofuncSymName:
gofuncAddr = sym.Value
}
}
for _, sec := range mf.Sections {
if sec.Name == "__gopclntab" {
data, err := sec.Data()
if err != nil {
t.Fatal(err)
}
pclntab = data
pclntabAddr = sec.Addr
pclntabEnd = sec.Addr + sec.Size
}
if moddataAddr >= sec.Addr && moddataAddr < sec.Addr+sec.Size {
data, err := sec.Data()
if err != nil {
t.Fatal(err)
}
moddataBytes = data[moddataAddr-sec.Addr:]
}
}
case pf != nil:
defer pf.Close()
switch ohdr := pf.OptionalHeader.(type) {
case *pe.OptionalHeader32:
imageBase = uint64(ohdr.ImageBase)
case *pe.OptionalHeader64:
imageBase = ohdr.ImageBase
}
var moddataSym, gofuncSym, pclntabSym, epclntabSym *pe.Symbol
for _, sym := range pf.Symbols {
switch sym.Name {
case moddataSymName:
moddataSym = sym
case gofuncSymName:
gofuncSym = sym
case "runtime.pclntab":
pclntabSym = sym
case "runtime.epclntab":
epclntabSym = sym
}
}
if moddataSym == nil {
t.Fatalf("could not find symbol %s", moddataSymName)
}
if gofuncSym == nil {
t.Fatalf("could not find symbol %s", gofuncSymName)
}
if pclntabSym == nil {
t.Fatal("could not find symbol runtime.pclntab")
}
if epclntabSym == nil {
t.Fatal("could not find symbol runtime.epclntab")
}
sec := pf.Sections[moddataSym.SectionNumber-1]
data, err := sec.Data()
if err != nil {
t.Fatal(err)
}
moddataBytes = data[moddataSym.Value:]
moddataAddr = uint64(sec.VirtualAddress + moddataSym.Value)
sec = pf.Sections[gofuncSym.SectionNumber-1]
gofuncAddr = uint64(sec.VirtualAddress + gofuncSym.Value)
if pclntabSym.SectionNumber != epclntabSym.SectionNumber {
t.Fatalf("runtime.pclntab section %d != runtime.epclntab section %d", pclntabSym.SectionNumber, epclntabSym.SectionNumber)
}
sec = pf.Sections[pclntabSym.SectionNumber-1]
data, err = sec.Data()
if err != nil {
t.Fatal(err)
}
pclntab = data[pclntabSym.Value:epclntabSym.Value]
pclntabAddr = uint64(sec.VirtualAddress + pclntabSym.Value)
pclntabEnd = uint64(sec.VirtualAddress + epclntabSym.Value)
case xf != nil:
defer xf.Close()
var moddataSym, gofuncSym, pclntabSym, epclntabSym *xcoff.Symbol
for _, sym := range xf.Symbols {
switch sym.Name {
case moddataSymName:
moddataSym = sym
case gofuncSymName:
gofuncSym = sym
case "runtime.pclntab":
pclntabSym = sym
case "runtime.epclntab":
epclntabSym = sym
}
}
if moddataSym == nil {
t.Fatalf("could not find symbol %s", moddataSymName)
}
if gofuncSym == nil {
t.Fatalf("could not find symbol %s", gofuncSymName)
}
if pclntabSym == nil {
t.Fatal("could not find symbol runtime.pclntab")
}
if epclntabSym == nil {
t.Fatal("could not find symbol runtime.epclntab")
}
sec := xf.Sections[moddataSym.SectionNumber-1]
data, err := sec.Data()
if err != nil {
t.Fatal(err)
}
moddataBytes = data[moddataSym.Value:]
moddataAddr = uint64(sec.VirtualAddress + moddataSym.Value)
sec = xf.Sections[gofuncSym.SectionNumber-1]
gofuncAddr = uint64(sec.VirtualAddress + gofuncSym.Value)
if pclntabSym.SectionNumber != epclntabSym.SectionNumber {
t.Fatalf("runtime.pclntab section %d != runtime.epclntab section %d", pclntabSym.SectionNumber, epclntabSym.SectionNumber)
}
sec = xf.Sections[pclntabSym.SectionNumber-1]
data, err = sec.Data()
if err != nil {
t.Fatal(err)
}
pclntab = data[pclntabSym.Value:epclntabSym.Value]
pclntabAddr = uint64(sec.VirtualAddress + pclntabSym.Value)
pclntabEnd = uint64(sec.VirtualAddress + epclntabSym.Value)
default:
panic("can't happen")
}
if len(pclntab) == 0 {
t.Fatal("could not find pclntab section")
}
if moddataAddr == 0 {
t.Fatalf("could not find %s symbol", moddataSymName)
}
if gofuncAddr == 0 {
t.Fatalf("could not find %s symbol", gofuncSymName)
}
if gofuncAddr < pclntabAddr || gofuncAddr >= pclntabEnd {
t.Fatalf("%s out of range: value %#x not between %#x and %#x", gofuncSymName, gofuncAddr, pclntabAddr, pclntabEnd)
}
if len(moddataBytes) == 0 {
t.Fatal("could not find module data")
}
// What a slice looks like in the object file.
type moddataSlice struct {
addr uintptr
len int
cap int
}
// This needs to match the struct defined in runtime/symtab.go,
// and written out by (*Link).symtab.
// This is not the complete moddata struct, only what we need here.
type moddataType struct {
pcHeader uintptr
funcnametab moddataSlice
cutab moddataSlice
filetab moddataSlice
pctab moddataSlice
pclntable moddataSlice
ftab moddataSlice
findfunctab uintptr
minpc, maxpc uintptr
text, etext uintptr
noptrdata, enoptrdata uintptr
data, edata uintptr
bss, ebss uintptr
noptrbss, enoptrbss uintptr
covctrs, ecovctrs uintptr
end, gcdata, gcbss uintptr
types, etypes uintptr
rodata uintptr
gofunc uintptr
}
// The executable is on the same system as we are running,
// so the sizes and alignments should match.
// But moddataBytes itself may not be aligned as needed.
// Copy to a variable to ensure alignment.
var moddata moddataType
setValueFromBytes(&moddata, moddataBytes)
ftabAddr := uint64(moddata.ftab.addr) - imageBase
if ftabAddr < pclntabAddr || ftabAddr >= pclntabEnd {
t.Fatalf("ftab address %#x not between %#x and %#x", ftabAddr, pclntabAddr, pclntabEnd)
}
// From runtime/symtab.go and the linker function writePCToFunc.
type functab struct {
entryoff uint32
funcoff uint32
}
// The ftab slice in moddata has one extra entry used to record
// the final PC.
ftabLen := moddata.ftab.len - 1
ftab := make([]functab, ftabLen)
copy(ftab, unsafe.Slice((*functab)(unsafe.Pointer(&pclntab[ftabAddr-pclntabAddr])), ftabLen))
ftabBase := uint64(moddata.pclntable.addr) - imageBase
// From runtime/runtime2.go _func and the linker function writeFuncs.
type funcEntry struct {
entryOff uint32
nameOff int32
args int32
deferreturn uint32
pcsp uint32
pcfile uint32
pcln uint32
npcdata uint32
cuOffset uint32
startLine int32
funcID abi.FuncID
flag abi.FuncFlag
_ [1]byte
nfuncdata uint8
}
for i, ftabEntry := range ftab {
funcAddr := ftabBase + uint64(ftabEntry.funcoff)
if funcAddr < pclntabAddr || funcAddr >= pclntabEnd {
t.Errorf("ftab entry %d address %#x not between %#x and %#x", i, funcAddr, pclntabAddr, pclntabEnd)
continue
}
var fe funcEntry
setValueFromBytes(&fe, pclntab[funcAddr-pclntabAddr:])
funcdataVals := funcAddr + uint64(unsafe.Sizeof(fe)) + uint64(fe.npcdata*4)
for j := range fe.nfuncdata {
var funcdataVal uint32
setValueFromBytes(&funcdataVal, pclntab[funcdataVals+uint64(j)*4-pclntabAddr:])
if funcdataVal == ^uint32(0) {
continue
}
funcdataAddr := gofuncAddr + uint64(funcdataVal)
if funcdataAddr < pclntabAddr || funcdataAddr >= pclntabEnd {
t.Errorf("ftab entry %d funcdata %d address %#x not between %#x and %#x", i, j, funcdataAddr, pclntabAddr, pclntabEnd)
}
}
}
if uint64(moddata.findfunctab)-imageBase < pclntabAddr || uint64(moddata.findfunctab)-imageBase >= pclntabEnd {
t.Errorf("findfunctab address %#x not between %#x and %#x", moddata.findfunctab, pclntabAddr, pclntabEnd)
}
}
// Test that moduledata winds up in its own .go.module section.
func TestModuledataPlacement(t *testing.T) {
testenv.MustHaveGoBuild(t)
t.Parallel()
tmpdir := t.TempDir()
src := filepath.Join(tmpdir, "x.go")
if err := os.WriteFile(src, []byte(trivialSrc), 0o444); err != nil {
t.Fatal(err)
}
exe := filepath.Join(tmpdir, "x.exe")
cmd := goCmd(t, "build", "-o", exe, src)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("build failed; %v, output:\n%s", err, out)
}
ef, _ := elf.Open(exe)
mf, _ := macho.Open(exe)
pf, _ := pe.Open(exe)
xf, _ := xcoff.Open(exe)
// TODO: plan9
if ef == nil && mf == nil && pf == nil && xf == nil {
t.Skip("unrecognized executable file format")
}
const moddataSymName = "runtime.firstmoduledata"
switch {
case ef != nil:
defer ef.Close()
syms, err := ef.Symbols()
if err != nil {
t.Fatal(err)
}
for _, sym := range syms {
if sym.Name == moddataSymName {
sec := ef.Sections[sym.Section]
if sec.Name != ".go.module" {
t.Errorf("moduledata in section %s, not .go.module", sec.Name)
}
if sym.Value != sec.Addr {
t.Errorf("moduledata address %#x != section start address %#x", sym.Value, sec.Addr)
}
break
}
}
case mf != nil:
defer mf.Close()
for _, sym := range mf.Symtab.Syms {
if sym.Name == moddataSymName {
if sym.Sect == 0 {
t.Error("moduledata not in a section")
} else {
sec := mf.Sections[sym.Sect-1]
if sec.Name != "__go_module" {
t.Errorf("moduledata in section %s, not __go.module", sec.Name)
}
if sym.Value != sec.Addr {
t.Errorf("moduledata address %#x != section start address %#x", sym.Value, sec.Addr)
}
}
break
}
}
case pf != nil, xf != nil:
if pf != nil {
defer pf.Close()
}
if xf != nil {
defer xf.Close()
}
// On Windows and AIX all the Go specific sections
// get stuffed into a few sections,
// so there is nothing to test here.
}
}
|