summaryrefslogtreecommitdiff
path: root/lib/spack/spack/build_environment.py
blob: c571689869215bb77b418bc22f602372d431b9d2 (plain) (blame)
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
# Copyright 2013-2024 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

"""
This module contains all routines related to setting up the package
build environment.  All of this is set up by package.py just before
install() is called.

There are two parts to the build environment:

1. Python build environment (i.e. install() method)

   This is how things are set up when install() is called.  Spack
   takes advantage of each package being in its own module by adding a
   bunch of command-like functions (like configure(), make(), etc.) in
   the package's module scope.  Ths allows package writers to call
   them all directly in Package.install() without writing 'self.'
   everywhere.  No, this isn't Pythonic.  Yes, it makes the code more
   readable and more like the shell script from which someone is
   likely porting.

2. Build execution environment

   This is the set of environment variables, like PATH, CC, CXX,
   etc. that control the build.  There are also a number of
   environment variables used to pass information (like RPATHs and
   other information about dependencies) to Spack's compiler wrappers.
   All of these env vars are also set up here.

Skimming this module is a nice way to get acquainted with the types of
calls you can make from within the install() function.
"""
import inspect
import io
import multiprocessing
import os
import re
import sys
import traceback
import types
from collections import defaultdict
from enum import Flag, auto
from itertools import chain
from typing import List, Tuple

import llnl.util.tty as tty
from llnl.string import plural
from llnl.util.filesystem import join_path
from llnl.util.lang import dedupe, stable_partition
from llnl.util.symlink import symlink
from llnl.util.tty.color import cescape, colorize
from llnl.util.tty.log import MultiProcessFd

import spack.build_systems.cmake
import spack.build_systems.meson
import spack.build_systems.python
import spack.builder
import spack.config
import spack.deptypes as dt
import spack.main
import spack.package_base
import spack.paths
import spack.platforms
import spack.repo
import spack.schema.environment
import spack.spec
import spack.store
import spack.subprocess_context
import spack.user_environment
import spack.util.path
import spack.util.pattern
from spack import traverse
from spack.context import Context
from spack.error import NoHeadersError, NoLibrariesError
from spack.install_test import spack_install_test_log
from spack.installer import InstallError
from spack.util.cpus import determine_number_of_jobs
from spack.util.environment import (
    SYSTEM_DIRS,
    EnvironmentModifications,
    env_flag,
    filter_system_paths,
    get_path,
    is_system_path,
    validate,
)
from spack.util.executable import Executable
from spack.util.log_parse import make_log_context, parse_log_events
from spack.util.module_cmd import load_module, module, path_from_modules

#
# This can be set by the user to globally disable parallel builds.
#
SPACK_NO_PARALLEL_MAKE = "SPACK_NO_PARALLEL_MAKE"

#
# These environment variables are set by
# set_wrapper_variables and used to pass parameters to
# Spack's compiler wrappers.
#
SPACK_ENV_PATH = "SPACK_ENV_PATH"
SPACK_INCLUDE_DIRS = "SPACK_INCLUDE_DIRS"
SPACK_LINK_DIRS = "SPACK_LINK_DIRS"
SPACK_RPATH_DIRS = "SPACK_RPATH_DIRS"
SPACK_RPATH_DEPS = "SPACK_RPATH_DEPS"
SPACK_LINK_DEPS = "SPACK_LINK_DEPS"
SPACK_PREFIX = "SPACK_PREFIX"
SPACK_INSTALL = "SPACK_INSTALL"
SPACK_DEBUG = "SPACK_DEBUG"
SPACK_SHORT_SPEC = "SPACK_SHORT_SPEC"
SPACK_DEBUG_LOG_ID = "SPACK_DEBUG_LOG_ID"
SPACK_DEBUG_LOG_DIR = "SPACK_DEBUG_LOG_DIR"
SPACK_CCACHE_BINARY = "SPACK_CCACHE_BINARY"
SPACK_SYSTEM_DIRS = "SPACK_SYSTEM_DIRS"

# Platform-specific library suffix.
if sys.platform == "darwin":
    dso_suffix = "dylib"
elif sys.platform == "win32":
    dso_suffix = "dll"
else:
    dso_suffix = "so"

stat_suffix = "lib" if sys.platform == "win32" else "a"


def jobserver_enabled():
    """Returns true if a posix jobserver (make) is detected."""
    return "MAKEFLAGS" in os.environ and "--jobserver" in os.environ["MAKEFLAGS"]


def get_effective_jobs(jobs, parallel=True, supports_jobserver=False):
    """Return the number of jobs, or None if supports_jobserver and a jobserver is detected."""
    if not parallel or jobs <= 1 or env_flag(SPACK_NO_PARALLEL_MAKE):
        return 1
    if supports_jobserver and jobserver_enabled():
        return None
    return jobs


class MakeExecutable(Executable):
    """Special callable executable object for make so the user can specify
    parallelism options on a per-invocation basis.  Specifying
    'parallel' to the call will override whatever the package's
    global setting is, so you can either default to true or false and
    override particular calls. Specifying 'jobs_env' to a particular
    call will name an environment variable which will be set to the
    parallelism level (without affecting the normal invocation with
    -j).
    """

    def __init__(self, name, jobs, **kwargs):
        supports_jobserver = kwargs.pop("supports_jobserver", True)
        super().__init__(name, **kwargs)
        self.supports_jobserver = supports_jobserver
        self.jobs = jobs

    def __call__(self, *args, **kwargs):
        """parallel, and jobs_env from kwargs are swallowed and used here;
        remaining arguments are passed through to the superclass.
        """
        parallel = kwargs.pop("parallel", True)
        jobs_env = kwargs.pop("jobs_env", None)
        jobs_env_supports_jobserver = kwargs.pop("jobs_env_supports_jobserver", False)

        jobs = get_effective_jobs(
            self.jobs, parallel=parallel, supports_jobserver=self.supports_jobserver
        )
        if jobs is not None:
            args = ("-j{0}".format(jobs),) + args

        if jobs_env:
            # Caller wants us to set an environment variable to
            # control the parallelism.
            jobs_env_jobs = get_effective_jobs(
                self.jobs, parallel=parallel, supports_jobserver=jobs_env_supports_jobserver
            )
            if jobs_env_jobs is not None:
                kwargs["extra_env"] = {jobs_env: str(jobs_env_jobs)}

        return super().__call__(*args, **kwargs)


def _on_cray():
    host_platform = spack.platforms.host()
    host_os = host_platform.operating_system("default_os")
    on_cray = str(host_platform) == "cray"
    using_cnl = re.match(r"cnl\d+", str(host_os))
    return on_cray, using_cnl


