-
Notifications
You must be signed in to change notification settings - Fork 415
/
post.py
1390 lines (1243 loc) · 64.4 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
from __future__ import absolute_import, division, print_function
from copy import copy
from collections import defaultdict, OrderedDict
from functools import partial
from fnmatch import fnmatch, filter as fnmatch_filter, translate as fnmatch_translate
from os.path import (basename, commonprefix, dirname, exists, isabs, isdir, isfile,
islink, join, normpath, realpath, relpath, sep, splitext)
import io
import locale
import re
import os
import shutil
import stat
from subprocess import call, check_output, CalledProcessError
import sys
try:
from os import readlink
except ImportError:
readlink = False
from conda_build.os_utils import external
from conda_build.conda_interface import PY3
from conda_build.conda_interface import lchmod
from conda_build.conda_interface import walk_prefix
from conda_build.conda_interface import TemporaryDirectory
from conda_build.conda_interface import md5_file
from conda_build import utils
from conda_build.os_utils.liefldd import (have_lief, get_exports_memoized,
get_linkages_memoized, get_rpaths_raw,
get_runpaths_raw, set_rpath)
from conda_build.os_utils.pyldd import codefile_type
from conda_build.os_utils.ldd import get_package_files, get_package_obj_files
from conda_build.index import get_build_index
from conda_build.inspect_pkg import which_package
from conda_build.exceptions import (OverLinkingError, OverDependingError, RunPathError)
if sys.platform == 'darwin':
from conda_build.os_utils import macho
if PY3:
scandir = os.scandir
else:
from scandir import scandir
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_type(path):
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 io.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(br'^#!.+$', re.M)
bytes_ = True
m = SHEBANG_PAT.match(mm)
if m:
python_pattern = (re.compile(br'\/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 sys.platform == 'darwin' 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 io.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),
'%s.pth' % (fn.split('-')[0])), 'w') as fo:
fo.write('./%s\n' % fn)
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 IOError as e:
fn = basename(str(e).split()[-1])
raise IOError("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."
.format(egg_path=egg_path, sp_dir=sp_dir, fn=fn))
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(".dist-info{}INSTALLER".format(sep))]
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(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 sys.platform == 'win32':
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 PY3 else ""
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 sys.platform == 'win32':
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("ERROR: Top level dist-info version incorrect (is {}, should be {})".format(f_lower, 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("Error: Could not find %s" % 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("Error: Could not find %s" % 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(md5_file(join(prefix, f)))
if len(md5s) > 1:
sys.exit("Error: Found multiple instances of %s: %s" % (link, file_names[link]))
else:
file_names[link].sort()
print("Found multiple instances of %s (%s). "
"Choosing the first one." % (link, file_names[link]))
return file_names[link][0]
print("Don't know how to find %s, skipping" % link)
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("Fixing linking of %s in %s" % (link, path))
print(".. seems to be linking to a compiler runtime, replacing build prefix with "
"host prefix and")
if not codefile_type(link):
sys.exit("Error: Compiler runtime library in build prefix not found in host prefix %s"
% link)
else:
print(".. fixing linking of %s in %s instead" % (link, path))
link_loc = find_lib(link, host_prefix, files, path)
if not link_loc:
return
print("Fixing linking of %s in %s" % (link, path))
print("New link location is %s" % (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 = '@rpath/%s/%s' % (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, build_prefix, files, rpaths=('lib',)):
if sys.platform != 'darwin':
log = utils.get_logger(__name__)
log.warn("Found Mach-O file but patching is only supported on macOS, skipping: %s", path)
return
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:
# 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)
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("ERROR :: You should install patchelf, will proceed with LIEF for {} (was {})".format(elf, method))
method = 'LIEF'
else:
try:
existing_pe = check_output([patchelf, '--print-rpath', elf]).decode('utf-8').splitlines()[0]
except CalledProcessError:
if method == 'patchelf':
print("ERROR :: `patchelf --print-rpath` failed for {}, but patchelf was specified".format(
elf))
elif method != 'LIEF':
print("WARNING :: `patchelf --print-rpath` failed for {}, will proceed with LIEF (was {})".format(
elf, 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('WARNING :: get_rpaths_raw()={} and patchelf={} disagree for {} :: '.format(
existing2, [existing_pe], 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('Warning: rpath {0} is outside prefix {1} (removing it)'.format(old, prefix))
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('/'):
# IMHO utils.relative shouldn't exist, but I am too paranoid to remove
# it, so instead, make sure that what I think it should be replaced by
# gives the same result and assert if not. Yeah, I am a chicken.
rel_ours = normpath(utils.relative(f, rpath))
rel_stdlib = normpath(relpath(rpath, dirname(f)))
if not rel_ours == rel_stdlib:
raise ValueError('utils.relative {0} and relpath {1} disagree for {2}, {3}'.format(
rel_ours, rel_stdlib, f, rpath))
rpath = '$ORIGIN/' + rel_stdlib
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("library at %s appears to have an absolute path embedded" % path)
def determine_package_nature(pkg, prefix, subdir, bldpkgs_dir, output_folder, channel_urls):
run_exports = None
lib_prefix = pkg.name.startswith('lib')
codefiles = get_package_obj_files(pkg, prefix)
# get_package_obj_files already filters by extension and I'm not sure we need two.
dsos = [f for f in codefiles for ext in ('.dylib', '.so', '.dll', '.pyd') if ext in f]
# we don't care about the actual run_exports value, just whether or not run_exports are present.
# We can use channeldata and it'll be a more reliable source (no disk race condition nonsense)
_, _, channeldata1 = get_build_index(subdir=subdir,
bldpkgs_dir=bldpkgs_dir,
output_folder=output_folder,
channel_urls=channel_urls,
debug=False,
verbose=False,
clear_cache=False)
channel_used = pkg.channel
channeldata = channeldata1.get(channel_used)
# If the Dists end up coming from a multichannel such as 'defaults'
# instead of a real channel such as 'pkgs/main' then this assert
# can fire. To prevent that we use our own linked_data_no_multichannels()
# instead of conda's linked_data()
# The `or isinstance(pkg, FakeDist)` covers the case of an empty local channel.
assert isinstance(channeldata, dict) or isinstance(pkg, FakeDist)
if channeldata and pkg.name in channeldata['packages']:
run_exports = channeldata['packages'][pkg.name].get('run_exports', {})
return (dsos, run_exports, lib_prefix)
def library_nature(pkg, prefix, subdir, bldpkgs_dirs, output_folder, channel_urls):
'''
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.
'''
dsos, run_exports, _ = determine_package_nature(pkg, prefix, subdir, bldpkgs_dirs, output_folder, channel_urls)
if pkg.name == 'python':
return "interpreter (Python)"
elif pkg.name == 'r-base':
return "interpreter (R)"
if run_exports:
return "run-exports library"
elif len(dsos):
# 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]
dsos_without_plugins = [dso for dso in dsos if dso not in r_dsos + python_dsos]
if len(dsos_without_plugins):
return "dso library"
else:
if 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:
files = get_package_files(pkg, prefix)
python_files = [f for f in files if 'site-packages' in f]
r_files = [f for f in files if 'lib/R/library' in f]
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"
def dists_from_names(names, prefix):
results = []
from conda_build.utils import linked_data_no_multichannels
pkgs = linked_data_no_multichannels(prefix)
for name in names:
for pkg in pkgs:
if pkg.quad[0] == name:
results.append(pkg)
return results
class FakeDist:
def __init__(self, name, version, build_number, build_str, channel, files):
self.name = name
self.quad = [name]
self.version = version
self.build_number = build_number
self.build_string = build_str
self.channel = channel
self.files = files
def get(self, name):
if name == 'files':
return self.files
# 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()
sysroot = ''
if sysroots_files:
sysroot = list(sysroots_files.keys())[0]
for f in files:
path = join(run_prefix, f)
if not codefile_type(path):
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=sysroot, 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(set(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_type(fp, skip_symlinks=False) is not None
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))
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, avoid_canonical_channel_name=True))
# 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 = set(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_type 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("sysroot in {}, owner is {}".format(fp, 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 _get_fake_pkg_dist(pkg_name, pkg_version, build_str, build_number, channel, files):
pkg_vendoring_name = pkg_name
pkg_vendoring_version = str(pkg_version)
pkg_vendoring_build_str = build_str
pkg_vendoring_build_number = build_number
pkg_vendoring_key = '-'.join([pkg_vendoring_name,
pkg_vendoring_version,
pkg_vendoring_build_str])
return FakeDist(pkg_vendoring_name,
pkg_vendoring_version,
pkg_vendoring_build_number,
pkg_vendoring_build_str,
channel,
files), pkg_vendoring_key
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()]
else:
replacements = [needed_dso]
in_whitelist = False
in_sysroots = False
if len(sysroots_files):
# Check if we have a CDT package or a file in a sysroot.
sysroot_files = []
for sysroot, files in sysroots_files.items():
sysroot_os = sysroot.replace('\\', os.sep)
if needed_dso.startswith(sysroot_substitution):
# Do we want to do this replace?
sysroot_files.append(needed_dso.replace(sysroot_substitution, sysroot_os))
else:
found = caseless_sepless_fnmatch(files, needed_dso[1:])
sysroot_files.extend(found)
if len(sysroot_files):
in_sysroots = True
if 'osx-64' in subdir or 'win' in subdir:
in_prefix_dso = sysroot_files[0]
n_dso_p = "Needed DSO {}".format(in_prefix_dso)
_print_msg(errors, '{}: {} found in $SYSROOT'.
format(info_prelude, n_dso_p), verbose=verbose)
else:
# Removing sysroot_prefix is only for Linux, though we could
# use CONDA_BUILD_SYSROOT for macOS. We should figure out what to do about
# /opt/X11 too.
pkgs = []
for idx in range(len(sysroot_files)):
# in_prefix_dso = normpath(sysroot_files[idx].replace(
# sysroot_prefix + os.sep, ''))
in_prefix_dso = sysroot_files[idx][len(sysroot_prefix) + 1:]
n_dso_p = "Needed DSO {}".format(in_prefix_dso)
_pkgs = list(which_package(in_prefix_dso, sysroot_prefix))
if len(_pkgs) > 0:
pkgs.extend(_pkgs)
break
if len(pkgs):
_print_msg(errors, '{}: {} found in CDT/compiler package {}'.
format(info_prelude, n_dso_p, pkgs[0]), verbose=verbose)
else:
_print_msg(errors, '{}: {} not found in any CDT/compiler package,'
' nor the whitelist?!'.
format(msg_prelude, n_dso_p), verbose=verbose)
if not in_sysroots:
# It takes a very long time to glob in C:/Windows so we do not do that.
for replacement in replacements:
needed_dso_w = needed_dso.replace(sysroot_substitution, replacement + '/')
# We should pass in multiple paths at once to this, but the code isn't structured for that.
in_whitelist = any([caseless_sepless_fnmatch([needed_dso_w], w) for w in whitelist])
if in_whitelist:
n_dso_p = "Needed DSO {}".format(needed_dso_w)
_print_msg(errors, '{}: {} found in the whitelist'.
format(info_prelude, n_dso_p), verbose=verbose)
break
if not in_whitelist and not in_sysroots:
_print_msg(errors, "{}: {} not found in packages, sysroot(s) nor the missing_dso_whietlist.\n"
".. is this binary repackaging?".
format(msg_prelude, needed_dso), verbose=verbose)
def _lookup_in_prefix_packages(errors, needed_dso, files, run_prefix, whitelist, info_prelude, msg_prelude,
warn_prelude, verbose, requirements_run, lib_packages, lib_packages_used):
in_prefix_dso = normpath(needed_dso)
n_dso_p = "Needed DSO {}".format(in_prefix_dso.replace('\\', '/'))
and_also = " (and also in this package)" if in_prefix_dso in files else ""
pkgs = list(which_package(in_prefix_dso, run_prefix, avoid_canonical_channel_name=True))
in_pkgs_in_run_reqs = [pkg for pkg in pkgs if pkg.quad[0] in requirements_run]
# TODO :: metadata build/inherit_child_run_exports (for vc, mro-base-impl).
for pkg in in_pkgs_in_run_reqs:
if pkg in lib_packages:
lib_packages_used.add(pkg)
in_whitelist = any([fnmatch(in_prefix_dso, w) for w in whitelist])
if len(in_pkgs_in_run_reqs) == 1:
_print_msg(errors, '{}: {} found in {}{}'.format(info_prelude,
n_dso_p,
in_pkgs_in_run_reqs[0],
and_also), verbose=verbose)
elif in_whitelist:
_print_msg(errors, '{}: {} found in the whitelist'.
format(info_prelude, n_dso_p), verbose=verbose)
elif len(in_pkgs_in_run_reqs) == 0 and len(pkgs) > 0:
_print_msg(errors, '{}: {} found in {}{}'.format(msg_prelude,
n_dso_p,
[p.quad[0] for p in pkgs],
and_also), verbose=verbose)
_print_msg(errors, '{}: .. but {} not in reqs/run, (i.e. it is overlinking)'
' (likely) or a missing dependency (less likely)'.
format(msg_prelude, [p.quad[0] for p in pkgs]), verbose=verbose)
elif len(in_pkgs_in_run_reqs) > 1:
_print_msg(errors, '{}: {} found in multiple packages in run/reqs: {}{}'
.format(warn_prelude,
in_prefix_dso,
in_pkgs_in_run_reqs,
and_also), verbose=verbose)
else:
if not any(in_prefix_dso == normpath(w) for w in files):
_print_msg(errors, '{}: {} not found in any packages'.format(msg_prelude,
in_prefix_dso), verbose=verbose)
elif verbose:
_print_msg(errors, '{}: {} found in this package'.format(info_prelude,
in_prefix_dso), verbose=verbose)
def _show_linking_messages(files, errors, needed_dsos_for_file, build_prefix, run_prefix, pkg_name,
error_overlinking, runpath_whitelist, verbose, requirements_run, lib_packages,
lib_packages_used, whitelist, sysroots, sysroot_prefix, sysroot_substitution, subdir):
if len(sysroots):
for sysroot, sr_files in sysroots.items():
_print_msg(errors, " INFO: sysroot: '{}' files: '{}'".format(sysroot,
sorted(list(sr_files), reverse=True)[1:5]),
verbose=verbose)
for f in files:
path = join(run_prefix, f)
filetype = codefile_type(path)
if not filetype or filetype not in filetypes_for_platform[subdir.split('-')[0]]:
continue
warn_prelude = "WARNING ({},{})".format(pkg_name, f.replace(os.sep, '/'))
err_prelude = " ERROR ({},{})".format(pkg_name, f.replace(os.sep, '/'))
info_prelude = " INFO ({},{})".format(pkg_name, f.replace(os.sep, '/'))
msg_prelude = err_prelude if error_overlinking else warn_prelude
# TODO :: Determine this much earlier, storing in needed_dsos_for_file in _collect_needed_dsos()
try:
runpaths, _, _ = get_runpaths_raw(path)
except:
_print_msg(errors, '{}: pyldd.py failed to process'.format(warn_prelude),
verbose=verbose)
continue