-
Notifications
You must be signed in to change notification settings - Fork 427
/
post.py
1813 lines (1665 loc) · 66.2 KB
/
post.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 (C) 2014 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import json
import locale
import os
import re
import shutil
import stat
import sys
from collections import OrderedDict, defaultdict
from copy import copy
from fnmatch import filter as fnmatch_filter
from fnmatch import fnmatch
from fnmatch import translate as fnmatch_translate
from functools import partial
from os.path import (
basename,
dirname,
exists,
isabs,
isdir,
isfile,
islink,
join,
normpath,
realpath,
relpath,
sep,
splitext,
)
from pathlib import Path
from subprocess import CalledProcessError, call, check_output
from typing import TYPE_CHECKING
from conda.core.prefix_data import PrefixData
from conda.gateways.disk.create import TemporaryDirectory
from conda.gateways.disk.link import lchmod
from conda.gateways.disk.read import compute_sum
from conda.misc import walk_prefix
from conda.models.records import PrefixRecord
from . import utils
from .exceptions import OverDependingError, OverLinkingError, RunPathError
from .inspect_pkg import which_package
from .os_utils import external, macho
from .os_utils.liefldd import (
get_exports_memoized,
get_linkages_memoized,
get_rpaths_raw,
get_runpaths_raw,
have_lief,
set_rpath,
)
from .os_utils.pyldd import (
DLLfile,
EXEfile,
codefile_class,
elffile,
machofile,
)
from .utils import on_mac, on_win, prefix_files
if TYPE_CHECKING:
from typing import Literal
from .metadata import MetaData
filetypes_for_platform = {
"win": (DLLfile, EXEfile),
"osx": (machofile,),
"linux": (elffile,),
}
def fix_shebang(f, prefix, build_python, osx_is_app=False):
path = join(prefix, f)
if codefile_class(path, skip_symlinks=True):
return
elif islink(path):
return
elif not isfile(path):
return
if os.stat(path).st_size == 0:
return
bytes_ = False
os.chmod(path, 0o775)
with open(path, mode="r+", encoding=locale.getpreferredencoding()) as fi:
try:
data = fi.read(100)
fi.seek(0)
except UnicodeDecodeError: # file is binary
return
SHEBANG_PAT = re.compile(r"^#!.+$", re.M)
# regexp on the memory mapped file so we only read it into
# memory if the regexp matches.
try:
mm = utils.mmap_mmap(
fi.fileno(), 0, tagname=None, flags=utils.mmap_MAP_PRIVATE
)
except OSError:
mm = fi.read()
try:
m = SHEBANG_PAT.match(mm)
except TypeError:
SHEBANG_PAT = re.compile(rb"^#!.+$", re.M)
bytes_ = True
m = SHEBANG_PAT.match(mm)
if m:
python_pattern = (
re.compile(rb"\/python[w]?(?:$|\s|\Z)", re.M)
if bytes_
else re.compile(r"\/python[w]?(:$|\s|\Z)", re.M)
)
if not re.search(python_pattern, m.group()):
return
else:
return
data = mm[:]
py_exec = "#!" + (
"/bin/bash " + prefix + "/bin/pythonw"
if on_mac and osx_is_app
else prefix + "/bin/" + basename(build_python)
)
if bytes_ and hasattr(py_exec, "encode"):
py_exec = py_exec.encode()
new_data = SHEBANG_PAT.sub(py_exec, data, count=1)
if new_data == data:
return
print("updating shebang:", f)
with open(path, "w", encoding=locale.getpreferredencoding()) as fo:
try:
fo.write(new_data)
except TypeError:
fo.write(new_data.decode())
def write_pth(egg_path, config):
fn = basename(egg_path)
py_ver = ".".join(config.variant["python"].split(".")[:2])
with open(
join(
utils.get_site_packages(config.host_prefix, py_ver),
"{}.pth".format(fn.split("-")[0]),
),
"w",
) as fo:
fo.write(f"./{fn}\n")
def remove_easy_install_pth(files, prefix, config, preserve_egg_dir=False):
"""
remove the need for easy-install.pth and finally remove easy-install.pth
itself
"""
absfiles = [join(prefix, f) for f in files]
py_ver = ".".join(config.variant["python"].split(".")[:2])
sp_dir = utils.get_site_packages(prefix, py_ver)
for egg_path in utils.glob(join(sp_dir, "*-py*.egg")):
if isdir(egg_path):
if preserve_egg_dir or not any(
join(egg_path, i) in absfiles
for i in walk_prefix(egg_path, False, windows_forward_slashes=False)
):
write_pth(egg_path, config=config)
continue
print("found egg dir:", egg_path)
try:
shutil.move(join(egg_path, "EGG-INFO"), egg_path + "-info")
except OSError:
pass
utils.rm_rf(join(egg_path, "EGG-INFO"))
for fn in os.listdir(egg_path):
if fn == "__pycache__":
utils.rm_rf(join(egg_path, fn))
else:
# this might be a name-space package
# so the package directory already exists
# from another installed dependency
if exists(join(sp_dir, fn)):
try:
utils.copy_into(
join(egg_path, fn),
join(sp_dir, fn),
config.timeout,
locking=config.locking,
)
utils.rm_rf(join(egg_path, fn))
except OSError as e:
fn = basename(str(e).split()[-1])
raise OSError(
f"Tried to merge folder {egg_path} into {sp_dir}, but {fn}"
" exists in both locations. Please either add "
"build/preserve_egg_dir: True to meta.yaml, or manually "
"remove the file during your install process to avoid "
"this conflict."
)
else:
shutil.move(join(egg_path, fn), join(sp_dir, fn))
elif isfile(egg_path):
if egg_path not in absfiles:
continue
print("found egg:", egg_path)
write_pth(egg_path, config=config)
installer_files = [f for f in absfiles if f.endswith(f".dist-info{sep}INSTALLER")]
for file in installer_files:
with open(file, "w") as f:
f.write("conda")
utils.rm_rf(join(sp_dir, "easy-install.pth"))
def rm_py_along_so(prefix):
"""remove .py (.pyc) files alongside .so or .pyd files"""
files = list(os.scandir(prefix))
for fn in files:
if fn.is_file() and fn.name.endswith((".so", ".pyd")):
for ext in ".py", ".pyc", ".pyo":
name, _ = splitext(fn.path)
name = normpath(name + ext)
if any(name == normpath(f) for f in files):
os.unlink(name + ext)
def rm_pyo(files, prefix):
"""pyo considered harmful: https://www.python.org/dev/peps/pep-0488/
The build may have proceeded with:
[install]
optimize = 1
.. in setup.cfg in which case we can end up with some stdlib __pycache__
files ending in .opt-N.pyc on Python 3, as well as .pyo files for the
package's own python."""
re_pyo = re.compile(r".*(?:\.pyo$|\.opt-[0-9]\.pyc)")
for fn in files:
if re_pyo.match(fn):
os.unlink(join(prefix, fn))
def rm_pyc(files, prefix):
re_pyc = re.compile(r".*(?:\.pyc$)")
for fn in files:
if re_pyc.match(fn):
os.unlink(join(prefix, fn))
def rm_share_info_dir(files, prefix):
if "share/info/dir" in files:
fn = join(prefix, "share", "info", "dir")
if isfile(fn):
os.unlink(fn)
def compile_missing_pyc(files, cwd, python_exe, skip_compile_pyc=()):
if not isfile(python_exe):
return
compile_files = []
skip_compile_pyc_n = [normpath(skip) for skip in skip_compile_pyc]
skipped_files = set()
for skip in skip_compile_pyc_n:
skipped_files.update(set(fnmatch_filter(files, skip)))
unskipped_files = set(files) - skipped_files
for fn in unskipped_files:
# omit files in Library/bin, Scripts, and the root prefix - they are not generally imported
if on_win:
if any(
[
fn.lower().startswith(start)
for start in ["library/bin", "library\\bin", "scripts"]
]
):
continue
else:
if fn.startswith("bin"):
continue
cache_prefix = "__pycache__" + os.sep
if (
fn.endswith(".py")
and dirname(fn) + cache_prefix + basename(fn) + "c" not in files
):
compile_files.append(fn)
if compile_files:
if not isfile(python_exe):
print("compiling .pyc files... failed as no python interpreter was found")
else:
print("compiling .pyc files...")
# We avoid command lines longer than 8190
if on_win:
limit = 8190
else:
limit = 32760
limit -= len(compile_files) * 2
lower_limit = len(max(compile_files, key=len)) + 1
if limit < lower_limit:
limit = lower_limit
groups = [[]]
args = [python_exe, "-Wi", "-m", "py_compile"]
args_len = length = len(" ".join(args)) + 1
for f in compile_files:
length_this = len(f) + 1
if length_this + length > limit:
groups.append([])
length = args_len
else:
length += length_this
groups[len(groups) - 1].append(f)
for group in groups:
call(args + group, cwd=cwd)
def check_dist_info_version(name, version, files):
for f in files:
if f.endswith(".dist-info" + os.sep + "METADATA"):
f_lower = basename(dirname(f).lower())
if f_lower.startswith(name + "-"):
f_lower, _, _ = f_lower.rpartition(".dist-info")
_, distname, f_lower = f_lower.rpartition(name + "-")
if distname == name and version != f_lower:
print(
f"ERROR: Top level dist-info version incorrect (is {f_lower}, should be {version})"
)
sys.exit(1)
else:
return
def post_process(
name,
version,
files,
prefix,
config,
preserve_egg_dir=False,
noarch=False,
skip_compile_pyc=(),
):
rm_pyo(files, prefix)
if noarch:
rm_pyc(files, prefix)
else:
python_exe = (
config.build_python if isfile(config.build_python) else config.host_python
)
compile_missing_pyc(
files, cwd=prefix, python_exe=python_exe, skip_compile_pyc=skip_compile_pyc
)
remove_easy_install_pth(files, prefix, config, preserve_egg_dir=preserve_egg_dir)
rm_py_along_so(prefix)
rm_share_info_dir(files, prefix)
check_dist_info_version(name, version, files)
def find_lib(link, prefix, files, path=None):
if link.startswith(prefix):
link = normpath(link[len(prefix) + 1 :])
if not any(link == normpath(w) for w in files):
sys.exit(f"Error: Could not find {link}")
return link
if link.startswith("/"): # but doesn't start with the build prefix
return
if link.startswith("@rpath/"):
# Assume the rpath already points to lib, so there is no need to
# change it.
return
if "/" not in link or link.startswith("@executable_path/"):
link = basename(link)
file_names = defaultdict(list)
for f in files:
file_names[basename(f)].append(f)
if link not in file_names:
sys.exit(f"Error: Could not find {link}")
if len(file_names[link]) > 1:
if path and basename(path) == link:
# The link is for the file itself, just use it
return path
# Allow for the possibility of the same library appearing in
# multiple places.
md5s = set()
for f in file_names[link]:
md5s.add(compute_sum(join(prefix, f), "md5"))
if len(md5s) > 1:
sys.exit(
f"Error: Found multiple instances of {link}: {file_names[link]}"
)
else:
file_names[link].sort()
print(
f"Found multiple instances of {link} ({file_names[link]}). "
"Choosing the first one."
)
return file_names[link][0]
print(f"Don't know how to find {link}, skipping")
def osx_ch_link(path, link_dict, host_prefix, build_prefix, files):
link = link_dict["name"]
if build_prefix != host_prefix and link.startswith(build_prefix):
link = link.replace(build_prefix, host_prefix)
print(f"Fixing linking of {link} in {path}")
print(
".. seems to be linking to a compiler runtime, replacing build prefix with "
"host prefix and"
)
if not codefile_class(link, skip_symlinks=True):
sys.exit(
f"Error: Compiler runtime library in build prefix not found in host prefix {link}"
)
else:
print(f".. fixing linking of {link} in {path} instead")
link_loc = find_lib(link, host_prefix, files, path)
if not link_loc:
return
print(f"Fixing linking of {link} in {path}")
print(f"New link location is {link_loc}")
lib_to_link = relpath(dirname(link_loc), "lib")
# path_to_lib = utils.relative(path[len(prefix) + 1:])
# e.g., if
# path = '/build_prefix/lib/some/stuff/libstuff.dylib'
# link_loc = 'lib/things/libthings.dylib'
# then
# lib_to_link = 'things'
# path_to_lib = '../..'
# @rpath always means 'lib', link will be at
# @rpath/lib_to_link/basename(link), like @rpath/things/libthings.dylib.
# For when we can't use @rpath, @loader_path means the path to the library
# ('path'), so from path to link is
# @loader_path/path_to_lib/lib_to_link/basename(link), like
# @loader_path/../../things/libthings.dylib.
ret = f"@rpath/{lib_to_link}/{basename(link)}"
# XXX: IF the above fails for whatever reason, the below can be used
# TODO: This might contain redundant ..'s if link and path are both in
# some subdirectory of lib.
# ret = '@loader_path/%s/%s/%s' % (path_to_lib, lib_to_link, basename(link))
ret = ret.replace("/./", "/")
return ret
def mk_relative_osx(path, host_prefix, m, files, rpaths=("lib",)):
base_prefix = m.config.build_folder
assert base_prefix == dirname(host_prefix)
build_prefix = m.config.build_prefix
prefix = build_prefix if exists(build_prefix) else host_prefix
names = macho.otool(path, prefix)
s = macho.install_name_change(
path,
prefix,
partial(
osx_ch_link, host_prefix=host_prefix, build_prefix=build_prefix, files=files
),
dylibs=names,
)
if names:
existing_rpaths = macho.get_rpaths(path, build_prefix=prefix)
# Add an rpath to every executable to increase the chances of it
# being found.
for rpath in rpaths:
# Escape hatch for when you really don't want any rpaths added.
if rpath == "":
continue
rpath_new = join(
"@loader_path", relpath(join(host_prefix, rpath), dirname(path)), ""
).replace("/./", "/")
macho.add_rpath(path, rpath_new, build_prefix=prefix, verbose=True)
full_rpath = join(host_prefix, rpath)
for existing_rpath in existing_rpaths:
if normpath(existing_rpath) == normpath(full_rpath):
macho.delete_rpath(
path, existing_rpath, build_prefix=prefix, verbose=True
)
for rpath in existing_rpaths:
if rpath.startswith(base_prefix) and not rpath.startswith(host_prefix):
macho.delete_rpath(path, rpath, build_prefix=prefix, verbose=True)
if s:
# Skip for stub files, which have to use binary_has_prefix_files to be
# made relocatable.
assert_relative_osx(path, host_prefix, build_prefix)
"""
# Both patchelf and LIEF have bugs in them. Neither can be used on all binaries we have seen.
# This code tries each and tries to keep count of which worked between the original binary and
# patchelf-patched, LIEF-patched versions.
#
# Please do not delete it until you are sure the bugs in both projects have been fixed.
#
from subprocess import STDOUT
def check_binary(binary, expected=None):
from ctypes import cdll
print("trying {}".format(binary))
# import pdb; pdb.set_trace()
try:
txt = check_output(
[
sys.executable,
'-c',
'from ctypes import cdll; cdll.LoadLibrary("' + binary + '")'
],
timeout=2,
)
# mydll = cdll.LoadLibrary(binary)
except Exception as e:
print(e)
return None, None
try:
txt = check_output(binary, stderr=STDOUT, timeout=0.1)
except Exception as e:
print(e)
txt = e.output
if expected is not None:
return txt == expected, txt
return True, txt
worksd = {'original': 0,
'LIEF': 0,
'patchelf': 0}
def check_binary_patchers(elf, prefix, rpath):
patchelf = external.find_executable('patchelf', prefix)
tmpname_pe = elf+'.patchelf'
tmpname_le = elf+'.lief'
shutil.copy(elf, tmpname_pe)
shutil.copy(elf, tmpname_le)
import pdb; pdb.set_trace()
works, original = check_binary(elf)
if works:
worksd['original'] += 1
set_rpath(old_matching='*', new_rpath=rpath, file=tmpname_le)
works, LIEF = check_binary(tmpname_le, original)
call([patchelf, '--force-rpath', '--set-rpath', rpath, tmpname_pe])
works, pelf = check_binary(tmpname_pe, original)
if original == LIEF and works:
worksd['LIEF'] += 1
if original == pelf and works:
worksd['patchelf'] += 1
print('\n' + str(worksd) + '\n')
"""
def mk_relative_linux(f, prefix, rpaths=("lib",), method=None):
"Respects the original values and converts abs to $ORIGIN-relative"
elf = join(prefix, f)
origin = dirname(elf)
existing_pe = None
patchelf = external.find_executable("patchelf", prefix)
if not patchelf:
print(
f"ERROR :: You should install patchelf, will proceed with LIEF for {elf} (was {method})"
)
method = "LIEF"
else:
try:
existing_pe = (
check_output([patchelf, "--print-rpath", elf])
.decode("utf-8")
.splitlines()[0]
)
except CalledProcessError:
if method == "patchelf":
print(
f"ERROR :: `patchelf --print-rpath` failed for {elf}, but patchelf was specified"
)
elif method != "LIEF":
print(
f"WARNING :: `patchelf --print-rpath` failed for {elf}, will proceed with LIEF (was {method})"
)
method = "LIEF"
else:
existing_pe = existing_pe.split(os.pathsep)
existing = existing_pe
if have_lief:
existing2, _, _ = get_rpaths_raw(elf)
if existing_pe and existing_pe != existing2:
print(
f"WARNING :: get_rpaths_raw()={existing2} and patchelf={existing_pe} disagree for {elf} :: "
)
# Use LIEF if method is LIEF to get the initial value?
if method == "LIEF":
existing = existing2
new = []
for old in existing:
if old.startswith("$ORIGIN"):
new.append(old)
elif old.startswith("/"):
# Test if this absolute path is outside of prefix. That is fatal.
rp = relpath(old, prefix)
if rp.startswith(".." + os.sep):
print(f"Warning: rpath {old} is outside prefix {prefix} (removing it)")
else:
rp = "$ORIGIN/" + relpath(old, origin)
if rp not in new:
new.append(rp)
# Ensure that the asked-for paths are also in new.
for rpath in rpaths:
if rpath != "":
if not rpath.startswith("/"):
rpath = "$ORIGIN/" + normpath(relpath(rpath, dirname(f)))
if rpath not in new:
new.append(rpath)
rpath = ":".join(new)
# check_binary_patchers(elf, prefix, rpath)
if not patchelf or (method and method.upper() == "LIEF"):
set_rpath(old_matching="*", new_rpath=rpath, file=elf)
else:
call([patchelf, "--force-rpath", "--set-rpath", rpath, elf])
def assert_relative_osx(path, host_prefix, build_prefix):
tools_prefix = build_prefix if exists(build_prefix) else host_prefix
for name in macho.get_dylibs(path, tools_prefix):
for prefix in (host_prefix, build_prefix):
if prefix and name.startswith(prefix):
raise RuntimeError(
f"library at {path} appears to have an absolute path embedded"
)
def get_dsos(prec: PrefixRecord, prefix: str | os.PathLike | Path) -> set[str]:
return {
file
for file in prec["files"]
if codefile_class(Path(prefix, file), skip_symlinks=True)
# codefile_class already filters by extension/binary type, do we need this second filter?
for ext in (".dylib", ".so", ".dll", ".pyd")
if ext in file
}
def get_run_exports(
prec: PrefixRecord,
prefix: str | os.PathLike | Path,
) -> tuple[str, ...]:
json_file = Path(
prefix,
"conda-meta",
f"{prec.name}-{prec.version}-{prec.build}.json",
)
try:
json_info = json.loads(json_file.read_text())
except (FileNotFoundError, IsADirectoryError):
# FileNotFoundError: path doesn't exist
# IsADirectoryError: path is a directory
# raise CondaBuildException(f"Not a file: {json_file}")
# is this a "fake" PrefixRecord?
# i.e. this is the package being built and hasn't been "installed" to disk?
return ()
run_exports_json = Path(
json_info["extracted_package_dir"],
"info",
"run_exports.json",
)
try:
return tuple(json.loads(run_exports_json.read_text()))
except (FileNotFoundError, IsADirectoryError):
# FileNotFoundError: path doesn't exist
# IsADirectoryError: path is a directory
return ()
def library_nature(
prec: PrefixRecord, prefix: str | os.PathLike | Path
) -> Literal[
"interpreter (Python)"
| "interpreter (R)"
| "run-exports library"
| "dso library"
| "plugin library (Python,R)"
| "plugin library (Python)"
| "plugin library (R)"
| "interpreted library (Python,R)"
| "interpreted library (Python)"
| "interpreted library (R)"
| "non-library"
]:
"""
Result :: "non-library",
"interpreted library (Python|R|Python,R)",
"plugin library (Python|R|Python,R)",
"dso library",
"run-exports library",
"interpreter (R)"
"interpreter (Python)"
.. in that order, i.e. if have both dsos and run_exports, it's a run_exports_library.
"""
if prec.name == "python":
return "interpreter (Python)"
elif prec.name == "r-base":
return "interpreter (R)"
elif get_run_exports(prec, prefix):
return "run-exports library"
elif dsos := get_dsos(prec, prefix):
# If all DSOs are under site-packages or R/lib/
python_dsos = {dso for dso in dsos if "site-packages" in dso}
r_dsos = {dso for dso in dsos if "lib/R/library" in dso}
if dsos - python_dsos - r_dsos:
return "dso library"
elif python_dsos and r_dsos:
return "plugin library (Python,R)"
elif python_dsos:
return "plugin library (Python)"
elif r_dsos:
return "plugin library (R)"
else:
python_files = {file for file in prec["files"] if "site-packages" in file}
r_files = {file for file in prec["files"] if "lib/R/library" in file}
if python_files and r_files:
return "interpreted library (Python,R)"
elif python_files:
return "interpreted library (Python)"
elif r_files:
return "interpreted library (R)"
return "non-library"
# This is really just a small, fixed sysroot and it is rooted at ''. `libcrypto.0.9.8.dylib` should not be in it IMHO.
DEFAULT_MAC_WHITELIST = [
"/opt/X11/",
"/usr/lib/libSystem.B.dylib",
"/usr/lib/libcrypto.0.9.8.dylib",
"/usr/lib/libobjc.A.dylib",
"""
'/System/Library/Frameworks/Accelerate.framework/*',
'/System/Library/Frameworks/AGL.framework/*',
'/System/Library/Frameworks/AppKit.framework/*',
'/System/Library/Frameworks/ApplicationServices.framework/*',
'/System/Library/Frameworks/AudioToolbox.framework/*',
'/System/Library/Frameworks/AudioUnit.framework/*',
'/System/Library/Frameworks/AVFoundation.framework/*',
'/System/Library/Frameworks/CFNetwork.framework/*',
'/System/Library/Frameworks/Carbon.framework/*',
'/System/Library/Frameworks/Cocoa.framework/*',
'/System/Library/Frameworks/CoreAudio.framework/*',
'/System/Library/Frameworks/CoreFoundation.framework/*',
'/System/Library/Frameworks/CoreGraphics.framework/*',
'/System/Library/Frameworks/CoreMedia.framework/*',
'/System/Library/Frameworks/CoreBluetooth.framework/*',
'/System/Library/Frameworks/CoreMIDI.framework/*',
'/System/Library/Frameworks/CoreMedia.framework/*',
'/System/Library/Frameworks/CoreServices.framework/*',
'/System/Library/Frameworks/CoreText.framework/*',
'/System/Library/Frameworks/CoreVideo.framework/*',
'/System/Library/Frameworks/CoreWLAN.framework/*',
'/System/Library/Frameworks/DiskArbitration.framework/*',
'/System/Library/Frameworks/Foundation.framework/*',
'/System/Library/Frameworks/GameController.framework/*',
'/System/Library/Frameworks/GLKit.framework/*',
'/System/Library/Frameworks/ImageIO.framework/*',
'/System/Library/Frameworks/IOBluetooth.framework/*',
'/System/Library/Frameworks/IOKit.framework/*',
'/System/Library/Frameworks/IOSurface.framework/*',
'/System/Library/Frameworks/OpenAL.framework/*',
'/System/Library/Frameworks/OpenGL.framework/*',
'/System/Library/Frameworks/Quartz.framework/*',
'/System/Library/Frameworks/QuartzCore.framework/*',
'/System/Library/Frameworks/Security.framework/*',
'/System/Library/Frameworks/StoreKit.framework/*',
'/System/Library/Frameworks/SystemConfiguration.framework/*',
'/System/Library/Frameworks/WebKit.framework/*'
""",
]
# Should contain the System32/SysWOW64 DLLs present on a clean installation of the
# oldest version of Windows that we support (or are currently) building packages for.
DEFAULT_WIN_WHITELIST = [
"**/ADVAPI32.dll",
"**/bcrypt.dll",
"**/COMCTL32.dll",
"**/COMDLG32.dll",
"**/CRYPT32.dll",
"**/dbghelp.dll",
"**/GDI32.dll",
"**/IMM32.dll",
"**/KERNEL32.dll",
"**/NETAPI32.dll",
"**/ole32.dll",
"**/OLEAUT32.dll",
"**/PSAPI.DLL",
"**/RPCRT4.dll",
"**/SHELL32.dll",
"**/USER32.dll",
"**/USERENV.dll",
"**/WINHTTP.dll",
"**/WS2_32.dll",
"**/ntdll.dll",
"**/msvcrt.dll",
]
def _collect_needed_dsos(
sysroots_files,
files,
run_prefix,
sysroot_substitution,
build_prefix,
build_prefix_substitution,
):
all_needed_dsos = set()
needed_dsos_for_file = dict()
sysroots = ""
if sysroots_files:
sysroots = list(sysroots_files.keys())[0]
for f in files:
path = join(run_prefix, f)
if not codefile_class(path, skip_symlinks=True):
continue
build_prefix = build_prefix.replace(os.sep, "/")
run_prefix = run_prefix.replace(os.sep, "/")
needed = get_linkages_memoized(
path,
resolve_filenames=True,
recurse=False,
sysroot=sysroots,
envroot=run_prefix,
)
for lib, res in needed.items():
resolved = res["resolved"].replace(os.sep, "/")
for sysroot, sysroot_files in sysroots_files.items():
if resolved.startswith(sysroot):
resolved = resolved.replace(sysroot, sysroot_substitution)
elif resolved[1:] in sysroot_files:
resolved = sysroot_substitution + resolved[1:]
# We do not want to do this substitution when merging build and host prefixes.
if build_prefix != run_prefix and resolved.startswith(build_prefix):
resolved = resolved.replace(build_prefix, build_prefix_substitution)
if resolved.startswith(run_prefix):
resolved = relpath(resolved, run_prefix).replace(os.sep, "/")
# If resolved still starts with '$RPATH' then that means we will either find it in
# the whitelist or it will present as an error later.
res["resolved"] = resolved
needed_dsos_for_file[f] = needed
all_needed_dsos = all_needed_dsos.union(
{info["resolved"] for f, info in needed.items()}
)
return all_needed_dsos, needed_dsos_for_file
def _map_file_to_package(
files,
run_prefix,
build_prefix,
all_needed_dsos,
pkg_vendored_dist,
ignore_list_syms,
sysroot_substitution,
enable_static,
):
# Form a mapping of file => package
prefix_owners = {}
contains_dsos = {}
contains_static_libs = {}
# Used for both dsos and static_libs
all_lib_exports = {}
all_needed_dsos_lower = [w.lower() for w in all_needed_dsos]
if all_needed_dsos:
for prefix in (run_prefix, build_prefix):
all_lib_exports[prefix] = {}
prefix_owners[prefix] = {}
for subdir2, _, filez in os.walk(prefix):
for file in filez:
fp = join(subdir2, file)
dynamic_lib = any(
fnmatch(fp, ext) for ext in ("*.so*", "*.dylib*", "*.dll")
) and codefile_class(fp, skip_symlinks=False)
static_lib = any(fnmatch(fp, ext) for ext in ("*.a", "*.lib"))
# Looking at all the files is very slow.
if not dynamic_lib and not static_lib:
continue
rp = normpath(relpath(fp, prefix)).replace("\\", "/")
if dynamic_lib and not any(
rp.lower() == w for w in all_needed_dsos_lower
):
continue
if any(rp == normpath(w) for w in all_lib_exports[prefix]):
continue
rp_po = rp.replace("\\", "/")
owners = (
prefix_owners[prefix][rp_po]
if rp_po in prefix_owners[prefix]
else []
)
# Self-vendoring, not such a big deal but may as well report it?
if not len(owners):
if any(rp == normpath(w) for w in files):
owners.append(pkg_vendored_dist)
new_pkgs = list(which_package(rp, prefix))
# Cannot filter here as this means the DSO (eg libomp.dylib) will not be found in any package
# [owners.append(new_pkg) for new_pkg in new_pkgs if new_pkg not in owners
# and not any([fnmatch(new_pkg.name, i) for i in ignore_for_statics])]
for new_pkg in new_pkgs:
if new_pkg not in owners:
owners.append(new_pkg)
prefix_owners[prefix][rp_po] = owners
if len(prefix_owners[prefix][rp_po]):
exports = {
e
for e in get_exports_memoized(
fp, enable_static=enable_static
)
if not any(
fnmatch(e, pattern) for pattern in ignore_list_syms
)
}
all_lib_exports[prefix][rp_po] = exports
# Check codefile_class to filter out linker scripts.
if dynamic_lib:
contains_dsos[prefix_owners[prefix][rp_po][0]] = True
elif static_lib:
if sysroot_substitution in fp:
if (
prefix_owners[prefix][rp_po][0].name.startswith(
"gcc_impl_linux"
)
or prefix_owners[prefix][rp_po][0].name == "llvm"
):
continue
print(
f"sysroot in {fp}, owner is {prefix_owners[prefix][rp_po][0]}"
)
# Hmm, not right, muddies the prefixes again.
contains_static_libs[prefix_owners[prefix][rp_po][0]] = True
return prefix_owners, contains_dsos, contains_static_libs, all_lib_exports
def _print_msg(errors, text, verbose):
if text.startswith(" ERROR"):
errors.append(text)
if verbose:
print(text)
def caseless_sepless_fnmatch(paths, pat):
pat = pat.replace("\\", "/")
match = re.compile("(?i)" + fnmatch_translate(pat)).match
matches = [
path
for path in paths
if (path.replace("\\", "/") == pat) or match(path.replace("\\", "/"))
]
return matches
def _lookup_in_sysroots_and_whitelist(
errors,
whitelist,
needed_dso,
sysroots_files,
msg_prelude,
info_prelude,
sysroot_prefix,
sysroot_substitution,
subdir,
verbose,
):
# A system or ignored dependency. We should be able to find it in one of the CDT or
# compiler packages on linux or in a sysroot folder on other OSes. These usually
# start with '$RPATH/' which indicates pyldd did not find them, so remove that now.
if needed_dso.startswith(sysroot_substitution):
replacements = [sysroot_substitution] + [
sysroot for sysroot, _ in sysroots_files.items()
]