def clean_environment():
    # Stuff in here sanitizes the build environment to eliminate
    # anything the user has set that may interfere. We apply it immediately
    # unlike the other functions so it doesn't overwrite what the modules load.
    env = EnvironmentModifications()

    # Remove these vars from the environment during build because they
    # can affect how some packages find libraries.  We want to make
    # sure that builds never pull in unintended external dependencies.
    env.unset("LD_LIBRARY_PATH")
    env.unset("LD_RUN_PATH")
    env.unset("DYLD_LIBRARY_PATH")
    env.unset("DYLD_FALLBACK_LIBRARY_PATH")

    # These vars affect how the compiler finds libraries and include dirs.
    env.unset("LIBRARY_PATH")
    env.unset("CPATH")
    env.unset("C_INCLUDE_PATH")
    env.unset("CPLUS_INCLUDE_PATH")
    env.unset("OBJC_INCLUDE_PATH")

    env.unset("CMAKE_PREFIX_PATH")
    env.unset("PYTHONPATH")
    env.unset("R_HOME")
    env.unset("R_ENVIRON")

    # Affects GNU make, can e.g. indirectly inhibit enabling parallel build
    # env.unset('MAKEFLAGS')

    # Avoid that libraries of build dependencies get hijacked.
    env.unset("LD_PRELOAD")
    env.unset("DYLD_INSERT_LIBRARIES")

    # Avoid <packagename>_ROOT user variables overriding spack dependencies
    # https://cmake.org/cmake/help/latest/variable/PackageName_ROOT.html
    # Spack needs SPACK_ROOT though, so we need to exclude that
    for varname in os.environ.keys():
        if varname.endswith("_ROOT") and varname != "SPACK_ROOT":
            env.unset(varname)

    # On Cray "cluster" systems, unset CRAY_LD_LIBRARY_PATH to avoid
    # interference with Spack dependencies.
    # CNL requires these variables to be set (or at least some of them,
    # depending on the CNL version).
    on_cray, using_cnl = _on_cray()
    if on_cray and not using_cnl:
        env.unset("CRAY_LD_LIBRARY_PATH")
        for varname in os.environ.keys():
            if "PKGCONF" in varname:
                env.unset(varname)

    # Unset the following variables because they can affect installation of
    # Autotools and CMake packages.
    build_system_vars = [
        "CC",
        "CFLAGS",
        "CPP",
        "CPPFLAGS",  # C variables
        "CXX",
        "CCC",
        "CXXFLAGS",
        "CXXCPP",  # C++ variables
        "F77",
        "FFLAGS",
        "FLIBS",  # Fortran77 variables
        "FC",
        "FCFLAGS",
        "FCLIBS",  # Fortran variables
        "LDFLAGS",
        "LIBS",  # linker variables
    ]
    for v in build_system_vars:
        env.unset(v)

    # Unset mpi environment vars. These flags should only be set by
    # mpi providers for packages with mpi dependencies
    mpi_vars = ["MPICC", "MPICXX", "MPIFC", "MPIF77", "MPIF90"]
    for v in mpi_vars:
        env.unset(v)

    build_lang = spack.config.get("config:build_language")
    if build_lang:
        # Override language-related variables. This can be used to force
        # English compiler messages etc., which allows parse_log_events to
        # show useful matches.
        env.set("LC_ALL", build_lang)

    # Remove any macports installs from the PATH.  The macports ld can
    # cause conflicts with the built-in linker on el capitan.  Solves
    # assembler issues, e.g.:
    #    suffix or operands invalid for `movq'"
    path = get_path("PATH")
    for p in path:
        if "/macports/" in p:
            env.remove_path("PATH", p)

    return env


def _add_werror_handling(keep_werror, env):
    keep_flags = set()
    # set of pairs
    replace_flags: List[Tuple[str, str]] = []
    if keep_werror == "all":
        keep_flags.add("-Werror*")
    else:
        if keep_werror == "specific":
            keep_flags.add("-Werror-*")
            keep_flags.add("-Werror=*")
        # This extra case is to handle -Werror-implicit-function-declaration
        replace_flags.append(("-Werror-", "-Wno-error="))
        replace_flags.append(("-Werror", "-Wno-error"))
    env.set("SPACK_COMPILER_FLAGS_KEEP", "|".join(keep_flags))
    env.set("SPACK_COMPILER_FLAGS_REPLACE", " ".join(["|".join(item) for item in replace_flags]))


def set_compiler_environment_variables(pkg, env):
    assert pkg.spec.concrete
    compiler = pkg.compiler
    spec = pkg.spec

    # Make sure the executables for this compiler exist
    compiler.verify_executables()

    # Set compiler variables used by CMake and autotools
    assert all(key in compiler.link_paths for key in ("cc", "cxx", "f77", "fc"))

    # Populate an object with the list of environment modifications
    # and return it
    # TODO : add additional kwargs for better diagnostics, like requestor,
    # ttyout, ttyerr, etc.
    link_dir = spack.paths.build_env_path

    # Set SPACK compiler variables so that our wrapper knows what to
    # call.  If there is no compiler configured then use a default
    # wrapper which will emit an error if it is used.
    if compiler.cc:
        env.set("SPACK_CC", compiler.cc)
        env.set("CC", os.path.join(link_dir, compiler.link_paths["cc"]))
    else:
        env.set("CC", os.path.join(link_dir, "cc"))
    if compiler.cxx:
        env.set("SPACK_CXX", compiler.cxx)
        env.set("CXX", os.path.join(link_dir, compiler.link_paths["cxx"]))
    else:
        env.set("CC", os.path.join(link_dir, "c++"))
    if compiler.f77:
        env.set("SPACK_F77", compiler.f77)
        env.set("F77", os.path.join(link_dir, compiler.link_paths["f77"]))
    else:
        env.set("F77", os.path.join(link_dir, "f77"))
    if compiler.fc:
        env.set("SPACK_FC", compiler.fc)
        env.set("FC", os.path.join(link_dir, compiler.link_paths["fc"]))
    else:
        env.set("FC", os.path.join(link_dir, "fc"))

    # Set SPACK compiler rpath flags so that our wrapper knows what to use
    env.set("SPACK_CC_RPATH_ARG", compiler.cc_rpath_arg)
    env.set("SPACK_CXX_RPATH_ARG", compiler.cxx_rpath_arg)
    env.set("SPACK_F77_RPATH_ARG", compiler.f77_rpath_arg)
    env.set("SPACK_FC_RPATH_ARG", compiler.fc_rpath_arg)
    env.set("SPACK_LINKER_ARG", compiler.linker_arg)

    # Check whether we want to force RPATH or RUNPATH
    if spack.config.get("config:shared_linking:type") == "rpath":
        env.set("SPACK_DTAGS_TO_STRIP", compiler.enable_new_dtags)
        env.set("SPACK_DTAGS_TO_ADD", compiler.disable_new_dtags)
    else:
        env.set("SPACK_DTAGS_TO_STRIP", compiler.disable_new_dtags)
        env.set("SPACK_DTAGS_TO_ADD", compiler.enable_new_dtags)

    if pkg.keep_werror is not None:
        keep_werror = pkg.keep_werror
    else:
        keep_werror = spack.config.get("config:flags:keep_werror")

    _add_werror_handling(keep_werror, env)

    # Set the target parameters that the compiler will add
    # Don't set on cray platform because the targeting module handles this
    if spec.satisfies("platform=cray"):
        isa_arg = ""
    else:
        isa_arg = spec.architecture.target.optimization_flags(compiler)
    env.set("SPACK_TARGET_ARGS", isa_arg)

    # Trap spack-tracked compiler flags as appropriate.
    # env_flags are easy to accidentally override.
    inject_flags = {}
    env_flags = {}
    build_system_flags = {}
    for flag in spack.spec.FlagMap.valid_compiler_flags():
        # Always convert flag_handler to function type.
        # This avoids discrepencies in calling conventions between functions
        # and methods, or between bound and unbound methods in python 2.
        # We cannot effectively convert everything to a bound method, which
        # would be the simpler solution.
        if isinstance(pkg.flag_handler, types.FunctionType):
            handler = pkg.flag_handler
        else:
            handler = pkg.flag_handler.__func__

        injf, envf, bsf = handler(pkg, flag, spec.compiler_flags[flag][:])
        inject_flags[flag] = injf or []
        env_flags[flag] = envf or []
        build_system_flags[flag] = bsf or []

    # Place compiler flags as specified by flag_handler
    for flag in spack.spec.FlagMap.valid_compiler_flags():
        # Concreteness guarantees key safety here
        if inject_flags[flag]:
            # variables SPACK_<FLAG> inject flags through wrapper
            var_name = "SPACK_{0}".format(flag.upper())
            env.set(var_name, " ".join(f for f in inject_flags[flag]))
        if env_flags[flag]:
            # implicit variables
            env.set(flag.upper(), " ".join(f for f in env_flags[flag]))
    pkg.flags_to_build_system_args(build_system_flags)

    env.set("SPACK_COMPILER_SPEC", str(spec.compiler))

    env.set("SPACK_SYSTEM_DIRS", ":".join(SYSTEM_DIRS))

    compiler.setup_custom_environment(pkg, env)

    return env


