/
doebuild.py
3252 lines (2891 loc) · 111 KB
/
doebuild.py
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
# Copyright 2010-2023 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
__all__ = ["doebuild", "doebuild_environment", "spawn", "spawnebuild"]
import grp
import gzip
import errno
import fnmatch
from itertools import chain
import logging
import os as _os
import platform
import pwd
import re
import signal
import stat
import sys
import tempfile
from textwrap import wrap
import time
import warnings
import zlib
import portage
portage.proxy.lazyimport.lazyimport(
globals(),
"portage.package.ebuild.config:check_config_instance",
"portage.package.ebuild.digestcheck:digestcheck",
"portage.package.ebuild.digestgen:digestgen",
"portage.package.ebuild.fetch:_drop_privs_userfetch,_want_userfetch,fetch",
"portage.package.ebuild.prepare_build_dirs:_prepare_fake_distdir",
"portage.package.ebuild._ipc.QueryCommand:QueryCommand",
"portage.dep._slot_operator:evaluate_slot_operator_equal_deps",
"portage.package.ebuild._spawn_nofetch:spawn_nofetch",
"portage.util.elf.header:ELFHeader",
"portage.dep.soname.multilib_category:compute_multilib_category",
"portage.util._desktop_entry:validate_desktop_entry",
"portage.util._dyn_libs.NeededEntry:NeededEntry",
"portage.util._dyn_libs.soname_deps:SonameDepsProcessor",
"portage.util._async.SchedulerInterface:SchedulerInterface",
"portage.util._eventloop.global_event_loop:global_event_loop",
"portage.util.ExtractKernelVersion:ExtractKernelVersion",
)
from portage import (
bsd_chflags,
eapi_is_supported,
merge,
os,
selinux,
shutil,
unmerge,
_encodings,
_os_merge,
_shell_quote,
_unicode_decode,
_unicode_encode,
)
from portage.const import (
EBUILD_SH_ENV_FILE,
EBUILD_SH_ENV_DIR,
EBUILD_SH_BINARY,
INVALID_ENV_FILE,
MISC_SH_BINARY,
PORTAGE_PYM_PACKAGES,
SUPPORTED_GENTOO_BINPKG_FORMATS,
)
from portage.data import portage_gid, portage_uid, secpass, uid, userpriv_groups
from portage.dbapi.porttree import _parse_uri_map
from portage.dep import (
Atom,
check_required_use,
human_readable_required_use,
paren_enclose,
use_reduce,
)
from portage.dep.libc import find_libc_deps
from portage.eapi import (
eapi_exports_KV,
eapi_exports_merge_type,
eapi_exports_replace_vars,
eapi_has_required_use,
eapi_has_src_prepare_and_src_configure,
eapi_has_pkg_pretend,
_get_eapi_attrs,
)
from portage.elog import elog_process, _preload_elog_modules
from portage.elog.messages import eerror, eqawarn
from portage.exception import (
DigestException,
FileNotFound,
IncorrectParameter,
InvalidData,
InvalidDependString,
PermissionDenied,
UnsupportedAPIException,
)
from portage.localization import _
from portage.output import colormap
from portage.package.ebuild.prepare_build_dirs import prepare_build_dirs
from portage.process import find_binary
from portage.util import (
apply_recursive_permissions,
apply_secpass_permissions,
noiselimit,
shlex_split,
varexpand,
writemsg,
writemsg_stdout,
write_atomic,
)
from portage.util.cpuinfo import get_cpu_count, makeopts_to_job_count
from portage.util.lafilefixer import rewrite_lafile
from portage.util.compression_probe import _compressors
from portage.util.futures import asyncio
from portage.util.futures.executor.fork import ForkExecutor
from portage.util.path import first_existing
from portage.util.socks5 import get_socks5_proxy
from portage.util._dyn_libs.dyn_libs import check_dyn_libs_inconsistent
from portage.versions import _pkgsplit, pkgcmp
from _emerge.BinpkgEnvExtractor import BinpkgEnvExtractor
from _emerge.EbuildBuildDir import EbuildBuildDir
from _emerge.EbuildPhase import EbuildPhase
from _emerge.EbuildSpawnProcess import EbuildSpawnProcess
from _emerge.Package import Package
from _emerge.RootConfig import RootConfig
_unsandboxed_phases = frozenset(
[
"clean",
"cleanrm",
"config",
"help",
"info",
"postinst",
"preinst",
"pretend",
"postrm",
"prerm",
"setup",
]
)
# phases in which IPC with host is allowed
_ipc_phases = frozenset(
[
"setup",
"pretend",
"config",
"info",
"preinst",
"postinst",
"prerm",
"postrm",
]
)
# phases which execute in the global PID namespace
_global_pid_phases = frozenset(
["config", "depend", "preinst", "prerm", "postinst", "postrm"]
)
_phase_func_map = {
"config": "pkg_config",
"setup": "pkg_setup",
"nofetch": "pkg_nofetch",
"unpack": "src_unpack",
"prepare": "src_prepare",
"configure": "src_configure",
"compile": "src_compile",
"test": "src_test",
"install": "src_install",
"preinst": "pkg_preinst",
"postinst": "pkg_postinst",
"prerm": "pkg_prerm",
"postrm": "pkg_postrm",
"info": "pkg_info",
"pretend": "pkg_pretend",
}
_vdb_use_conditional_keys = Package._dep_keys + (
"LICENSE",
"PROPERTIES",
"RESTRICT",
)
def _doebuild_spawn(phase, settings, actionmap=None, **kwargs):
"""
All proper ebuild phases which execute ebuild.sh are spawned
via this function. No exceptions.
"""
if phase in _unsandboxed_phases:
kwargs["free"] = True
kwargs["ipc"] = "ipc-sandbox" not in settings.features or phase in _ipc_phases
kwargs["mountns"] = "mount-sandbox" in settings.features
kwargs["networked"] = (
"network-sandbox" not in settings.features
or (phase == "unpack" and "live" in settings["PORTAGE_PROPERTIES"].split())
or (
phase == "test" and "test_network" in settings["PORTAGE_PROPERTIES"].split()
)
or phase in _ipc_phases
or "network-sandbox" in settings["PORTAGE_RESTRICT"].split()
)
kwargs["pidns"] = (
"pid-sandbox" in settings.features and phase not in _global_pid_phases
)
kwargs["warn_on_large_env"] = "warn-on-large-env" in settings.features
if phase == "depend":
kwargs["droppriv"] = "userpriv" in settings.features
# It's not necessary to close_fds for this phase, since
# it should not spawn any daemons, and close_fds is
# best avoided since it can interact badly with some
# garbage collectors (see _setup_pipes docstring).
kwargs["close_fds"] = False
if actionmap is not None and phase in actionmap:
kwargs.update(actionmap[phase]["args"])
cmd = actionmap[phase]["cmd"] % phase
else:
if phase == "cleanrm":
ebuild_sh_arg = "clean"
else:
ebuild_sh_arg = phase
cmd = "{} {}".format(
_shell_quote(
os.path.join(
settings["PORTAGE_BIN_PATH"], os.path.basename(EBUILD_SH_BINARY)
)
),
ebuild_sh_arg,
)
settings["EBUILD_PHASE"] = phase
try:
return spawn(cmd, settings, **kwargs)
finally:
settings.pop("EBUILD_PHASE", None)
def _spawn_phase(
phase, settings, actionmap=None, returnpid=False, logfile=None, **kwargs
):
if returnpid:
return _doebuild_spawn(
phase,
settings,
actionmap=actionmap,
returnpid=returnpid,
logfile=logfile,
**kwargs,
)
# The logfile argument is unused here, since EbuildPhase uses
# the PORTAGE_LOG_FILE variable if set.
ebuild_phase = EbuildPhase(
actionmap=actionmap,
background=False,
phase=phase,
scheduler=SchedulerInterface(asyncio._safe_loop()),
settings=settings,
**kwargs,
)
ebuild_phase.start()
ebuild_phase.wait()
return ebuild_phase.returncode
def _doebuild_path(settings, eapi=None):
"""
Generate the PATH variable.
"""
# Note: PORTAGE_BIN_PATH may differ from the global constant
# when portage is reinstalling itself.
portage_bin_path = [settings["PORTAGE_BIN_PATH"]]
if portage_bin_path[0] != portage.const.PORTAGE_BIN_PATH:
# Add a fallback path for restarting failed builds (bug 547086)
portage_bin_path.append(portage.const.PORTAGE_BIN_PATH)
path = [x for x in settings.get("__PORTAGE_TEST_PATH_OVERRIDE", "").split(":") if x]
if "xattr" in settings.features:
for x in portage_bin_path:
path.append(os.path.join(x, "ebuild-helpers", "xattr"))
if (
uid != 0
and "unprivileged" in settings.features
and "fakeroot" not in settings.features
):
for x in portage_bin_path:
path.append(os.path.join(x, "ebuild-helpers", "unprivileged"))
if settings.get("USERLAND", "GNU") != "GNU":
for x in portage_bin_path:
path.append(os.path.join(x, "ebuild-helpers", "bsd"))
for x in portage_bin_path:
path.append(os.path.join(x, "ebuild-helpers"))
# If PATH is set in env.d, ignore PATH from the calling environment.
# This allows packages to update our PATH as they get installed.
if "PATH" in settings.configdict["env.d"]:
settings.configdict["env"].pop("PATH", None)
if "PATH" in settings:
pathset = set(path)
for p in settings["PATH"].split(":"):
# Avoid duplicate entries.
if p not in pathset:
path.append(p)
pathset.add(p)
settings["PATH"] = ":".join(path)
def doebuild_environment(
myebuild, mydo, myroot=None, settings=None, debug=False, use_cache=None, db=None
):
"""
Create and store environment variable in the config instance
that's passed in as the "settings" parameter. This will raise
UnsupportedAPIException if the given ebuild has an unsupported
EAPI. All EAPI dependent code comes last, so that essential
variables like PORTAGE_BUILDDIR are still initialized even in
cases when UnsupportedAPIException needs to be raised, which
can be useful when uninstalling a package that has corrupt
EAPI metadata.
The myroot and use_cache parameters are unused.
"""
if settings is None:
raise TypeError("settings argument is required")
if db is None:
raise TypeError("db argument is required")
mysettings = settings
mydbapi = db
ebuild_path = os.path.abspath(myebuild)
pkg_dir = os.path.dirname(ebuild_path)
mytree = os.path.dirname(os.path.dirname(pkg_dir))
mypv = os.path.basename(ebuild_path)[:-7]
mysplit = _pkgsplit(mypv, eapi=mysettings.configdict["pkg"].get("EAPI"))
if mysplit is None:
raise IncorrectParameter(_("Invalid ebuild path: '%s'") % myebuild)
if (
mysettings.mycpv is not None
and mysettings.configdict["pkg"].get("PF") == mypv
and "CATEGORY" in mysettings.configdict["pkg"]
):
# Assume that PF is enough to assume that we've got
# the correct CATEGORY, though this is not really
# a solid assumption since it's possible (though
# unlikely) that two packages in different
# categories have the same PF. Callers should call
# setcpv or create a clean clone of a locked config
# instance in order to ensure that this assumption
# does not fail like in bug #408817.
cat = mysettings.configdict["pkg"]["CATEGORY"]
mycpv = mysettings.mycpv
elif os.path.basename(pkg_dir) in (mysplit[0], mypv):
# portdbapi or vardbapi
cat = os.path.basename(os.path.dirname(pkg_dir))
mycpv = cat + "/" + mypv
else:
raise AssertionError("unable to determine CATEGORY")
# Make a backup of PORTAGE_TMPDIR prior to calling config.reset()
# so that the caller can override it.
tmpdir = mysettings["PORTAGE_TMPDIR"]
if mydo == "depend":
if mycpv != mysettings.mycpv:
# Don't pass in mydbapi here since the resulting aux_get
# call would lead to infinite 'depend' phase recursion.
mysettings.setcpv(mycpv)
else:
# If EAPI isn't in configdict["pkg"], it means that setcpv()
# hasn't been called with the mydb argument, so we have to
# call it here (portage code always calls setcpv properly,
# but api consumers might not).
if mycpv != mysettings.mycpv or "EAPI" not in mysettings.configdict["pkg"]:
# Reload env.d variables and reset any previous settings.
mysettings.reload()
mysettings.reset()
mysettings.setcpv(mycpv, mydb=mydbapi)
# config.reset() might have reverted a change made by the caller,
# so restore it to its original value. Sandbox needs canonical
# paths, so realpath it.
mysettings["PORTAGE_TMPDIR"] = os.path.realpath(tmpdir)
mysettings.pop("EBUILD_PHASE", None) # remove from backupenv
mysettings["EBUILD_PHASE"] = mydo
# Set requested Python interpreter for Portage helpers.
mysettings["PORTAGE_PYTHON"] = portage._python_interpreter
# This is used by assert_sigpipe_ok() that's used by the ebuild
# unpack() helper. SIGPIPE is typically 13, but its better not
# to assume that.
mysettings["PORTAGE_SIGPIPE_STATUS"] = str(128 + signal.SIGPIPE)
# We are disabling user-specific bashrc files.
mysettings["BASH_ENV"] = INVALID_ENV_FILE
if debug: # Otherwise it overrides emerge's settings.
# We have no other way to set debug... debug can't be passed in
# due to how it's coded... Don't overwrite this so we can use it.
mysettings["PORTAGE_DEBUG"] = "1"
mysettings["EBUILD"] = ebuild_path
mysettings["O"] = pkg_dir
mysettings.configdict["pkg"]["CATEGORY"] = cat
mysettings["PF"] = mypv
if hasattr(mydbapi, "repositories"):
repo = mydbapi.repositories.get_repo_for_location(mytree)
mysettings["PORTDIR"] = repo.eclass_db.porttrees[0]
mysettings["PORTAGE_ECLASS_LOCATIONS"] = repo.eclass_db.eclass_locations_string
mysettings.configdict["pkg"]["PORTAGE_REPO_NAME"] = repo.name
mysettings["PORTDIR"] = os.path.realpath(mysettings["PORTDIR"])
mysettings.pop("PORTDIR_OVERLAY", None)
mysettings["DISTDIR"] = os.path.realpath(mysettings["DISTDIR"])
mysettings["RPMDIR"] = os.path.realpath(mysettings["RPMDIR"])
mysettings["ECLASSDIR"] = mysettings["PORTDIR"] + "/eclass"
mysettings["PORTAGE_BASHRC_FILES"] = "\n".join(mysettings._pbashrc)
mysettings["P"] = mysplit[0] + "-" + mysplit[1]
mysettings["PN"] = mysplit[0]
mysettings["PV"] = mysplit[1]
mysettings["PR"] = mysplit[2]
mysettings["PVR"] = mypv[len(mysplit[0]) + 1 :]
if noiselimit < 0:
mysettings["PORTAGE_QUIET"] = "1"
# All temporary directories should be subdirectories of
# $PORTAGE_TMPDIR/portage, since it's common for /tmp and /var/tmp
# to be mounted with the "noexec" option (see bug #346899).
mysettings["BUILD_PREFIX"] = mysettings["PORTAGE_TMPDIR"] + "/portage"
mysettings["PKG_TMPDIR"] = mysettings["BUILD_PREFIX"] + "/._unmerge_"
# Package {pre,post}inst and {pre,post}rm may overlap, so they must have separate
# locations in order to prevent interference.
if mydo in ("unmerge", "prerm", "postrm", "cleanrm"):
mysettings["PORTAGE_BUILDDIR"] = os.path.join(
mysettings["PKG_TMPDIR"], mysettings["CATEGORY"], mysettings["PF"]
)
else:
mysettings["PORTAGE_BUILDDIR"] = os.path.join(
mysettings["BUILD_PREFIX"], mysettings["CATEGORY"], mysettings["PF"]
)
mysettings["HOME"] = os.path.join(mysettings["PORTAGE_BUILDDIR"], "homedir")
mysettings["WORKDIR"] = os.path.join(mysettings["PORTAGE_BUILDDIR"], "work")
mysettings["D"] = os.path.join(mysettings["PORTAGE_BUILDDIR"], "image") + os.sep
mysettings["T"] = os.path.join(mysettings["PORTAGE_BUILDDIR"], "temp")
mysettings["SANDBOX_LOG"] = os.path.join(mysettings["T"], "sandbox.log")
mysettings["FILESDIR"] = os.path.join(settings["PORTAGE_BUILDDIR"], "files")
# Prefix forward compatibility
eprefix_lstrip = mysettings["EPREFIX"].lstrip(os.sep)
mysettings["ED"] = (
os.path.join(mysettings["D"], eprefix_lstrip).rstrip(os.sep) + os.sep
)
mysettings["PORTAGE_BASHRC"] = os.path.join(
mysettings["PORTAGE_CONFIGROOT"], EBUILD_SH_ENV_FILE
)
mysettings["PM_EBUILD_HOOK_DIR"] = os.path.join(
mysettings["PORTAGE_CONFIGROOT"], EBUILD_SH_ENV_DIR
)
# Allow color.map to control colors associated with einfo, ewarn, etc...
mysettings["PORTAGE_COLORMAP"] = colormap()
if "COLUMNS" not in mysettings:
# Set COLUMNS, in order to prevent unnecessary stty calls
# inside the set_colors function of isolated-functions.sh.
# We cache the result in os.environ, in order to avoid
# multiple stty calls in cases when get_term_size() falls
# back to stty due to a missing or broken curses module.
columns = os.environ.get("COLUMNS")
if columns is None:
rows, columns = portage.output.get_term_size()
if columns < 1:
# Force a sane value for COLUMNS, so that tools
# like ls don't complain (see bug #394091).
columns = 80
columns = str(columns)
os.environ["COLUMNS"] = columns
mysettings["COLUMNS"] = columns
# EAPI is always known here, even for the "depend" phase, because
# EbuildMetadataPhase gets it from _parse_eapi_ebuild_head().
eapi = mysettings.configdict["pkg"]["EAPI"]
_doebuild_path(mysettings, eapi=eapi)
# All EAPI dependent code comes last, so that essential variables like
# PATH and PORTAGE_BUILDDIR are still initialized even in cases when
# UnsupportedAPIException needs to be raised, which can be useful
# when uninstalling a package that has corrupt EAPI metadata.
if not eapi_is_supported(eapi):
raise UnsupportedAPIException(mycpv, eapi)
if mydo != "depend":
if hasattr(mydbapi, "getFetchMap") and (
"A" not in mysettings.configdict["pkg"]
or "AA" not in mysettings.configdict["pkg"]
):
src_uri = mysettings.configdict["pkg"].get("SRC_URI")
if src_uri is None:
(src_uri,) = mydbapi.aux_get(
mysettings.mycpv, ["SRC_URI"], mytree=mytree
)
metadata = {
"EAPI": eapi,
"SRC_URI": src_uri,
}
use = frozenset(mysettings["PORTAGE_USE"].split())
try:
uri_map = _parse_uri_map(mysettings.mycpv, metadata, use=use)
except InvalidDependString:
mysettings.configdict["pkg"]["A"] = ""
else:
mysettings.configdict["pkg"]["A"] = " ".join(uri_map)
try:
uri_map = _parse_uri_map(mysettings.mycpv, metadata)
except InvalidDependString:
mysettings.configdict["pkg"]["AA"] = ""
else:
mysettings.configdict["pkg"]["AA"] = " ".join(uri_map)
ccache = "ccache" in mysettings.features
distcc = "distcc" in mysettings.features
icecream = "icecream" in mysettings.features
if ccache or distcc or icecream:
libdir = None
default_abi = mysettings.get("DEFAULT_ABI")
if default_abi:
libdir = mysettings.get("LIBDIR_" + default_abi)
if not libdir:
libdir = "lib"
# The installation locations use to vary between versions...
# Safer to look them up rather than assuming
possible_libexecdirs = (libdir, "lib", "libexec")
masquerades = []
if distcc:
masquerades.append(("distcc", "distcc"))
if icecream:
masquerades.append(("icecream", "icecc"))
if ccache:
masquerades.append(("ccache", "ccache"))
for feature, m in masquerades:
for l in possible_libexecdirs:
p = os.path.join(os.sep, eprefix_lstrip, "usr", l, m, "bin")
if os.path.isdir(p):
mysettings["PATH"] = p + ":" + mysettings["PATH"]
break
else:
writemsg(
(
"Warning: %s requested but no masquerade dir "
"can be found in /usr/lib*/%s/bin\n"
)
% (m, m)
)
mysettings.features.remove(feature)
if "MAKEOPTS" not in mysettings:
nproc = get_cpu_count()
if nproc:
mysettings["MAKEOPTS"] = "-j%d" % (nproc)
if "GNUMAKEFLAGS" not in mysettings and "MAKEFLAGS" not in mysettings:
mysettings["GNUMAKEFLAGS"] = (
f"--load-average {nproc} --output-sync=line"
)
if not eapi_exports_KV(eapi):
# Discard KV for EAPIs that don't support it. Cached KV is restored
# from the backupenv whenever config.reset() is called.
mysettings.pop("KV", None)
elif "KV" not in mysettings and mydo in (
"compile",
"config",
"configure",
"info",
"install",
"nofetch",
"postinst",
"postrm",
"preinst",
"prepare",
"prerm",
"setup",
"test",
"unpack",
):
mykv, err1 = ExtractKernelVersion(
os.path.join(mysettings["EROOT"], "usr/src/linux")
)
if mykv:
# Regular source tree
mysettings["KV"] = mykv
else:
mysettings["KV"] = ""
mysettings.backup_changes("KV")
binpkg_format = mysettings.get(
"BINPKG_FORMAT", SUPPORTED_GENTOO_BINPKG_FORMATS[0]
)
if binpkg_format not in portage.const.SUPPORTED_GENTOO_BINPKG_FORMATS:
writemsg(
"!!! BINPKG_FORMAT contains invalid or "
"unsupported format: %s" % binpkg_format,
noiselevel=-1,
)
binpkg_format = "xpak"
mysettings["BINPKG_FORMAT"] = binpkg_format
binpkg_compression = mysettings.get("BINPKG_COMPRESS", "bzip2")
try:
compression = _compressors[binpkg_compression]
except KeyError as e:
if binpkg_compression:
writemsg(
f"Warning: Invalid or unsupported compression method: {e.args[0]}\n"
)
else:
# Empty BINPKG_COMPRESS disables compression.
mysettings["PORTAGE_COMPRESSION_COMMAND"] = "cat"
else:
if (
settings.get(
f"BINPKG_COMPRESS_FLAGS_{binpkg_compression.upper()}", None
)
is not None
):
compression["compress"] = compression["compress"].replace(
"${BINPKG_COMPRESS_FLAGS}",
f"${{BINPKG_COMPRESS_FLAGS_{binpkg_compression.upper()}}}",
)
try:
compression_binary = compression["compress"].replace(
"{JOBS}",
str(makeopts_to_job_count(mysettings.get("MAKEOPTS", "1"))),
)
compression_binary = shlex_split(
varexpand(compression_binary, mydict=settings)
)[0]
except IndexError as e:
writemsg(
f"Warning: Invalid or unsupported compression method: {e.args[0]}\n"
)
else:
if find_binary(compression_binary) is None:
missing_package = compression["package"]
writemsg(
"Warning: File compression unsupported %s. Missing package: %s\n"
% (binpkg_compression, missing_package)
)
else:
compression_binary = compression["compress"].replace(
"{JOBS}",
str(makeopts_to_job_count(mysettings.get("MAKEOPTS", "1"))),
)
cmd = [
varexpand(x, mydict=settings)
for x in shlex_split(compression_binary)
]
# Filter empty elements
cmd = [x for x in cmd if x != ""]
mysettings["PORTAGE_COMPRESSION_COMMAND"] = " ".join(cmd)
_doebuild_manifest_cache = None
_doebuild_broken_ebuilds = set()
_doebuild_broken_manifests = set()
_doebuild_commands_without_builddir = (
"clean",
"cleanrm",
"depend",
"digest",
"fetch",
"fetchall",
"help",
"manifest",
)
def doebuild(
myebuild,
mydo,
_unused=DeprecationWarning,
settings=None,
debug=0,
listonly=0,
fetchonly=0,
cleanup=0,
use_cache=1,
fetchall=0,
tree=None,
mydbapi=None,
vartree=None,
prev_mtimes=None,
fd_pipes=None,
returnpid=False,
):
"""
Wrapper function that invokes specific ebuild phases through the spawning
of ebuild.sh
@param myebuild: name of the ebuild to invoke the phase on (CPV)
@type myebuild: String
@param mydo: Phase to run
@type mydo: String
@param _unused: Deprecated (use settings["ROOT"] instead)
@type _unused: String
@param settings: Portage Configuration
@type settings: instance of portage.config
@param debug: Turns on various debug information (eg, debug for spawn)
@type debug: Boolean
@param listonly: Used to wrap fetch(); passed such that fetch only lists files required.
@type listonly: Boolean
@param fetchonly: Used to wrap fetch(); passed such that files are only fetched (no other actions)
@type fetchonly: Boolean
@param cleanup: Passed to prepare_build_dirs (TODO: what does it do?)
@type cleanup: Boolean
@param use_cache: Enables the cache
@type use_cache: Boolean
@param fetchall: Used to wrap fetch(), fetches all URIs (even ones invalid due to USE conditionals)
@type fetchall: Boolean
@param tree: Which tree to use ('vartree','porttree','bintree', etc..), defaults to 'porttree'
@type tree: String
@param mydbapi: a dbapi instance to pass to various functions; this should be a portdbapi instance.
@type mydbapi: portdbapi instance
@param vartree: A instance of vartree; used for aux_get calls, defaults to db[myroot]['vartree']
@type vartree: vartree instance
@param prev_mtimes: A dict of { filename:mtime } keys used by merge() to do config_protection
@type prev_mtimes: dictionary
@param fd_pipes: A dict of mapping for pipes, { '0': stdin, '1': stdout }
for example.
@type fd_pipes: Dictionary
@param returnpid: Return a list of process IDs for a successful spawn, or
an integer value if spawn is unsuccessful. NOTE: This requires the
caller clean up all returned PIDs.
@type returnpid: Boolean
@rtype: Boolean
@return:
1. 0 for success
2. 1 for error
Most errors have an accompanying error message.
listonly and fetchonly are only really necessary for operations involving 'fetch'
prev_mtimes are only necessary for merge operations.
Other variables may not be strictly required, many have defaults that are set inside of doebuild.
"""
if settings is None:
raise TypeError("settings parameter is required")
mysettings = settings
myroot = settings["EROOT"]
if _unused is not DeprecationWarning:
warnings.warn(
"The third parameter of the "
"portage.doebuild() is deprecated. Instead "
"settings['EROOT'] is used.",
DeprecationWarning,
stacklevel=2,
)
if not tree:
writemsg("Warning: tree not specified to doebuild\n")
tree = "porttree"
# chunked out deps for each phase, so that ebuild binary can use it
# to collapse targets down.
actionmap_deps = {
"pretend": [],
"setup": ["pretend"],
"unpack": ["setup"],
"prepare": ["unpack"],
"configure": ["prepare"],
"compile": ["configure"],
"test": ["compile"],
"install": ["test"],
"instprep": ["install"],
"rpm": ["install"],
"package": ["install"],
"merge": ["install"],
}
if mydbapi is None:
mydbapi = portage.db[myroot][tree].dbapi
if vartree is None and mydo in ("merge", "qmerge", "unmerge"):
vartree = portage.db[myroot]["vartree"]
features = mysettings.features
clean_phases = ("clean", "cleanrm")
validcommands = [
"help",
"clean",
"prerm",
"postrm",
"cleanrm",
"preinst",
"postinst",
"config",
"info",
"setup",
"depend",
"pretend",
"fetch",
"fetchall",
"digest",
"unpack",
"prepare",
"configure",
"compile",
"test",
"install",
"instprep",
"rpm",
"qmerge",
"merge",
"package",
"unmerge",
"manifest",
"nofetch",
]
if mydo not in validcommands:
validcommands.sort()
writemsg(
f"!!! doebuild: '{mydo}' is not one of the following valid commands:",
noiselevel=-1,
)
for vcount in range(len(validcommands)):
if vcount % 6 == 0:
writemsg("\n!!! ", noiselevel=-1)
writemsg(validcommands[vcount].ljust(11), noiselevel=-1)
writemsg("\n", noiselevel=-1)
return 1
if returnpid and mydo != "depend":
# This case is not supported, since it bypasses the EbuildPhase class
# which implements important functionality (including post phase hooks
# and IPC for things like best/has_version and die).
warnings.warn(
"portage.doebuild() called "
"with returnpid parameter enabled. This usage will "
"not be supported in the future.",
DeprecationWarning,
stacklevel=2,
)
if mydo == "fetchall":
fetchall = 1
mydo = "fetch"
if mydo not in clean_phases and not os.path.exists(myebuild):
writemsg(f"!!! doebuild: {myebuild} not found for {mydo}\n", noiselevel=-1)
return 1
global _doebuild_manifest_cache
pkgdir = os.path.dirname(myebuild)
manifest_path = os.path.join(pkgdir, "Manifest")
if tree == "porttree":
repo_config = mysettings.repositories.get_repo_for_location(
os.path.dirname(os.path.dirname(pkgdir))
)
else:
repo_config = None
mf = None
if (
"strict" in features
and "digest" not in features
and tree == "porttree"
and not repo_config.thin_manifest
and mydo not in ("digest", "manifest", "help")
and not portage._doebuild_manifest_exempt_depend
and not (
repo_config.allow_missing_manifest and not os.path.exists(manifest_path)
)
):
# Always verify the ebuild checksums before executing it.
global _doebuild_broken_ebuilds
if myebuild in _doebuild_broken_ebuilds:
return 1
# Avoid checking the same Manifest several times in a row during a
# regen with an empty cache.
if (
_doebuild_manifest_cache is None
or _doebuild_manifest_cache.getFullname() != manifest_path
):
_doebuild_manifest_cache = None
if not os.path.exists(manifest_path):
out = portage.output.EOutput()
out.eerror(_("Manifest not found for '%s'") % (myebuild,))
_doebuild_broken_ebuilds.add(myebuild)
return 1
mf = repo_config.load_manifest(pkgdir, mysettings["DISTDIR"])
else:
mf = _doebuild_manifest_cache
try:
mf.checkFileHashes("EBUILD", os.path.basename(myebuild))
except KeyError:
if not (
mf.allow_missing
and os.path.basename(myebuild) not in mf.fhashdict["EBUILD"]
):
out = portage.output.EOutput()
out.eerror(_("Missing digest for '%s'") % (myebuild,))
_doebuild_broken_ebuilds.add(myebuild)
return 1
except FileNotFound:
out = portage.output.EOutput()
out.eerror(
_("A file listed in the Manifest " "could not be found: '%s'")
% (myebuild,)
)
_doebuild_broken_ebuilds.add(myebuild)
return 1
except DigestException as e:
out = portage.output.EOutput()
out.eerror(_("Digest verification failed:"))
out.eerror(f"{e.value[0]}")
out.eerror(_("Reason: %s") % e.value[1])
out.eerror(_("Got: %s") % e.value[2])
out.eerror(_("Expected: %s") % e.value[3])
_doebuild_broken_ebuilds.add(myebuild)
return 1
if mf.getFullname() in _doebuild_broken_manifests:
return 1
if mf is not _doebuild_manifest_cache and not mf.allow_missing:
# Make sure that all of the ebuilds are
# actually listed in the Manifest.
for f in os.listdir(pkgdir):
pf = None
if f[-7:] == ".ebuild":
pf = f[:-7]
if pf is not None and not mf.hasFile("EBUILD", f):
f = os.path.join(pkgdir, f)
if f not in _doebuild_broken_ebuilds:
out = portage.output.EOutput()
out.eerror(
_("A file is not listed in the " "Manifest: '%s'") % (f,)
)
_doebuild_broken_manifests.add(manifest_path)
return 1
# We cache it only after all above checks succeed.
_doebuild_manifest_cache = mf
logfile = None
builddir_lock = None
tmpdir = None
tmpdir_orig = None
try:
if mydo in ("digest", "manifest", "help"):
# Temporarily exempt the depend phase from manifest checks, in case
# aux_get calls trigger cache generation.
portage._doebuild_manifest_exempt_depend += 1
# If we don't need much space and we don't need a constant location,
# we can temporarily override PORTAGE_TMPDIR with a random temp dir
# so that there's no need for locking and it can be used even if the