-
Notifications
You must be signed in to change notification settings - Fork 694
/
emsdk.py
3274 lines (2724 loc) · 123 KB
/
emsdk.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
#!/usr/bin/env python
# Copyright 2019 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
from __future__ import print_function
import copy
from collections import OrderedDict
import errno
import json
import multiprocessing
import os
import os.path
import platform
import re
import shutil
import stat
import subprocess
import sys
import sysconfig
import zipfile
if os.name == 'nt':
try:
import winreg
except ImportError:
# old python 2 name
import _winreg as winreg
import ctypes.wintypes
if sys.version_info >= (3,):
from urllib.parse import urljoin
from urllib.request import urlopen
import functools
else:
from urlparse import urljoin
from urllib2 import urlopen
emsdk_packages_url = 'https://storage.googleapis.com/webassembly/emscripten-releases-builds/deps/'
emscripten_releases_repo = 'https://chromium.googlesource.com/emscripten-releases'
emscripten_releases_download_url_template = "https://storage.googleapis.com/webassembly/emscripten-releases-builds/%s/%s/wasm-binaries%s.%s"
# This was previously `master.zip` but we are transitioning to `main` and
# `HEAD.zip` works for both cases. In future we could switch this to
# `main.zip` perhaps.
emsdk_zip_download_url = 'https://github.com/emscripten-core/emsdk/archive/HEAD.zip'
zips_subdir = 'zips/'
extra_release_tag = None
# Enable this to do very verbose printing about the different steps that are
# being run. Useful for debugging.
VERBOSE = int(os.getenv('EMSDK_VERBOSE', '0'))
TTY_OUTPUT = not os.getenv('EMSDK_NOTTY', not sys.stdout.isatty())
def errlog(msg):
print(msg, file=sys.stderr)
def exit_with_error(msg):
errlog('error: %s' % msg)
sys.exit(1)
WINDOWS = False
MINGW = False
MSYS = False
MACOS = False
LINUX = False
if 'EMSDK_OS' in os.environ:
EMSDK_OS = os.environ['EMSDK_OS']
if EMSDK_OS == 'windows':
WINDOWS = True
elif EMSDK_OS == 'linux':
LINUX = True
elif EMSDK_OS == 'macos':
MACOS = True
else:
assert False, 'EMSDK_OS must be one of: windows, linux, macos'
else:
if os.name == 'nt' or ('windows' in os.getenv('SYSTEMROOT', '').lower()) or ('windows' in os.getenv('COMSPEC', '').lower()):
WINDOWS = True
if os.getenv('MSYSTEM'):
MSYS = True
# Some functions like os.path.normpath() exhibit different behavior between
# different versions of Python, so we need to distinguish between the MinGW
# and MSYS versions of Python
if sysconfig.get_platform() == 'mingw':
MINGW = True
if os.getenv('MSYSTEM') != 'MSYS' and os.getenv('MSYSTEM') != 'MINGW64':
# https://stackoverflow.com/questions/37460073/msys-vs-mingw-internal-environment-variables
errlog('Warning: MSYSTEM environment variable is present, and is set to "' + os.getenv('MSYSTEM') + '". This shell has not been tested with emsdk and may not work.')
if platform.mac_ver()[0] != '':
MACOS = True
if not MACOS and (platform.system() == 'Linux'):
LINUX = True
UNIX = (MACOS or LINUX)
# Pick which shell of 4 shells to use
POWERSHELL = bool(os.getenv('EMSDK_POWERSHELL'))
CSH = bool(os.getenv('EMSDK_CSH'))
CMD = bool(os.getenv('EMSDK_CMD'))
BASH = bool(os.getenv('EMSDK_BASH'))
if WINDOWS and BASH:
MSYS = True
if not CSH and not POWERSHELL and not BASH and not CMD:
# Fall back to default of `cmd` on windows and `bash` otherwise
if WINDOWS and not MSYS:
CMD = True
else:
BASH = True
if WINDOWS:
ENVPATH_SEPARATOR = ';'
else:
ENVPATH_SEPARATOR = ':'
# platform.machine() may return AMD64 on windows, so standardize the case.
machine = os.getenv('EMSDK_ARCH', platform.machine().lower())
if machine.startswith('x64') or machine.startswith('amd64') or machine.startswith('x86_64'):
ARCH = 'x86_64'
elif machine.endswith('86'):
ARCH = 'x86'
elif machine.startswith('aarch64') or machine.lower().startswith('arm64'):
ARCH = 'aarch64'
elif machine.startswith('arm'):
ARCH = 'arm'
else:
exit_with_error('unknown machine architecture: ' + machine)
# Don't saturate all cores to not steal the whole system, but be aggressive.
CPU_CORES = int(os.getenv('EMSDK_NUM_CORES', max(multiprocessing.cpu_count() - 1, 1)))
CMAKE_BUILD_TYPE_OVERRIDE = None
# If true, perform a --shallow clone of git.
GIT_CLONE_SHALLOW = False
# If true, LLVM backend is built with tests enabled, and Binaryen is built with
# Visual Studio static analyzer enabled.
BUILD_FOR_TESTING = False
# If 'auto', assertions are decided by the build type
# (Release&MinSizeRel=disabled, Debug&RelWithDebInfo=enabled)
# Other valid values are 'ON' and 'OFF'
ENABLE_LLVM_ASSERTIONS = 'auto'
# If true, keeps the downloaded archive files.
KEEP_DOWNLOADS = bool(os.getenv('EMSDK_KEEP_DOWNLOADS'))
def os_name():
if WINDOWS:
return 'win'
elif LINUX:
return 'linux'
elif MACOS:
return 'mac'
else:
raise Exception('unknown OS')
def debug_print(msg):
if VERBOSE:
errlog(msg)
def to_unix_path(p):
return p.replace('\\', '/')
def emsdk_path():
return to_unix_path(os.path.dirname(os.path.realpath(__file__)))
EMSDK_SET_ENV = ""
if POWERSHELL:
EMSDK_SET_ENV = os.path.join(emsdk_path(), 'emsdk_set_env.ps1')
else:
EMSDK_SET_ENV = os.path.join(emsdk_path(), 'emsdk_set_env.bat')
# Parses https://github.com/emscripten-core/emscripten/tree/d6aced8 to a pair (https://github.com/emscripten-core/emscripten, d6aced8)
def parse_github_url_and_refspec(url):
if not url:
return ('', '')
if url.endswith(('/tree/', '/tree', '/commit/', '/commit')):
raise Exception('Malformed git URL and refspec ' + url + '!')
if '/tree/' in url:
if url.endswith('/'):
raise Exception('Malformed git URL and refspec ' + url + '!')
return url.split('/tree/')
elif '/commit/' in url:
if url.endswith('/'):
raise Exception('Malformed git URL and refspec ' + url + '!')
return url.split('/commit/')
else:
return (url, 'main') # Assume the default branch is main in the absence of a refspec
ARCHIVE_SUFFIXES = ('zip', '.tar', '.gz', '.xz', '.tbz2', '.bz2')
# Finds the given executable 'program' in PATH. Operates like the Unix tool 'which'.
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and (WINDOWS or os.access(fpath, os.X_OK))
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
if WINDOWS and '.' not in fname:
if is_exe(exe_file + '.exe'):
return exe_file + '.exe'
if is_exe(exe_file + '.cmd'):
return exe_file + '.cmd'
if is_exe(exe_file + '.bat'):
return exe_file + '.bat'
return None
def vswhere(version):
try:
program_files = os.getenv('ProgramFiles(x86)')
if not program_files:
program_files = os.environ['ProgramFiles']
vswhere_path = os.path.join(program_files, 'Microsoft Visual Studio', 'Installer', 'vswhere.exe')
output = json.loads(subprocess.check_output([vswhere_path, '-latest', '-version', '[%s.0,%s.0)' % (version, version + 1), '-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64', '-property', 'installationPath', '-format', 'json']))
# Visual Studio 2017 Express is not included in the above search, and it
# does not have the VC.Tools.x86.x64 tool, so do a catch-all attempt as a
# fallback, to detect Express version.
if not output:
output = json.loads(subprocess.check_output([vswhere_path, '-latest', '-version', '[%s.0,%s.0)' % (version, version + 1), '-products', '*', '-property', 'installationPath', '-format', 'json']))
if not output:
return ''
return str(output[0]['installationPath'])
except Exception:
return ''
def vs_filewhere(installation_path, platform, file):
try:
vcvarsall = os.path.join(installation_path, 'VC\\Auxiliary\\Build\\vcvarsall.bat')
env = subprocess.check_output('cmd /c "%s" %s & where %s' % (vcvarsall, platform, file))
paths = [path[:-len(file)] for path in env.split('\r\n') if path.endswith(file)]
return paths[0]
except Exception:
return ''
CMAKE_GENERATOR = 'Unix Makefiles'
if WINDOWS:
# Detect which CMake generator to use when building on Windows
if '--mingw' in sys.argv:
CMAKE_GENERATOR = 'MinGW Makefiles'
elif '--vs2017' in sys.argv:
CMAKE_GENERATOR = 'Visual Studio 15'
elif '--vs2019' in sys.argv:
CMAKE_GENERATOR = 'Visual Studio 16'
else:
vs2019_exists = len(vswhere(16)) > 0
vs2017_exists = len(vswhere(15)) > 0
mingw_exists = which('mingw32-make') is not None and which('g++') is not None
if vs2019_exists:
CMAKE_GENERATOR = 'Visual Studio 16'
elif vs2017_exists:
# VS2017 has an LLVM build issue, see
# https://github.com/kripken/emscripten-fastcomp/issues/185
CMAKE_GENERATOR = 'Visual Studio 15'
elif mingw_exists:
CMAKE_GENERATOR = 'MinGW Makefiles'
else:
# No detected generator
CMAKE_GENERATOR = ''
sys.argv = [a for a in sys.argv if a not in ('--mingw', '--vs2017', '--vs2019')]
# Computes a suitable path prefix to use when building with a given generator.
def cmake_generator_prefix():
if CMAKE_GENERATOR == 'Visual Studio 16':
return '_vs2019'
if CMAKE_GENERATOR == 'Visual Studio 15':
return '_vs2017'
elif CMAKE_GENERATOR == 'MinGW Makefiles':
return '_mingw'
# Unix Makefiles do not specify a path prefix for backwards path compatibility
return ''
# Removes a directory tree even if it was readonly, and doesn't throw exception
# on failure.
def remove_tree(d):
debug_print('remove_tree(' + str(d) + ')')
if not os.path.exists(d):
return
try:
def remove_readonly_and_try_again(func, path, exc_info):
if not (os.stat(path).st_mode & stat.S_IWRITE):
os.chmod(path, stat.S_IWRITE)
func(path)
else:
raise
shutil.rmtree(d, onerror=remove_readonly_and_try_again)
except Exception as e:
debug_print('remove_tree threw an exception, ignoring: ' + str(e))
def win_set_environment_variable_direct(key, value, system=True):
folder = None
try:
if system:
# Read globally from ALL USERS section.
folder = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', 0, winreg.KEY_ALL_ACCESS)
else:
# Register locally from CURRENT USER section.
folder = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, 'Environment', 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(folder, key, 0, winreg.REG_EXPAND_SZ, value)
debug_print('Set key=' + key + ' with value ' + value + ' in registry.')
return True
except Exception as e:
# 'Access is denied.'
if e.args[3] == 5:
exit_with_error('failed to set the environment variable \'' + key + '\'! Setting environment variables permanently requires administrator access. Please rerun this command with administrative privileges. This can be done for example by holding down the Ctrl and Shift keys while opening a command prompt in start menu.')
errlog('Failed to write environment variable ' + key + ':')
errlog(str(e))
return False
finally:
if folder is not None:
folder.Close()
def win_get_environment_variable(key, system=True, user=True, fallback=True):
if (not system and not user and fallback):
# if no --system or --permanent flag is provided use shell's value
return os.environ[key]
try:
folder = None
try:
if system:
# Read globally from ALL USERS section.
folder = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment')
else:
# Register locally from CURRENT USER section.
folder = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment')
value = str(winreg.QueryValueEx(folder, key)[0])
except Exception:
# If reading registry fails for some reason - read via os.environ. This has the drawback
# that expansion items such as %PROGRAMFILES% will have been expanded, so
# need to be precise not to set these back to system registry, or
# expansion items would be lost.
if fallback:
return os.environ[key]
return None
finally:
if folder is not None:
folder.Close()
except Exception as e:
# this catch is if both the registry key threw an exception and the key is not in os.environ
if e.args[0] != 2:
# 'The system cannot find the file specified.'
errlog('Failed to read environment variable ' + key + ':')
errlog(str(e))
return None
return value
def win_set_environment_variable(key, value, system, user):
debug_print('set ' + str(key) + '=' + str(value) + ', in system=' + str(system))
previous_value = win_get_environment_variable(key, system=system, user=user)
if previous_value == value:
debug_print(' no need to set, since same value already exists.')
# No need to elevate UAC for nothing to set the same value, skip.
return False
if not value:
try:
if system:
cmd = ['REG', 'DELETE', 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', '/V', key, '/f']
else:
cmd = ['REG', 'DELETE', 'HKCU\\Environment', '/V', key, '/f']
debug_print(str(cmd))
value = subprocess.call(cmd, stdout=subprocess.PIPE)
except Exception:
return False
return True
try:
if win_set_environment_variable_direct(key, value, system):
return True
# Escape % signs so that we don't expand references to environment variables.
value = value.replace('%', '^%')
if len(value) >= 1024:
exit_with_error('the new environment variable ' + key + ' is more than 1024 characters long! A value this long cannot be set via command line: please add the environment variable specified above to system environment manually via Control Panel.')
cmd = ['SETX', key, value]
debug_print(str(cmd))
retcode = subprocess.call(cmd, stdout=subprocess.PIPE)
if retcode != 0:
errlog('ERROR! Failed to set environment variable ' + key + '=' + value + '. You may need to set it manually.')
else:
return True
except Exception as e:
errlog('ERROR! Failed to set environment variable ' + key + '=' + value + ':')
errlog(str(e))
errlog('You may need to set it manually.')
return False
def win_set_environment_variables(env_vars_to_add, system, user):
if not env_vars_to_add:
return
changed = False
for key, value in env_vars_to_add:
if win_set_environment_variable(key, value, system, user):
if not changed:
changed = True
print('Setting global environment variables:')
print(key + ' = ' + value)
if not changed:
print('Global environment variables up to date')
return
# if changes were made then we need to notify other processes
try:
HWND_BROADCAST = ctypes.wintypes.HWND(0xFFFF) # win32con.HWND_BROADCAST == 65535
WM_SETTINGCHANGE = 0x001A # win32con.WM_SETTINGCHANGE == 26
SMTO_BLOCK = 0x0001 # win32con.SMTO_BLOCK == 1
ctypes.windll.user32.SendMessageTimeoutA(
HWND_BROADCAST, # hWnd: notify everyone
WM_SETTINGCHANGE, # Msg: registry changed
0, # wParam: Must be 0 when setting changed is sent by users
'Environment', # lParam: Specifically environment variables changed
SMTO_BLOCK, # fuFlags: Wait for message to be sent or timeout
100) # uTimeout: 100ms
except Exception as e:
errlog('SendMessageTimeout failed with error: ' + str(e))
def win_delete_environment_variable(key, system=True, user=True):
debug_print('win_delete_environment_variable(key=' + key + ', system=' + str(system) + ')')
return win_set_environment_variable(key, None, system, user)
# Returns the absolute pathname to the given path inside the Emscripten SDK.
def sdk_path(path):
if os.path.isabs(path):
return path
return to_unix_path(os.path.join(emsdk_path(), path))
# Removes a single file, suppressing exceptions on failure.
def rmfile(filename):
debug_print('rmfile(' + filename + ')')
if os.path.lexists(filename):
os.remove(filename)
# http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
def mkdir_p(path):
debug_print('mkdir_p(' + path + ')')
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno != errno.EEXIST or not os.path.isdir(path):
raise
def is_nonempty_directory(path):
if not os.path.isdir(path):
return False
return len(os.listdir(path)) != 0
def run(cmd, cwd=None, quiet=False):
debug_print('run(cmd=' + str(cmd) + ', cwd=' + str(cwd) + ')')
process = subprocess.Popen(cmd, cwd=cwd, env=os.environ.copy())
process.communicate()
if process.returncode != 0 and not quiet:
errlog(str(cmd) + ' failed with error code ' + str(process.returncode) + '!')
return process.returncode
# http://pythonicprose.blogspot.fi/2009/10/python-extract-targz-archive.html
def untargz(source_filename, dest_dir):
print("Unpacking '" + source_filename + "' to '" + dest_dir + "'")
mkdir_p(dest_dir)
returncode = run(['tar', '-xvf' if VERBOSE else '-xf', sdk_path(source_filename), '--strip', '1'], cwd=dest_dir)
# tfile = tarfile.open(source_filename, 'r:gz')
# tfile.extractall(dest_dir)
return returncode == 0
# On Windows, it is not possible to reference path names that are longer than
# ~260 characters, unless the path is referenced via a "\\?\" prefix.
# See https://msdn.microsoft.com/en-us/library/aa365247.aspx#maxpath and http://stackoverflow.com/questions/3555527/python-win32-filename-length-workaround
# In that mode, forward slashes cannot be used as delimiters.
def fix_potentially_long_windows_pathname(pathname):
if not WINDOWS or MSYS:
return pathname
# Test if emsdk calls fix_potentially_long_windows_pathname() with long
# relative paths (which is problematic)
if not os.path.isabs(pathname) and len(pathname) > 200:
errlog('Warning: Seeing a relative path "' + pathname + '" which is dangerously long for being referenced as a short Windows path name. Refactor emsdk to be able to handle this!')
if pathname.startswith('\\\\?\\'):
return pathname
pathname = os.path.normpath(pathname.replace('/', '\\'))
if MINGW:
# MinGW versions of Python return normalized paths with backslashes
# converted to forward slashes, so we must use forward slashes in our
# prefix
return '//?/' + pathname
return '\\\\?\\' + pathname
# On windows, rename/move will fail if the destination exists, and there is no
# race-free way to do it. This method removes the destination if it exists, so
# the move always works
def move_with_overwrite(src, dest):
if os.path.exists(dest):
os.remove(dest)
os.rename(src, dest)
# http://stackoverflow.com/questions/12886768/simple-way-to-unzip-file-in-python-on-all-oses
def unzip(source_filename, dest_dir):
print("Unpacking '" + source_filename + "' to '" + dest_dir + "'")
mkdir_p(dest_dir)
common_subdir = None
try:
with zipfile.ZipFile(source_filename) as zf:
# Implement '--strip 1' behavior to unzipping by testing if all the files
# in the zip reside in a common subdirectory, and if so, we move the
# output tree at the end of uncompression step.
for member in zf.infolist():
words = member.filename.split('/')
if len(words) > 1: # If there is a directory component?
if common_subdir is None:
common_subdir = words[0]
elif common_subdir != words[0]:
common_subdir = None
break
else:
common_subdir = None
break
unzip_to_dir = dest_dir
if common_subdir:
unzip_to_dir = os.path.join(os.path.dirname(dest_dir), 'unzip_temp')
# Now do the actual decompress.
for member in zf.infolist():
zf.extract(member, fix_potentially_long_windows_pathname(unzip_to_dir))
dst_filename = os.path.join(unzip_to_dir, member.filename)
# See: https://stackoverflow.com/questions/42326428/zipfile-in-python-file-permission
unix_attributes = member.external_attr >> 16
if unix_attributes:
os.chmod(dst_filename, unix_attributes)
# Move the extracted file to its final location without the base
# directory name, if we are stripping that away.
if common_subdir:
if not member.filename.startswith(common_subdir):
raise Exception('Unexpected filename "' + member.filename + '"!')
stripped_filename = '.' + member.filename[len(common_subdir):]
final_dst_filename = os.path.join(dest_dir, stripped_filename)
# Check if a directory
if stripped_filename.endswith('/'):
d = fix_potentially_long_windows_pathname(final_dst_filename)
if not os.path.isdir(d):
os.mkdir(d)
else:
parent_dir = os.path.dirname(fix_potentially_long_windows_pathname(final_dst_filename))
if parent_dir and not os.path.exists(parent_dir):
os.makedirs(parent_dir)
move_with_overwrite(fix_potentially_long_windows_pathname(dst_filename), fix_potentially_long_windows_pathname(final_dst_filename))
if common_subdir:
remove_tree(unzip_to_dir)
except zipfile.BadZipfile as e:
errlog("Unzipping file '" + source_filename + "' failed due to reason: " + str(e) + "! Removing the corrupted zip file.")
rmfile(source_filename)
return False
except Exception as e:
errlog("Unzipping file '" + source_filename + "' failed due to reason: " + str(e))
return False
return True
# This function interprets whether the given string looks like a path to a
# directory instead of a file, without looking at the actual filesystem.
# 'a/b/c' points to directory, so does 'a/b/c/', but 'a/b/c.x' is parsed as a
# filename
def path_points_to_directory(path):
if path == '.':
return True
last_slash = max(path.rfind('/'), path.rfind('\\'))
last_dot = path.rfind('.')
no_suffix = last_dot < last_slash or last_dot == -1
if no_suffix:
return True
suffix = path[last_dot:]
# Very simple logic for the only file suffixes used by emsdk downloader. Other
# suffixes, like 'clang-3.2' are treated as dirs.
if suffix in ('.exe', '.zip', '.txt'):
return False
else:
return True
def get_content_length(download):
try:
meta = download.info()
if hasattr(meta, "getheaders") and hasattr(meta.getheaders, "Content-Length"):
return int(meta.getheaders("Content-Length")[0])
elif hasattr(download, "getheader") and download.getheader('Content-Length'):
return int(download.getheader('Content-Length'))
elif hasattr(meta, "getheader") and meta.getheader('Content-Length'):
return int(meta.getheader('Content-Length'))
except Exception:
pass
return 0
def get_download_target(url, dstpath, filename_prefix=''):
file_name = filename_prefix + url.split('/')[-1]
if path_points_to_directory(dstpath):
file_name = os.path.join(dstpath, file_name)
else:
file_name = dstpath
# Treat all relative destination paths as relative to the SDK root directory,
# not the current working directory.
file_name = sdk_path(file_name)
return file_name
# On success, returns the filename on the disk pointing to the destination file that was produced
# On failure, returns None.
def download_file(url, dstpath, download_even_if_exists=False, filename_prefix=''):
debug_print('download_file(url=' + url + ', dstpath=' + dstpath + ')')
file_name = get_download_target(url, dstpath, filename_prefix)
if os.path.exists(file_name) and not download_even_if_exists:
print("File '" + file_name + "' already downloaded, skipping.")
return file_name
try:
u = urlopen(url)
mkdir_p(os.path.dirname(file_name))
with open(file_name, 'wb') as f:
file_size = get_content_length(u)
if file_size > 0:
print("Downloading: %s from %s, %s Bytes" % (file_name, url, file_size))
else:
print("Downloading: %s from %s" % (file_name, url))
file_size_dl = 0
# Draw a progress bar 80 chars wide (in non-TTY mode)
progress_max = 80 - 4
progress_shown = 0
block_sz = 256 * 1024
if not TTY_OUTPUT:
print(' [', end='')
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
if file_size:
percent = file_size_dl * 100.0 / file_size
if TTY_OUTPUT:
status = r" %10d [%3.02f%%]" % (file_size_dl, percent)
print(status, end='\r')
else:
while progress_shown < progress_max * percent / 100:
print('-', end='')
sys.stdout.flush()
progress_shown += 1
if not TTY_OUTPUT:
print(']')
sys.stdout.flush()
except Exception as e:
errlog("Error: Downloading URL '" + url + "': " + str(e))
if "SSL: CERTIFICATE_VERIFY_FAILED" in str(e) or "urlopen error unknown url type: https" in str(e):
errlog("Warning: Possibly SSL/TLS issue. Update or install Python SSL root certificates (2048-bit or greater) supplied in Python folder or https://pypi.org/project/certifi/ and try again.")
rmfile(file_name)
return None
except KeyboardInterrupt:
rmfile(file_name)
exit_with_error("aborted by user, exiting")
return file_name
def run_get_output(cmd, cwd=None):
debug_print('run_get_output(cmd=' + str(cmd) + ', cwd=' + str(cwd) + ')')
process = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, env=os.environ.copy(), universal_newlines=True)
stdout, stderr = process.communicate()
return (process.returncode, stdout, stderr)
cached_git_executable = None
# must_succeed: If false, the search is performed silently without printing out
# errors if not found. Empty string is returned if git is not found.
# If true, the search is required to succeed, and the execution
# will terminate with sys.exit(1) if not found.
def GIT(must_succeed=True):
global cached_git_executable
if cached_git_executable is not None:
return cached_git_executable
# The order in the following is important, and specifies the preferred order
# of using the git tools. Primarily use git from emsdk if installed. If not,
# use system git.
gits = ['git/1.9.4/bin/git.exe', which('git')]
for git in gits:
try:
ret, stdout, stderr = run_get_output([git, '--version'])
if ret == 0:
cached_git_executable = git
return git
except:
pass
if must_succeed:
if WINDOWS:
msg = "git executable was not found. Please install it by typing 'emsdk install git-1.9.4', or alternatively by installing it manually from http://git-scm.com/downloads . If you install git manually, remember to add it to PATH"
elif MACOS:
msg = "git executable was not found. Please install git for this operation! This can be done from http://git-scm.com/ , or by installing XCode and then the XCode Command Line Tools (see http://stackoverflow.com/questions/9329243/xcode-4-4-command-line-tools )"
elif LINUX:
msg = "git executable was not found. Please install git for this operation! This can be probably be done using your package manager, see http://git-scm.com/book/en/Getting-Started-Installing-Git"
else:
msg = "git executable was not found. Please install git for this operation!"
exit_with_error(msg)
# Not found
return ''
def git_repo_version(repo_path):
returncode, stdout, stderr = run_get_output([GIT(), 'log', '-n', '1', '--pretty="%aD %H"'], cwd=repo_path)
if returncode == 0:
return stdout.strip()
else:
return ""
def git_recent_commits(repo_path, n=20):
returncode, stdout, stderr = run_get_output([GIT(), 'log', '-n', str(n), '--pretty="%H"'], cwd=repo_path)
if returncode == 0:
return stdout.strip().replace('\r', '').replace('"', '').split('\n')
else:
return []
def git_clone(url, dstpath, branch):
debug_print('git_clone(url=' + url + ', dstpath=' + dstpath + ')')
if os.path.isdir(os.path.join(dstpath, '.git')):
debug_print("Repository '" + url + "' already cloned to directory '" + dstpath + "', skipping.")
return True
mkdir_p(dstpath)
git_clone_args = ['--recurse-submodules', '--branch', branch] # Do not check out a branch (installer will issue a checkout command right after)
if GIT_CLONE_SHALLOW:
git_clone_args += ['--depth', '1']
print('Cloning from ' + url + '...')
return run([GIT(), 'clone'] + git_clone_args + [url, dstpath]) == 0
def git_pull(repo_path, branch_or_tag):
debug_print('git_pull(repo_path=' + repo_path + ', branch/tag=' + branch_or_tag + ')')
ret = run([GIT(), 'fetch', '--quiet', 'origin'], repo_path)
if ret != 0:
return False
try:
print("Fetching latest changes to the branch/tag '" + branch_or_tag + "' for '" + repo_path + "'...")
ret = run([GIT(), 'fetch', '--quiet', 'origin'], repo_path)
if ret != 0:
return False
# this line assumes that the user has not gone and manually messed with the
# repo and added new remotes to ambiguate the checkout.
ret = run([GIT(), 'checkout', '--recurse-submodules', '--quiet', branch_or_tag], repo_path)
if ret != 0:
return False
# Test if branch_or_tag is a branch, or if it is a tag that needs to be updated
target_is_tag = run([GIT(), 'symbolic-ref', '-q', 'HEAD'], repo_path, quiet=True)
if not target_is_tag:
# update branch to latest (not needed for tags)
# this line assumes that the user has not gone and made local changes to the repo
ret = run([GIT(), 'merge', '--ff-only', 'origin/' + branch_or_tag], repo_path)
if ret != 0:
return False
run([GIT(), 'submodule', 'update', '--init'], repo_path, quiet=True)
except:
errlog('git operation failed!')
return False
print("Successfully updated and checked out branch/tag '" + branch_or_tag + "' on repository '" + repo_path + "'")
print("Current repository version: " + git_repo_version(repo_path))
return True
def git_clone_checkout_and_pull(url, dstpath, branch):
debug_print('git_clone_checkout_and_pull(url=' + url + ', dstpath=' + dstpath + ', branch=' + branch + ')')
# If the repository has already been cloned before, issue a pull operation. Otherwise do a new clone.
if os.path.isdir(os.path.join(dstpath, '.git')):
return git_pull(dstpath, branch)
else:
return git_clone(url, dstpath, branch)
# Each tool can have its own build type, or it can be overridden on the command
# line.
def decide_cmake_build_type(tool):
if CMAKE_BUILD_TYPE_OVERRIDE:
return CMAKE_BUILD_TYPE_OVERRIDE
else:
return tool.cmake_build_type
# The root directory of the build.
def llvm_build_dir(tool):
generator_suffix = ''
if CMAKE_GENERATOR == 'Visual Studio 15':
generator_suffix = '_vs2017'
elif CMAKE_GENERATOR == 'Visual Studio 16':
generator_suffix = '_vs2019'
elif CMAKE_GENERATOR == 'MinGW Makefiles':
generator_suffix = '_mingw'
bitness_suffix = '_32' if tool.bitness == 32 else '_64'
if hasattr(tool, 'git_branch'):
build_dir = 'build_' + tool.git_branch.replace(os.sep, '-') + generator_suffix + bitness_suffix
else:
build_dir = 'build_' + tool.version + generator_suffix + bitness_suffix
return build_dir
def exe_suffix(filename):
if WINDOWS and not filename.endswith('.exe'):
filename += '.exe'
return filename
# The directory where the binaries are produced. (relative to the installation
# root directory of the tool)
def fastcomp_build_bin_dir(tool):
build_dir = llvm_build_dir(tool)
if WINDOWS and 'Visual Studio' in CMAKE_GENERATOR:
old_llvm_bin_dir = os.path.join(build_dir, 'bin', decide_cmake_build_type(tool))
new_llvm_bin_dir = None
default_cmake_build_type = decide_cmake_build_type(tool)
cmake_build_types = [default_cmake_build_type, 'Release', 'RelWithDebInfo', 'MinSizeRel', 'Debug']
for build_type in cmake_build_types:
d = os.path.join(build_dir, build_type, 'bin')
if os.path.isfile(os.path.join(tool.installation_path(), d, exe_suffix('clang'))):
new_llvm_bin_dir = d
break
if new_llvm_bin_dir and os.path.exists(os.path.join(tool.installation_path(), new_llvm_bin_dir)):
return new_llvm_bin_dir
elif os.path.exists(os.path.join(tool.installation_path(), old_llvm_bin_dir)):
return old_llvm_bin_dir
return os.path.join(build_dir, default_cmake_build_type, 'bin')
else:
return os.path.join(build_dir, 'bin')
def build_env(generator):
build_env = os.environ.copy()
# To work around a build issue with older Mac OS X builds, add -stdlib=libc++ to all builds.
# See https://groups.google.com/forum/#!topic/emscripten-discuss/5Or6QIzkqf0
if MACOS:
build_env['CXXFLAGS'] = ((build_env['CXXFLAGS'] + ' ') if hasattr(build_env, 'CXXFLAGS') else '') + '-stdlib=libc++'
elif 'Visual Studio 15' in generator or 'Visual Studio 16' in generator:
if 'Visual Studio 16' in generator:
path = vswhere(16)
else:
path = vswhere(15)
# Configuring CMake for Visual Studio needs and env. var VCTargetsPath to be present.
# How this is supposed to work is unfortunately very undocumented. See
# https://discourse.cmake.org/t/cmake-failed-to-get-the-value-of-vctargetspath-with-vs2019-16-7/1839/16
# for some conversation. Try a couple of common paths if one of them would work.
# In the future as new versions of VS come out, we likely need to add new paths into this list.
if 'VCTargetsPath' not in build_env:
vctargets_paths = [
os.path.join(path, 'MSBuild\\Microsoft\\VC\\v160\\'),
os.path.join(path, 'Common7\\IDE\\VC\\VCTargets')
]
for p in vctargets_paths:
if os.path.isfile(os.path.join(p, 'Microsoft.Cpp.Default.props')):
debug_print('Set env. var VCTargetsPath=' + p + ' for CMake.')
build_env['VCTargetsPath'] = p
break
else:
debug_print('Searched path ' + p + ' as candidate for VCTargetsPath, not working.')
if 'VCTargetsPath' not in build_env:
errlog('Unable to locate Visual Studio compiler installation for generator "' + generator + '"!')
errlog('Either rerun installation in Visual Studio Command Prompt, or locate directory to Microsoft.Cpp.Default.props manually')
sys.exit(1)
# CMake and VS2017 cl.exe needs to have mspdb140.dll et al. in its PATH.
vc_bin_paths = [vs_filewhere(path, 'amd64', 'cl.exe'),
vs_filewhere(path, 'x86', 'cl.exe')]
for path in vc_bin_paths:
if os.path.isdir(path):
build_env['PATH'] = build_env['PATH'] + ';' + path
return build_env
def get_generator_for_sln_file(sln_file):
contents = open(sln_file, 'r').read()
if '# Visual Studio 16' in contents or '# Visual Studio Version 16' in contents: # VS2019
return 'Visual Studio 16'
if '# Visual Studio 15' in contents: # VS2017
return 'Visual Studio 15'
raise Exception('Unknown generator used to build solution file ' + sln_file)
def find_msbuild(sln_file):
# The following logic attempts to find a Visual Studio version specific
# MSBuild.exe from a list of known locations.
generator = get_generator_for_sln_file(sln_file)
debug_print('find_msbuild looking for generator ' + str(generator))
if generator == 'Visual Studio 16': # VS2019
path = vswhere(16)
search_paths = [os.path.join(path, 'MSBuild/Current/Bin'),
os.path.join(path, 'MSBuild/15.0/Bin/amd64'),
os.path.join(path, 'MSBuild/15.0/Bin')]
elif generator == 'Visual Studio 15': # VS2017
path = vswhere(15)
search_paths = [os.path.join(path, 'MSBuild/15.0/Bin/amd64'),
os.path.join(path, 'MSBuild/15.0/Bin')]
else:
raise Exception('Unknown generator!')
for path in search_paths:
p = os.path.join(path, 'MSBuild.exe')
debug_print('Searching for MSBuild.exe: ' + p)
if os.path.isfile(p):
return p
debug_print('MSBuild.exe in PATH? ' + str(which('MSBuild.exe')))
# Last fallback, try any MSBuild from PATH (might not be compatible, but best effort)
return which('MSBuild.exe')
def make_build(build_root, build_type, build_target_platform='x64'):
debug_print('make_build(build_root=' + build_root + ', build_type=' + build_type + ', build_target_platform=' + build_target_platform + ')')
if CPU_CORES > 1:
print('Performing a parallel build with ' + str(CPU_CORES) + ' cores.')
else:
print('Performing a singlethreaded build.')
generator_to_use = CMAKE_GENERATOR
if WINDOWS:
if 'Visual Studio' in CMAKE_GENERATOR:
solution_name = str(subprocess.check_output(['dir', '/b', '*.sln'], shell=True, cwd=build_root).decode('utf-8').strip())
generator_to_use = get_generator_for_sln_file(os.path.join(build_root, solution_name))
# Disabled for now: Don't pass /maxcpucount argument to msbuild, since it