def set_wrapper_variables(pkg, env):
    """Set environment variables used by the Spack compiler wrapper (which have the prefix
    `SPACK_`) and also add the compiler wrappers to PATH.

    This determines the injected -L/-I/-rpath options; each of these specifies a search order and
    this function computes these options in a manner that is intended to match the DAG traversal
    order in `SetupContext`. TODO: this is not the case yet, we're using post order, SetupContext
    is using topo order."""
    # Set environment variables if specified for
    # the given compiler
    compiler = pkg.compiler
    env.extend(spack.schema.environment.parse(compiler.environment))

    if compiler.extra_rpaths:
        extra_rpaths = ":".join(compiler.extra_rpaths)
        env.set("SPACK_COMPILER_EXTRA_RPATHS", extra_rpaths)

    # Add spack build environment path with compiler wrappers first in
    # the path. We add the compiler wrapper path, which includes default
    # wrappers (cc, c++, f77, f90), AND a subdirectory containing
    # compiler-specific symlinks.  The latter ensures that builds that
    # are sensitive to the *name* of the compiler see the right name when
    # we're building with the wrappers.
    #
    # Conflicts on case-insensitive systems (like "CC" and "cc") are
    # handled by putting one in the <build_env_path>/case-insensitive
    # directory.  Add that to the path too.
    env_paths = []
    compiler_specific = os.path.join(
        spack.paths.build_env_path, os.path.dirname(pkg.compiler.link_paths["cc"])
    )
    for item in [spack.paths.build_env_path, compiler_specific]:
        env_paths.append(item)
        ci = os.path.join(item, "case-insensitive")
        if os.path.isdir(ci):
            env_paths.append(ci)

    tty.debug("Adding compiler bin/ paths: " + " ".join(env_paths))
    for item in env_paths:
        env.prepend_path("PATH", item)
    env.set_path(SPACK_ENV_PATH, env_paths)

    # Working directory for the spack command itself, for debug logs.
    if spack.config.get("config:debug"):
        env.set(SPACK_DEBUG, "TRUE")
    env.set(SPACK_SHORT_SPEC, pkg.spec.short_spec)
    env.set(SPACK_DEBUG_LOG_ID, pkg.spec.format("{name}-{hash:7}"))
    env.set(SPACK_DEBUG_LOG_DIR, spack.main.spack_working_dir)

    # Find ccache binary and hand it to build environment
    if spack.config.get("config:ccache"):
        ccache = Executable("ccache")
        if not ccache:
            raise RuntimeError("No ccache binary found in PATH")
        env.set(SPACK_CCACHE_BINARY, ccache)

    # Gather information about various types of dependencies
    link_deps = set(pkg.spec.traverse(root=False, deptype=("link")))
    rpath_deps = get_rpath_deps(pkg)

    link_dirs = []
    include_dirs = []
    rpath_dirs = []

    def _prepend_all(list_to_modify, items_to_add):
        # Update the original list (creating a new list would be faster but
        # may not be convenient)
        for item in reversed(list(items_to_add)):
            list_to_modify.insert(0, item)

    def update_compiler_args_for_dep(dep):
        if dep in link_deps and (not is_system_path(dep.prefix)):
            query = pkg.spec[dep.name]
            dep_link_dirs = list()
            try:
                # In some circumstances (particularly for externals) finding
                # libraries packages can be time consuming, so indicate that
                # we are performing this operation (and also report when it
                # finishes).
                tty.debug("Collecting libraries for {0}".format(dep.name))
                dep_link_dirs.extend(query.libs.directories)
                tty.debug("Libraries for {0} have been collected.".format(dep.name))
            except NoLibrariesError:
                tty.debug("No libraries found for {0}".format(dep.name))

            for default_lib_dir in ["lib", "lib64"]:
                default_lib_prefix = os.path.join(dep.prefix, default_lib_dir)
                if os.path.isdir(default_lib_prefix):
                    dep_link_dirs.append(default_lib_prefix)

            _prepend_all(link_dirs, dep_link_dirs)
            if dep in rpath_deps:
                _prepend_all(rpath_dirs, dep_link_dirs)

            try:
                _prepend_all(include_dirs, query.headers.directories)
            except NoHeadersError:
                tty.debug("No headers found for {0}".format(dep.name))

    for dspec in pkg.spec.traverse(root=False, order="post"):
        if dspec.external:
            update_compiler_args_for_dep(dspec)

    # Just above, we prepended entries for -L/-rpath for externals. We
    # now do this for non-external packages so that Spack-built packages
    # are searched first for libraries etc.
    for dspec in pkg.spec.traverse(root=False, order="post"):
        if not dspec.external:
            update_compiler_args_for_dep(dspec)

    # The top-level package is always RPATHed. It hasn't been installed yet
    # so the RPATHs are added unconditionally (e.g. even though lib64/ may
    # not be created for the install).
    for libdir in ["lib64", "lib"]:
        lib_path = os.path.join(pkg.prefix, libdir)
        rpath_dirs.insert(0, lib_path)

    link_dirs = list(dedupe(filter_system_paths(link_dirs)))
    include_dirs = list(dedupe(filter_system_paths(include_dirs)))
    rpath_dirs = list(dedupe(filter_system_paths(rpath_dirs)))

    env.set(SPACK_LINK_DIRS, ":".join(link_dirs))
    env.set(SPACK_INCLUDE_DIRS, ":".join(include_dirs))
    env.set(SPACK_RPATH_DIRS, ":".join(rpath_dirs))


def set_package_py_globals(pkg, context: Context = Context.BUILD):
    """Populate the Python module of a package with some useful global names.
    This makes things easier for package writers.
    """
    module = ModuleChangePropagator(pkg)

    m = module

    if context == Context.BUILD:
        jobs = determine_number_of_jobs(parallel=pkg.parallel)
        m.make_jobs = jobs

        # TODO: make these build deps that can be installed if not found.
        m.make = MakeExecutable("make", jobs)
        m.gmake = MakeExecutable("gmake", jobs)
        m.ninja = MakeExecutable("ninja", jobs, supports_jobserver=False)
        # TODO: johnwparent: add package or builder support to define these build tools
        # for now there is no entrypoint for builders to define these on their
        # own
        if sys.platform == "win32":
            m.nmake = Executable("nmake")
            m.msbuild = Executable("msbuild")
            # analog to configure for win32
            m.cscript = Executable("cscript")

        # Find the configure script in the archive path
        # Don't use which for this; we want to find it in the current dir.
        m.configure = Executable("./configure")

        # Standard CMake arguments
        m.std_cmake_args = spack.build_systems.cmake.CMakeBuilder.std_args(pkg)
        m.std_meson_args = spack.build_systems.meson.MesonBuilder.std_args(pkg)
        m.std_pip_args = spack.build_systems.python.PythonPipBuilder.std_args(pkg)

    # Put spack compiler paths in module scope. (Some packages use it
    # in setup_run_environment etc, so don't put it context == build)
    link_dir = spack.paths.build_env_path
    m.spack_cc = os.path.join(link_dir, pkg.compiler.link_paths["cc"])
    m.spack_cxx = os.path.join(link_dir, pkg.compiler.link_paths["cxx"])
    m.spack_f77 = os.path.join(link_dir, pkg.compiler.link_paths["f77"])
    m.spack_fc = os.path.join(link_dir, pkg.compiler.link_paths["fc"])

    # Useful directories within the prefix are encapsulated in
    # a Prefix object.
    m.prefix = pkg.prefix

    # Platform-specific library suffix.
    m.dso_suffix = dso_suffix

    def static_to_shared_library(static_lib, shared_lib=None, **kwargs):
        compiler_path = kwargs.get("compiler", m.spack_cc)
        compiler = Executable(compiler_path)

        return _static_to_shared_library(
            pkg.spec.architecture, compiler, static_lib, shared_lib, **kwargs
        )

    m.static_to_shared_library = static_to_shared_library

    module.propagate_changes_to_mro()


def _static_to_shared_library(arch, compiler, static_lib, shared_lib=None, **kwargs):
    """
    Converts a static library to a shared library. The static library has to
    be built with PIC for the conversion to work.

    Parameters:
        static_lib (str): Path to the static library.
        shared_lib (str): Path to the shared library. Default is to derive
                          from the static library's path.

    Keyword arguments:
        compiler (str): Path to the compiler. Default is spack_cc.
        compiler_output: Where to print compiler output to.
        arguments (str list): Additional arguments for the compiler.
        version (str): Library version. Default is unspecified.
        compat_version (str): Library compatibility version. Default is
                              version.
    """
    compiler_output = kwargs.get("compiler_output", None)
    arguments = kwargs.get("arguments", [])
    version = kwargs.get("version", None)
    compat_version = kwargs.get("compat_version", version)

    if not shared_lib:
        shared_lib = "{0}.{1}".format(os.path.splitext(static_lib)[0], dso_suffix)

    compiler_args = []

    # TODO: Compiler arguments should not be hardcoded but provided by
    #       the different compiler classes.
    if "linux" in arch or "cray" in arch:
        soname = os.path.basename(shared_lib)

        if compat_version:
            soname += ".{0}".format(compat_version)

        compiler_args = [
            "-shared",
            "-Wl,-soname,{0}".format(soname),
            "-Wl,--whole-archive",
            static_lib,
            "-Wl,--no-whole-archive",
        ]
    elif "darwin" in arch:
        install_name = shared_lib

        if compat_version:
            install_name += ".{0}".format(compat_version)

        compiler_args = [
            "-dynamiclib",
            "-install_name",
            "{0}".format(install_name),
            "-Wl,-force_load,{0}".format(static_lib),
        ]

        if compat_version:
            compiler_args.extend(["-compatibility_version", "{0}".format(compat_version)])

        if version:
            compiler_args.extend(["-current_version", "{0}".format(version)])

    if len(arguments) > 0:
        compiler_args.extend(arguments)

    shared_lib_base = shared_lib

    if version:
        shared_lib += ".{0}".format(version)
    elif compat_version:
        shared_lib += ".{0}".format(compat_version)

    compiler_args.extend(["-o", shared_lib])

    # Create symlinks for version and compat_version
    shared_lib_link = os.path.basename(shared_lib)

    if version or compat_version:
        symlink(shared_lib_link, shared_lib_base)

    if compat_version and compat_version != version:
        symlink(shared_lib_link, "{0}.{1}".format(shared_lib_base, compat_version))

    return compiler(*compiler_args, output=compiler_output)


def get_rpath_deps(pkg):
    """Return immediate or transitive RPATHs depending on the package."""
    if pkg.transitive_rpaths:
        return [d for d in pkg.spec.traverse(root=False, deptype=("link"))]
    else:
        return pkg.spec.dependencies(deptype="link")


def get_rpaths(pkg):
    """Get a list of all the rpaths for a package."""
    rpaths = [pkg.prefix.lib, pkg.prefix.lib64]
    deps = get_rpath_deps(pkg)
    rpaths.extend(d.prefix.lib for d in deps if os.path.isdir(d.prefix.lib))
    rpaths.extend(d.prefix.lib64 for d in deps if os.path.isdir(d.prefix.lib64))
    # Second module is our compiler mod name. We use that to get rpaths from
    # module show output.
    if pkg.compiler.modules and len(pkg.compiler.modules) > 1:
        rpaths.append(path_from_modules([pkg.compiler.modules[1]]))
    return list(dedupe(filter_system_paths(rpaths)))


def load_external_modules(pkg):
    """Traverse a package's spec DAG and load any external modules.

    Traverse a package's dependencies and load any external modules
    associated with them.

    Args:
        pkg (spack.package_base.PackageBase): package to load deps for
    """
    for dep in list(pkg.spec.traverse()):
        external_modules = dep.external_modules or []
        for external_module in external_modules:
            load_module(external_module)


def setup_package(pkg, dirty, context: Context = Context.BUILD):
    """Execute all environment setup routines."""
    if context not in (Context.BUILD, Context.TEST):
        raise ValueError(f"'context' must be Context.BUILD or Context.TEST - got {context}")

    # First populate the package.py's module with the relevant globals that could be used in any
    # of the setup_* functions.
    setup_context = SetupContext(pkg.spec, context=context)
    setup_context.set_all_package_py_globals()

    # Keep track of env changes from packages separately, since we want to
    # issue warnings when packages make "suspicious" modifications.
    env_base = EnvironmentModifications() if dirty else clean_environment()
    env_mods = EnvironmentModifications()

    # setup compilers for build contexts
    need_compiler = context == Context.BUILD or (
        context == Context.TEST and pkg.test_requires_compiler
    )
    if need_compiler:
        set_compiler_environment_variables(pkg, env_mods)
        set_wrapper_variables(pkg, env_mods)

    # Platform specific setup goes before package specific setup. This is for setting
    # defaults like MACOSX_DEPLOYMENT_TARGET on macOS.
    platform = spack.platforms.by_name(pkg.spec.architecture.platform)
    target = platform.target(pkg.spec.architecture.target)
    platform.setup_platform_environment(pkg, env_mods)

    tty.debug("setup_package: grabbing modifications from dependencies")
    env_mods.extend(setup_context.get_env_modifications())
    tty.debug("setup_package: collected all modifications from dependencies")

    if context == Context.TEST:
        env_mods.prepend_path("PATH", ".")
    elif context == Context.BUILD and not dirty and not env_mods.is_unset("CPATH"):
        tty.debug(
            "A dependency has updated CPATH, this may lead pkg-config to assume that the package "
            "is part of the system includes and omit it when invoked with '--cflags'."
        )

    # First apply the clean environment changes
    env_base.apply_modifications()

    # Load modules on an already clean environment, just before applying Spack's
    # own environment modifications. This ensures Spack controls CC/CXX/... variables.
    if need_compiler:
        tty.debug("setup_package: loading compiler modules")
        for mod in pkg.compiler.modules:
            load_module(mod)

    # kludge to handle cray mpich and libsci being automatically loaded by
    # PrgEnv modules on cray platform. Module unload does no damage when
    # unnecessary
    on_cray, _ = _on_cray()
    if on_cray and not dirty:
        for mod in ["cray-mpich", "cray-libsci"]:
            module("unload", mod)

    if target.module_name:
        load_module(target.module_name)

    load_external_modules(pkg)

    implicit_rpaths = pkg.compiler.implicit_rpaths()
    if implicit_rpaths:
        env_mods.set("SPACK_COMPILER_IMPLICIT_RPATHS", ":".join(implicit_rpaths))

    # Make sure nothing's strange about the Spack environment.
    validate(env_mods, tty.warn)
    env_mods.apply_modifications()

    # Return all env modifications we controlled (excluding module related ones)
    env_base.extend(env_mods)
    return env_base


class EnvironmentVisitor:
    def __init__(self, *roots: spack.spec.Spec, context: Context):
        # For the roots (well, marked specs) we follow different edges
        # than for their deps, depending on the context.
        self.root_hashes = set(s.dag_hash() for s in roots)

        if context == Context.BUILD:
            # Drop direct run deps in build context
            # We don't really distinguish between install and build time test deps,
            # so we include them here as build-time test deps.
            self.root_depflag = dt.BUILD | dt.TEST | dt.LINK
        elif context == Context.TEST:
            # This is more of an extended run environment
            self.root_depflag = dt.TEST | dt.RUN | dt.LINK
        elif context == Context.RUN:
            self.root_depflag = dt.RUN | dt.LINK

    def neighbors(self, item):
        spec = item.edge.spec
        if spec.dag_hash() in self.root_hashes:
            depflag = self.root_depflag
        else:
            depflag = dt.LINK | dt.RUN
        return traverse.sort_edges(spec.edges_to_dependencies(depflag=depflag))


class UseMode(Flag):
    #: Entrypoint spec (a spec to be built; an env root, etc)
    ROOT = auto()

    #: A spec used at runtime, but no executables in PATH
    RUNTIME = auto()

    #: A spec used at runtime, with executables in PATH
    RUNTIME_EXECUTABLE = auto()

    #: A spec that's a direct build or test dep
    BUILDTIME_DIRECT = auto()

    #: A spec that should be visible in search paths in a build env.
    BUILDTIME = auto()

    #: Flag is set when the (node, mode) is finalized
    ADDED = auto()


def effective_deptypes(
    *specs: spack.spec.Spec, context: Context = Context.BUILD
) -> List[Tuple[spack.spec.Spec, UseMode]]:
    """Given a list of input specs and a context, return a list of tuples of
    all specs that contribute to (environment) modifications, together with
    a flag specifying in what way they do so. The list is ordered topologically
    from root to leaf, meaning that environment modifications should be applied
    in reverse so that dependents override dependencies, not the other way around."""
    visitor = traverse.TopoVisitor(
        EnvironmentVisitor(*specs, context=context),
        key=lambda x: x.dag_hash(),
        root=True,
        all_edges=True,
    )
    traverse.traverse_depth_first_with_visitor(traverse.with_artificial_edges(specs), visitor)

    # Dictionary with "no mode" as default value, so it's easy to write modes[x] |= flag.
    use_modes = defaultdict(lambda: UseMode(0))
    nodes_with_type = []

    for edge in visitor.edges:
        parent, child, depflag = edge.parent, edge.spec, edge.depflag

        # Mark the starting point
        if parent is None:
            use_modes[child] = UseMode.ROOT
            continue

        parent_mode = use_modes[parent]

        # Nothing to propagate.
        if not parent_mode:
            continue

        # Dependending on the context, include particular deps from the root.
        if UseMode.ROOT & parent_mode:
            if context == Context.BUILD:
                if (dt.BUILD | dt.TEST) & depflag:
                    use_modes[child] |= UseMode.BUILDTIME_DIRECT
                if dt.LINK & depflag:
                    use_modes[child] |= UseMode.BUILDTIME

            elif context == Context.TEST:
                if (dt.RUN | dt.TEST) & depflag:
                    use_modes[child] |= UseMode.RUNTIME_EXECUTABLE
                elif dt.LINK & depflag:
                    use_modes[child] |= UseMode.RUNTIME

            elif context == Context.RUN:
                if dt.RUN & depflag:
                    use_modes[child] |= UseMode.RUNTIME_EXECUTABLE
                elif dt.LINK & depflag:
                    use_modes[child] |= UseMode.RUNTIME

        # Propagate RUNTIME and RUNTIME_EXECUTABLE through link and run deps.
        if (UseMode.RUNTIME | UseMode.RUNTIME_EXECUTABLE | UseMode.BUILDTIME_DIRECT) & parent_mode:
            if dt.LINK & depflag:
                use_modes[child] |= UseMode.RUNTIME
            if dt.RUN & depflag:
                use_modes[child] |= UseMode.RUNTIME_EXECUTABLE

        # Propagate BUILDTIME through link deps.
        if UseMode.BUILDTIME & parent_mode:
            if dt.LINK & depflag:
                use_modes[child] |= UseMode.BUILDTIME

        # Finalize the spec; the invariant is that all in-edges are processed
        # before out-edges, meaning that parent is done.
        if not (UseMode.ADDED & parent_mode):
            use_modes[parent] |= UseMode.ADDED
            nodes_with_type.append((parent, parent_mode))

    # Attach the leaf nodes, since we only added nodes with out-edges.
    for spec, parent_mode in use_modes.items():
        if parent_mode and not (UseMode.ADDED & parent_mode):
            nodes_with_type.append((spec, parent_mode))

    return nodes_with_type


class SetupContext:
    """This class encapsulates the logic to determine environment modifications, and is used as
    well to set globals in modules of package.py."""

    def __init__(self, *specs: spack.spec.Spec, context: Context) -> None:
        """Construct a ModificationsFromDag object.
        Args:
            specs: single root spec for build/test context, possibly more for run context
            context: build, run, or test"""
        if (context == Context.BUILD or context == Context.TEST) and not len(specs) == 1:
            raise ValueError("Cannot setup build environment for multiple specs")
        specs_with_type = effective_deptypes(*specs, context=context)

        self.specs = specs
        self.context = context
        self.external: List[Tuple[spack.spec.Spec, UseMode]]
        self.nonexternal: List[Tuple[spack.spec.Spec, UseMode]]
        # Reverse so we go from leaf to root
        self.nodes_in_subdag = set(id(s) for s, _ in specs_with_type)

        # Split into non-external and external, maintaining topo order per group.
        self.external, self.nonexternal = stable_partition(
            reversed(specs_with_type), lambda t: t[0].external
        )
        self.should_be_runnable = UseMode.BUILDTIME_DIRECT | UseMode.RUNTIME_EXECUTABLE
        self.should_setup_run_env = (
            UseMode.BUILDTIME_DIRECT | UseMode.RUNTIME | UseMode.RUNTIME_EXECUTABLE
        )
        self.should_setup_dependent_build_env = UseMode.BUILDTIME | UseMode.BUILDTIME_DIRECT
        self.should_setup_build_env = UseMode.ROOT if context == Context.BUILD else UseMode(0)

        if context == Context.RUN or context == Context.TEST:
            self.should_be_runnable |= UseMode.ROOT
            self.should_setup_run_env |= UseMode.ROOT

        # Everything that calls setup_run_environment and setup_dependent_* needs globals set.
        self.should_set_package_py_globals = (
            self.should_setup_dependent_build_env | self.should_setup_run_env | UseMode.ROOT
        )
        # In a build context, the root and direct build deps need build-specific globals set.
        self.needs_build_context = UseMode.ROOT | UseMode.BUILDTIME_DIRECT

    def set_all_package_py_globals(self):
        """Set the globals in modules of package.py files."""
        for dspec, flag in chain(self.external, self.nonexternal):
            pkg = dspec.package

            if self.should_set_package_py_globals & flag:
                if self.context == Context.BUILD and self.needs_build_context & flag:
                    set_package_py_globals(pkg, context=Context.BUILD)
                else:
                    # This includes runtime dependencies, also runtime deps of direct build deps.
                    set_package_py_globals(pkg, context=Context.RUN)

            for spec in dspec.dependents():
                # Note: some specs have dependents that are unreachable from the root, so avoid
                # setting globals for those.
                if id(spec) not in self.nodes_in_subdag:
                    continue
                dependent_module = ModuleChangePropagator(spec.package)
                pkg.setup_dependent_package(dependent_module, spec)
                dependent_module.propagate_changes_to_mro()

    def get_env_modifications(self) -> EnvironmentModifications:
        """Returns the environment variable modifications for the given input specs and context.
        Environment modifications include:
        - Updating PATH for packages that are required at runtime
        - Updating CMAKE_PREFIX_PATH and PKG_CONFIG_PATH so that their respective
        tools can find Spack-built dependencies (when context=build)
        - Running custom package environment modifications: setup_run_environment,
        setup_dependent_run_environment, setup_build_environment,
        setup_dependent_build_environment.

        The (partial) order imposed on the specs is externals first, then topological
        from leaf to root. That way externals cannot contribute search paths that would shadow
        Spack's prefixes, and dependents override variables set by dependencies."""
        env = EnvironmentModifications()
        for dspec, flag in chain(self.external, self.nonexternal):
            tty.debug(f"Adding env modifications for {dspec.name}")
            pkg = dspec.package

            if self.should_setup_dependent_build_env & flag:
                self._make_buildtime_detectable(dspec, env)

                for root in self.specs:  # there is only one root in build context
                    spack.builder.create(pkg).setup_dependent_build_environment(env, root)

            if self.should_setup_build_env & flag:
                spack.builder.create(pkg).setup_build_environment(env)

            if self.should_be_runnable & flag:
                self._make_runnable(dspec, env)

            if self.should_setup_run_env & flag:
                run_env_mods = EnvironmentModifications()
                for spec in dspec.dependents(deptype=dt.LINK | dt.RUN):
                    if id(spec) in self.nodes_in_subdag:
                        pkg.setup_dependent_run_environment(run_env_mods, spec)
                pkg.setup_run_environment(run_env_mods)

                external_env = (dspec.extra_attributes or {}).get("environment", {})
                if external_env:
                    run_env_mods.extend(spack.schema.environment.parse(external_env))

                if self.context == Context.BUILD:
                    # Don't let the runtime environment of comiler like dependencies leak into the
                    # build env
                    run_env_mods.drop("CC", "CXX", "F77", "FC")
                env.extend(run_env_mods)

        return env

    def _make_buildtime_detectable(self, dep: spack.spec.Spec, env: EnvironmentModifications):
        if is_system_path(dep.prefix):
            return

        env.prepend_path("CMAKE_PREFIX_PATH", dep.prefix)
        for d in ("lib", "lib64", "share"):
            pcdir = os.path.join(dep.prefix, d, "pkgconfig")
            if os.path.isdir(pcdir):
                env.prepend_path("PKG_CONFIG_PATH", pcdir)

    def _make_runnable(self, dep: spack.spec.Spec, env: EnvironmentModifications):
        if is_system_path(dep.prefix):
            return

        for d in ("bin", "bin64"):
            bin_dir = os.path.join(dep.prefix, d)
            if os.path.isdir(bin_dir):
                env.prepend_path("PATH", bin_dir)


def get_cmake_prefix_path(pkg):
    # Note that unlike modifications_from_dependencies, this does not include
    # any edits to CMAKE_PREFIX_PATH defined in custom
    # setup_dependent_build_environment implementations of dependency packages
    build_deps = set(pkg.spec.dependencies(deptype=("build", "test")))
    link_deps = set(pkg.spec.traverse(root=False, deptype=("link")))
    build_link_deps = build_deps | link_deps
    spack_built = []
    externals = []
    # modifications_from_dependencies updates CMAKE_PREFIX_PATH by first
    # prepending all externals and then all non-externals
    for dspec in pkg.spec.traverse(root=False, order="post"):
        if dspec in build_link_deps:
            if dspec.external:
                externals.insert(0, dspec)
            else:
                spack_built.insert(0, dspec)

    ordered_build_link_deps = spack_built + externals
    cmake_prefix_path_entries = []
    for spec in ordered_build_link_deps:
        cmake_prefix_path_entries.extend(spec.package.cmake_prefix_paths)

    return filter_system_paths(cmake_prefix_path_entries)


def _setup_pkg_and_run(
    serialized_pkg, function, kwargs, write_pipe, input_multiprocess_fd, jsfd1, jsfd2
):
    context: str = kwargs.get("context", "build")

    try:
        # We are in the child process. Python sets sys.stdin to
        # open(os.devnull) to prevent our process and its parent from
        # simultaneously reading from the original stdin. But, we assume
        # that the parent process is not going to read from it till we
        # are done with the child, so we undo Python's precaution.
        if input_multiprocess_fd is not None:
            sys.stdin = os.fdopen(input_multiprocess_fd.fd)

        pkg = serialized_pkg.restore()

        if not kwargs.get("fake", False):
            kwargs["unmodified_env"] = os.environ.copy()
            kwargs["env_modifications"] = setup_package(
                pkg, dirty=kwargs.get("dirty", False), context=Context.from_string(context)
            )
        return_value = function(pkg, kwargs)
        write_pipe.send(return_value)

    except StopPhase as e:
        # Do not create a full ChildError from this, it's not an error
        # it's a control statement.
        write_pipe.send(e)
    except BaseException:
        # catch ANYTHING that goes wrong in the child process
        exc_type, exc, tb = sys.exc_info()

        # Need to unwind the traceback in the child because traceback
        # objects can't be sent to the parent.
        tb_string = traceback.format_exc()

        # build up some context from the offending package so we can
        # show that, too.
        package_context = get_package_context(tb)

        logfile = None
        if context == "build":
            try:
                if hasattr(pkg, "log_path"):
                    logfile = pkg.log_path
            except NameError:
                # 'pkg' is not defined yet
                pass
        elif context == "test":
            logfile = os.path.join(pkg.test_suite.stage, pkg.test_suite.test_log_name(pkg.spec))

        error_msg = str(exc)
        if isinstance(exc, (spack.multimethod.NoSuchMethodError, AttributeError)):
            process = "test the installation" if context == "test" else "build from sources"
            error_msg = (
                "The '{}' package cannot find an attribute while trying to {}. "
                "This might be due to a change in Spack's package format "
                "to support multiple build-systems for a single package. You can fix this "
                "by updating the {} recipe, and you can also report the issue as a bug. "
                "More information at https://spack.readthedocs.io/en/latest/packaging_guide.html#installation-procedure"
            ).format(pkg.name, process, context)
            error_msg = colorize("@*R{{{}}}".format(error_msg))
            error_msg = "{}\n\n{}".format(str(exc), error_msg)

        # make a pickleable exception to send to parent.
        msg = "%s: %s" % (exc_type.__name__, error_msg)

        ce = ChildError(
            msg,
            exc_type.__module__,
            exc_type.__name__,
            tb_string,
            logfile,
            context,
            package_context,
        )
        write_pipe.send(ce)

    finally:
        write_pipe.close()
        if input_multiprocess_fd is not None:
            input_multiprocess_fd.close()


def start_build_process(pkg, function, kwargs):
    """Create a child process to do part of a spack build.

    Args:

        pkg (spack.package_base.PackageBase): package whose environment we should set up the
            child process for.
        function (typing.Callable): argless function to run in the child
            process.

    Usage::

        def child_fun():
            # do stuff
        build_env.start_build_process(pkg, child_fun)

    The child process is run with the build environment set up by
    spack.build_environment.  This allows package authors to have full
    control over the environment, etc. without affecting other builds
    that might be executed in the same spack call.

    If something goes wrong, the child process catches the error and
    passes it to the parent wrapped in a ChildError.  The parent is
    expected to handle (or re-raise) the ChildError.

    This uses `multiprocessing.Process` to create the child process. The
    mechanism used to create the process differs on different operating
    systems and for different versions of Python. In some cases "fork"
    is used (i.e. the "fork" system call) and some cases it starts an
    entirely new Python interpreter process (in the docs this is referred
    to as the "spawn" start method). Breaking it down by OS:

    - Linux always uses fork.
    - Mac OS uses fork before Python 3.8 and "spawn" for 3.8 and after.
    - Windows always uses the "spawn" start method.

    For more information on `multiprocessing` child process creation
    mechanisms, see https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
    """
    read_pipe, write_pipe = multiprocessing.Pipe(duplex=False)
    input_multiprocess_fd = None
    jobserver_fd1 = None
    jobserver_fd2 = None

    serialized_pkg = spack.subprocess_context.PackageInstallContext(pkg)

    try:
        # Forward sys.stdin when appropriate, to allow toggling verbosity
        if sys.platform != "win32" and sys.stdin.isatty() and hasattr(sys.stdin, "fileno"):
            input_fd = os.dup(sys.stdin.fileno())
            input_multiprocess_fd = MultiProcessFd(input_fd)
        mflags = os.environ.get("MAKEFLAGS", False)
        if mflags:
            m = re.search(r"--jobserver-[^=]*=(\d),(\d)", mflags)
            if m:
                jobserver_fd1 = MultiProcessFd(int(m.group(1)))
                jobserver_fd2 = MultiProcessFd(int(m.group(2)))

        p = multiprocessing.Process(
            target=_setup_pkg_and_run,
            args=(
                serialized_pkg,
                function,
                kwargs,
                write_pipe,
                input_multiprocess_fd,
                jobserver_fd1,
                jobserver_fd2,
            ),
        )

        p.start()

        # We close the writable end of the pipe now to be sure that p is the
        # only process which owns a handle for it. This ensures that when p
        # closes its handle for the writable end, read_pipe.recv() will
        # promptly report the readable end as being ready.
        write_pipe.close()

    except InstallError as e:
        e.pkg = pkg
        raise

    finally:
        # Close the input stream in the parent process
        if input_multiprocess_fd is not None:
            input_multiprocess_fd.close()

    def exitcode_msg(p):
        typ = "exit" if p.exitcode >= 0 else "signal"
        return f"{typ} {abs(p.exitcode)}"

    try:
        child_result = read_pipe.recv()
    except EOFError:
        p.join()
        raise InstallError(f"The process has stopped unexpectedly ({exitcode_msg(p)})")

    p.join()

    # If returns a StopPhase, raise it
    if isinstance(child_result, StopPhase):
        # do not print
        raise child_result

    # let the caller know which package went wrong.
    if isinstance(child_result, InstallError):
        child_result.pkg = pkg

    if isinstance(child_result, ChildError):
        # If the child process raised an error, print its output here rather
        # than waiting until the call to SpackError.die() in main(). This
        # allows exception handling output to be logged from within Spack.
        # see spack.main.SpackCommand.
        child_result.print_context()
        raise child_result

    # Fallback. Usually caught beforehand in EOFError above.
    if p.exitcode != 0:
        raise InstallError(f"The process failed unexpectedly ({exitcode_msg(p)})")

    return child_result


CONTEXT_BASES = (spack.package_base.PackageBase, spack.build_systems._checks.BaseBuilder)


def get_package_context(traceback, context=3):
    """Return some context for an error message when the build fails.

    Args:
        traceback: A traceback from some exception raised during
            install

        context (int): Lines of context to show before and after the line
            where the error happened

    This function inspects the stack to find where we failed in the
    package file, and it adds detailed context to the long_message
    from there.

    """

    def make_stack(tb, stack=None):
        """Tracebacks come out of the system in caller -> callee order.  Return
        an array in callee -> caller order so we can traverse it."""
        if stack is None:
            stack = []
        if tb is not None:
            make_stack(tb.tb_next, stack)
            stack.append(tb)
        return stack

    stack = make_stack(traceback)

    basenames = tuple(base.__name__ for base in CONTEXT_BASES)
    for tb in stack:
        frame = tb.tb_frame
        if "self" in frame.f_locals:
            # Find the first proper subclass of the PackageBase or BaseBuilder, but
            # don't provide context if the code is actually in the base classes.
            obj = frame.f_locals["self"]
            func = getattr(obj, tb.tb_frame.f_code.co_name, "")
            if func:
                typename, *_ = func.__qualname__.partition(".")
                if isinstance(obj, CONTEXT_BASES) and typename not in basenames:
                    break
    else:
        return None

    # We found obj, the Package implementation we care about.
    # Point out the location in the install method where we failed.
    filename = inspect.getfile(frame.f_code)
    lineno = frame.f_lineno
    if os.path.basename(filename) == "package.py":
        # subtract 1 because we inject a magic import at the top of package files.
        # TODO: get rid of the magic import.
        lineno -= 1

    lines = ["{0}:{1:d}, in {2}:".format(filename, lineno, frame.f_code.co_name)]

    # Build a message showing context in the install method.
    sourcelines, start = inspect.getsourcelines(frame)

    # Calculate lineno of the error relative to the start of the function.
    fun_lineno = lineno - start
    start_ctx = max(0, fun_lineno - context)
    sourcelines = sourcelines[start_ctx : fun_lineno + context + 1]

    for i, line in enumerate(sourcelines):
        is_error = start_ctx + i == fun_lineno
        mark = ">> " if is_error else "   "
        # Add start to get lineno relative to start of file, not function.
        marked = "  {0}{1:-6d}{2}".format(mark, start + start_ctx + i, line.rstrip())
        if is_error:
            marked = colorize("@R{%s}" % cescape(marked))
        lines.append(marked)

    return lines


class ChildError(InstallError):
    """Special exception class for wrapping exceptions from child processes
       in Spack's build environment.

    The main features of a ChildError are:

    1. They're serializable, so when a child build fails, we can send one
       of these to the parent and let the parent report what happened.

    2. They have a ``traceback`` field containing a traceback generated
       on the child immediately after failure.  Spack will print this on
       failure in lieu of trying to run sys.excepthook on the parent
       process, so users will see the correct stack trace from a child.

    3. They also contain context, which shows context in the Package
       implementation where the error happened.  This helps people debug
       Python code in their packages.  To get it, Spack searches the
       stack trace for the deepest frame where ``self`` is in scope and
       is an instance of PackageBase.  This will generally find a useful
       spot in the ``package.py`` file.

    The long_message of a ChildError displays one of two things:

      1. If the original error was a ProcessError, indicating a command
         died during the build, we'll show context from the build log.

      2. If the original error was any other type of error, we'll show
         context from the Python code.

    SpackError handles displaying the special traceback if we're in debug
    mode with spack -d.

    """

    # List of errors considered "build errors", for which we'll show log
    # context instead of Python context.
    build_errors = [("spack.util.executable", "ProcessError")]

    def __init__(self, msg, module, classname, traceback_string, log_name, log_type, context):
        super().__init__(msg)
        self.module = module
        self.name = classname
        self.traceback = traceback_string
        self.log_name = log_name
        self.log_type = log_type
        self.context = context

    @property
    def long_message(self):
        out = io.StringIO()
        out.write(self._long_message if self._long_message else "")

        have_log = self.log_name and os.path.exists(self.log_name)

        if (self.module, self.name) in ChildError.build_errors:
            # The error happened in some external executed process. Show
            # the log with errors or warnings highlighted.
            if have_log:
                write_log_summary(out, self.log_type, self.log_name)

        else:
            # The error happened in the Python code, so try to show
            # some context from the Package itself.
            if self.context:
                out.write("\n")
                out.write("\n".join(self.context))
                out.write("\n")

        if out.getvalue():
            out.write("\n")

        if have_log:
            out.write("See {0} log for details:\n".format(self.log_type))
            out.write("  {0}\n".format(self.log_name))

        # Also output the test log path IF it exists
        if self.context != "test":
            test_log = join_path(os.path.dirname(self.log_name), spack_install_test_log)
            if os.path.isfile(test_log):
                out.write("\nSee test log for details:\n")
                out.write("  {0}\n".format(test_log))

        return out.getvalue()

    def __str__(self):
        return self.message

    def __reduce__(self):
        """__reduce__ is used to serialize (pickle) ChildErrors.

        Return a function to reconstruct a ChildError, along with the
        salient properties we'll need.
        """
        return _make_child_error, (
            self.message,
            self.module,
            self.name,
            self.traceback,
            self.log_name,
            self.log_type,
            self.context,
        )


def _make_child_error(msg, module, name, traceback, log, log_type, context):
    """Used by __reduce__ in ChildError to reconstruct pickled errors."""
    return ChildError(msg, module, name, traceback, log, log_type, context)


class StopPhase(spack.error.SpackError):
    """Pickle-able exception to control stopped builds."""

    def __reduce__(self):
        return _make_stop_phase, (self.message, self.long_message)


def _make_stop_phase(msg, long_msg):
    return StopPhase(msg, long_msg)


def write_log_summary(out, log_type, log, last=None):
    errors, warnings = parse_log_events(log)
    nerr = len(errors)
    nwar = len(warnings)

    if nerr > 0:
        if last and nerr > last:
            errors = errors[-last:]
            nerr = last

        # If errors are found, only display errors
        out.write("\n%s found in %s log:\n" % (plural(nerr, "error"), log_type))
        out.write(make_log_context(errors))
    elif nwar > 0:
        if last and nwar > last:
            warnings = warnings[-last:]
            nwar = last

        # If no errors are found but warnings are, display warnings
        out.write("\n%s found in %s log:\n" % (plural(nwar, "warning"), log_type))
        out.write(make_log_context(warnings))


class ModuleChangePropagator:
    """Wrapper class to accept changes to a package.py Python module, and propagate them in the
    MRO of the package.

    It is mainly used as a substitute of the ``package.py`` module, when calling the
    "setup_dependent_package" function during build environment setup.
    """

    _PROTECTED_NAMES = ("package", "current_module", "modules_in_mro", "_set_attributes")

    def __init__(self, package):
        self._set_self_attributes("package", package)
        self._set_self_attributes("current_module", package.module)

        #: Modules for the classes in the MRO up to PackageBase
        modules_in_mro = []
        for cls in inspect.getmro(type(package)):
            module = cls.module

            if module == self.current_module:
                continue

            if module == spack.package_base:
                break

            modules_in_mro.append(module)
        self._set_self_attributes("modules_in_mro", modules_in_mro)
        self._set_self_attributes("_set_attributes", {})

    def _set_self_attributes(self, key, value):
        super().__setattr__(key, value)

    def __getattr__(self, item):
        return getattr(self.current_module, item)

    def __setattr__(self, key, value):
        if key in ModuleChangePropagator._PROTECTED_NAMES:
            msg = f'Cannot set attribute "{key}" in ModuleMonkeyPatcher'
            return AttributeError(msg)

        setattr(self.current_module, key, value)
        self._set_attributes[key] = value

    def propagate_changes_to_mro(self):
        for module_in_mro in self.modules_in_mro:
            module_in_mro.__dict__.update(self._set_attributes)