forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared.py
1924 lines (1672 loc) · 74.3 KB
/
shared.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
import shutil, time, os, sys, json, tempfile, copy, shlex, atexit, subprocess, hashlib, cPickle, re, errno
from subprocess import Popen, PIPE, STDOUT
from tempfile import mkstemp
from distutils.spawn import find_executable
import jsrun, cache, tempfiles
import response_file
import logging, platform, multiprocessing
# Temp file utilities
from tempfiles import try_delete
# On Windows python suffers from a particularly nasty bug if python is spawning new processes while python itself is spawned from some other non-console process.
# Use a custom replacement for Popen on Windows to avoid the "WindowsError: [Error 6] The handle is invalid" errors when emcc is driven through cmake or mingw32-make.
# See http://bugs.python.org/issue3905
class WindowsPopen:
def __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False,
shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
# (stdin, stdout, stderr) store what the caller originally wanted to be done with the streams.
# (stdin_, stdout_, stderr_) will store the fixed set of streams that workaround the bug.
self.stdin_ = stdin
self.stdout_ = stdout
self.stderr_ = stderr
# If the caller wants one of these PIPEd, we must PIPE them all to avoid the 'handle is invalid' bug.
if self.stdin_ == PIPE or self.stdout_ == PIPE or self.stderr_ == PIPE:
if self.stdin_ == None:
self.stdin_ = PIPE
if self.stdout_ == None:
self.stdout_ = PIPE
if self.stderr_ == None:
self.stderr_ = PIPE
# emscripten.py supports reading args from a response file instead of cmdline.
# Use .rsp to avoid cmdline length limitations on Windows.
if len(args) >= 2 and args[1].endswith("emscripten.py"):
response_filename = response_file.create_response_file(args[2:], TEMP_DIR)
args = args[0:2] + ['@' + response_filename]
try:
# Call the process with fixed streams.
self.process = subprocess.Popen(args, bufsize, executable, self.stdin_, self.stdout_, self.stderr_, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
self.pid = self.process.pid
except Exception, e:
logging.error('\nsubprocess.Popen(args=%s) failed! Exception %s\n' % (' '.join(args), str(e)))
raise e
def communicate(self, input=None):
output = self.process.communicate(input)
self.returncode = self.process.returncode
# If caller never wanted to PIPE stdout or stderr, route the output back to screen to avoid swallowing output.
if self.stdout == None and self.stdout_ == PIPE and len(output[0].strip()) > 0:
print >> sys.stdout, output[0]
if self.stderr == None and self.stderr_ == PIPE and len(output[1].strip()) > 0:
print >> sys.stderr, output[1]
# Return a mock object to the caller. This works as long as all emscripten code immediately .communicate()s the result, and doesn't
# leave the process object around for longer/more exotic uses.
if self.stdout == None and self.stderr == None:
return (None, None)
if self.stdout == None:
return (None, output[1])
if self.stderr == None:
return (output[0], None)
return (output[0], output[1])
def poll(self):
return self.process.poll()
def kill(self):
return self.process.kill()
__rootpath__ = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
def path_from_root(*pathelems):
return os.path.join(__rootpath__, *pathelems)
def add_coloring_to_emit_windows(fn):
def _out_handle(self):
import ctypes
return ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)
out_handle = property(_out_handle)
def _set_color(self, code):
import ctypes
# Constants from the Windows API
self.STD_OUTPUT_HANDLE = -11
hdl = ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)
ctypes.windll.kernel32.SetConsoleTextAttribute(hdl, code)
setattr(logging.StreamHandler, '_set_color', _set_color)
def new(*args):
FOREGROUND_BLUE = 0x0001 # text color contains blue.
FOREGROUND_GREEN = 0x0002 # text color contains green.
FOREGROUND_RED = 0x0004 # text color contains red.
FOREGROUND_INTENSITY = 0x0008 # text color is intensified.
FOREGROUND_WHITE = FOREGROUND_BLUE|FOREGROUND_GREEN |FOREGROUND_RED
# winbase.h
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# wincon.h
FOREGROUND_BLACK = 0x0000
FOREGROUND_BLUE = 0x0001
FOREGROUND_GREEN = 0x0002
FOREGROUND_CYAN = 0x0003
FOREGROUND_RED = 0x0004
FOREGROUND_MAGENTA = 0x0005
FOREGROUND_YELLOW = 0x0006
FOREGROUND_GREY = 0x0007
FOREGROUND_INTENSITY = 0x0008 # foreground color is intensified.
BACKGROUND_BLACK = 0x0000
BACKGROUND_BLUE = 0x0010
BACKGROUND_GREEN = 0x0020
BACKGROUND_CYAN = 0x0030
BACKGROUND_RED = 0x0040
BACKGROUND_MAGENTA = 0x0050
BACKGROUND_YELLOW = 0x0060
BACKGROUND_GREY = 0x0070
BACKGROUND_INTENSITY = 0x0080 # background color is intensified.
levelno = args[1].levelno
if(levelno >= 50):
color = BACKGROUND_YELLOW | FOREGROUND_RED | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY
elif(levelno >= 40):
color = FOREGROUND_RED | FOREGROUND_INTENSITY
elif(levelno >= 30):
color = FOREGROUND_YELLOW | FOREGROUND_INTENSITY
elif(levelno >= 20):
color = FOREGROUND_GREEN
elif(levelno >= 10):
color = FOREGROUND_MAGENTA
else:
color = FOREGROUND_WHITE
args[0]._set_color(color)
ret = fn(*args)
args[0]._set_color( FOREGROUND_WHITE )
#print "after"
return ret
return new
def add_coloring_to_emit_ansi(fn):
# add methods we need to the class
def new(*args):
levelno = args[1].levelno
if(levelno >= 50):
color = '\x1b[31m' # red
elif(levelno >= 40):
color = '\x1b[31m' # red
elif(levelno >= 30):
color = '\x1b[33m' # yellow
elif(levelno >= 20):
color = '\x1b[32m' # green
elif(levelno >= 10):
color = '\x1b[35m' # pink
else:
color = '\x1b[0m' # normal
args[1].msg = color + args[1].msg + '\x1b[0m' # normal
#print "after"
return fn(*args)
return new
WINDOWS = sys.platform.startswith('win')
if WINDOWS:
logging.StreamHandler.emit = add_coloring_to_emit_windows(logging.StreamHandler.emit)
else:
logging.StreamHandler.emit = add_coloring_to_emit_ansi(logging.StreamHandler.emit)
# Emscripten configuration is done through the --em-config command line option or
# the EM_CONFIG environment variable. If the specified string value contains newline
# or semicolon-separated definitions, then these definitions will be used to configure
# Emscripten. Otherwise, the string is understood to be a path to a settings
# file that contains the required definitions.
try:
EM_CONFIG = sys.argv[sys.argv.index('--em-config')+1]
# And now remove it from sys.argv
skip = False
newargs = []
for arg in sys.argv:
if not skip and arg != '--em-config':
newargs += [arg]
elif arg == '--em-config':
skip = True
elif skip:
skip = False
sys.argv = newargs
# Emscripten compiler spawns other processes, which can reimport shared.py, so make sure that
# those child processes get the same configuration file by setting it to the currently active environment.
os.environ['EM_CONFIG'] = EM_CONFIG
except:
EM_CONFIG = os.environ.get('EM_CONFIG')
if EM_CONFIG and not os.path.isfile(EM_CONFIG):
if EM_CONFIG.startswith('-'):
raise Exception('Passed --em-config without an argument. Usage: --em-config /path/to/.emscripten or --em-config EMSCRIPTEN_ROOT=/path/;LLVM_ROOT=/path;...')
if not '=' in EM_CONFIG:
raise Exception('File ' + EM_CONFIG + ' passed to --em-config does not exist!')
else:
EM_CONFIG = EM_CONFIG.replace(';', '\n') + '\n'
if not EM_CONFIG:
EM_CONFIG = '~/.emscripten'
if '\n' in EM_CONFIG:
CONFIG_FILE = None
else:
CONFIG_FILE = os.path.expanduser(EM_CONFIG)
if not os.path.exists(CONFIG_FILE):
# Note: repr is used to ensure the paths are escaped correctly on Windows.
# The full string is replaced so that the template stays valid Python.
config_file = open(path_from_root('tools', 'settings_template_readonly.py')).read().split('\n')
config_file = config_file[1:] # remove "this file will be copied..."
config_file = '\n'.join(config_file)
# autodetect some default paths
config_file = config_file.replace('\'{{{ EMSCRIPTEN_ROOT }}}\'', repr(__rootpath__))
llvm_root = os.path.dirname(find_executable('llvm-dis') or '/usr/bin/llvm-dis')
config_file = config_file.replace('\'{{{ LLVM_ROOT }}}\'', repr(llvm_root))
node = find_executable('node') or find_executable('nodejs') or 'node'
config_file = config_file.replace('\'{{{ NODE }}}\'', repr(node))
if WINDOWS:
tempdir = os.environ.get('TEMP') or os.environ.get('TMP') or 'c:\\temp'
else:
tempdir = '/tmp'
config_file = config_file.replace('\'{{{ TEMP }}}\'', repr(tempdir))
# write
open(CONFIG_FILE, 'w').write(config_file)
print >> sys.stderr, '''
==============================================================================
Welcome to Emscripten!
This is the first time any of the Emscripten tools has been run.
A settings file has been copied to %s, at absolute path: %s
It contains our best guesses for the important paths, which are:
LLVM_ROOT = %s
NODE_JS = %s
EMSCRIPTEN_ROOT = %s
Please edit the file if any of those are incorrect.
This command will now exit. When you are done editing those paths, re-run it.
==============================================================================
''' % (EM_CONFIG, CONFIG_FILE, llvm_root, node, __rootpath__)
sys.exit(0)
try:
config_text = open(CONFIG_FILE, 'r').read() if CONFIG_FILE else EM_CONFIG
exec(config_text)
except Exception, e:
logging.error('Error in evaluating %s (at %s): %s, text: %s' % (EM_CONFIG, CONFIG_FILE, str(e), config_text))
sys.exit(1)
def listify(x):
if type(x) is not list: return [x]
return x
def fix_js_engine(old, new):
global JS_ENGINES
JS_ENGINES = map(lambda x: new if x == old else x, JS_ENGINES)
return new
try:
SPIDERMONKEY_ENGINE = fix_js_engine(SPIDERMONKEY_ENGINE, listify(SPIDERMONKEY_ENGINE))
except:
pass
try:
NODE_JS = fix_js_engine(NODE_JS, listify(NODE_JS))
except:
pass
try:
V8_ENGINE = fix_js_engine(V8_ENGINE, listify(V8_ENGINE))
except:
pass
COMPILER_ENGINE = listify(COMPILER_ENGINE)
JS_ENGINES = [listify(ENGINE) for ENGINE in JS_ENGINES]
try:
EM_POPEN_WORKAROUND
except:
EM_POPEN_WORKAROUND = os.environ.get('EM_POPEN_WORKAROUND')
# Install our replacement Popen handler if we are running on Windows to avoid python spawn process function.
# nb. This is by default disabled since it has the adverse effect of buffering up all logging messages, which makes
# builds look unresponsive (messages are printed only after the whole build finishes). Whether this workaround is needed
# seems to depend on how the host application that invokes emcc has set up its stdout and stderr.
if EM_POPEN_WORKAROUND and os.name == 'nt':
logging.debug('Installing Popen workaround handler to avoid bug http://bugs.python.org/issue3905')
Popen = WindowsPopen
# Verbosity level control for any intermediate subprocess spawns from the compiler. Useful for internal debugging.
# 0: disabled.
# 1: Log stderr of subprocess spawns.
# 2: Log stdout and stderr of subprocess spawns. Print out subprocess commands that were executed.
# 3: Log stdout and stderr, and pass VERBOSE=1 to CMake configure steps.
EM_BUILD_VERBOSE_LEVEL = int(os.getenv('EM_BUILD_VERBOSE')) if os.getenv('EM_BUILD_VERBOSE') != None else 0
# Expectations
EXPECTED_LLVM_VERSION = (3, 7)
actual_clang_version = None
def get_clang_version():
global actual_clang_version
if actual_clang_version is None:
response = Popen([CLANG, '-v'], stderr=PIPE).communicate()[1]
m = re.search(r'[Vv]ersion\s+(\d+\.\d+)', response)
actual_clang_version = m and m.group(1)
return actual_clang_version
def check_clang_version():
expected = '.'.join(map(str, EXPECTED_LLVM_VERSION))
actual = get_clang_version()
if expected in actual:
return True
logging.warning('LLVM version appears incorrect (seeing "%s", expected "%s")' % (actual, expected))
return False
def check_llvm_version():
try:
check_clang_version()
except Exception, e:
logging.warning('Could not verify LLVM version: %s' % str(e))
# look for emscripten-version.txt files under or alongside the llvm source dir
def get_fastcomp_src_dir():
d = LLVM_ROOT
emroot = path_from_root() # already abspath
# look for version file in llvm repo, making sure not to mistake the emscripten repo for it
while d != os.path.dirname(d):
d = os.path.abspath(d)
# when the build directory lives below the source directory
if os.path.exists(os.path.join(d, 'emscripten-version.txt')) and not d == emroot:
return d
# when the build directory lives alongside the source directory
elif os.path.exists(os.path.join(d, 'src', 'emscripten-version.txt')) and not os.path.join(d, 'src') == emroot:
return os.path.join(d, 'src')
else:
d = os.path.dirname(d)
return None
def check_fastcomp():
try:
llc_version_info = Popen([LLVM_COMPILER, '--version'], stdout=PIPE).communicate()[0]
pre, targets = llc_version_info.split('Registered Targets:')
if 'js' not in targets or 'JavaScript (asm.js, emscripten) backend' not in targets:
logging.critical('fastcomp in use, but LLVM has not been built with the JavaScript backend as a target, llc reports:')
print >> sys.stderr, '==========================================================================='
print >> sys.stderr, llc_version_info,
print >> sys.stderr, '==========================================================================='
logging.critical('you can fall back to the older (pre-fastcomp) compiler core, although that is not recommended, see http://kripken.github.io/emscripten-site/docs/building_from_source/LLVM-Backend.html')
return False
d = get_fastcomp_src_dir()
if d is not None:
llvm_version = open(os.path.join(d, 'emscripten-version.txt')).read().strip()
if os.path.exists(os.path.join(d, 'tools', 'clang', 'emscripten-version.txt')):
clang_version = open(os.path.join(d, 'tools', 'clang', 'emscripten-version.txt')).read().strip()
elif os.path.exists(os.path.join(d, 'tools', 'clang')):
clang_version = '?' # Looks like the LLVM compiler tree has an old checkout from the time before it contained a version.txt: Should update!
else:
clang_version = llvm_version # This LLVM compiler tree does not have a tools/clang, so it's probably an out-of-source build directory. No need for separate versioning.
if EMSCRIPTEN_VERSION != llvm_version or EMSCRIPTEN_VERSION != clang_version:
logging.error('Emscripten, llvm and clang versions do not match, this is dangerous (%s, %s, %s)', EMSCRIPTEN_VERSION, llvm_version, clang_version)
logging.error('Make sure to use the same branch in each repo, and to be up-to-date on each. See http://kripken.github.io/emscripten-site/docs/building_from_source/LLVM-Backend.html')
else:
logging.warning('did not see a source tree above or next to the LLVM root directory (guessing based on directory of %s), could not verify version numbers match' % LLVM_COMPILER)
return True
except Exception, e:
logging.warning('could not check fastcomp: %s' % str(e))
return True
EXPECTED_NODE_VERSION = (0,8,0)
def check_node_version():
try:
actual = Popen(NODE_JS + ['--version'], stdout=PIPE).communicate()[0].strip()
version = tuple(map(int, actual.replace('v', '').replace('-pre', '').split('.')))
if version >= EXPECTED_NODE_VERSION:
return True
logging.warning('node version appears too old (seeing "%s", expected "%s")' % (actual, 'v' + ('.'.join(map(str, EXPECTED_NODE_VERSION)))))
return False
except Exception, e:
logging.warning('cannot check node version: %s', e)
return False
# Finds the system temp directory without resorting to using the one configured in .emscripten
def find_temp_directory():
if WINDOWS:
if os.getenv('TEMP') and os.path.isdir(os.getenv('TEMP')):
return os.getenv('TEMP')
elif os.getenv('TMP') and os.path.isdir(os.getenv('TMP')):
return os.getenv('TMP')
elif os.path.isdir('C:\\temp'):
return os.getenv('C:\\temp')
else:
return None # No luck!
else:
return '/tmp'
# Check that basic stuff we need (a JS engine to compile, Node.js, and Clang and LLVM)
# exists.
# The test runner always does this check (through |force|). emcc does this less frequently,
# only when ${EM_CONFIG}_sanity does not exist or is older than EM_CONFIG (so,
# we re-check sanity when the settings are changed)
# We also re-check sanity and clear the cache when the version changes
try:
EMSCRIPTEN_VERSION = open(path_from_root('emscripten-version.txt')).read().strip()
try:
parts = map(int, EMSCRIPTEN_VERSION.split('.'))
EMSCRIPTEN_VERSION_MAJOR = parts[0]
EMSCRIPTEN_VERSION_MINOR = parts[1]
EMSCRIPTEN_VERSION_TINY = parts[2]
except Exception, e:
logging.warning('emscripten version ' + EMSCRIPTEN_VERSION + ' lacks standard parts')
EMSCRIPTEN_VERSION_MAJOR = 0
EMSCRIPTEN_VERSION_MINOR = 0
EMSCRIPTEN_VERSION_TINY = 0
raise e
except Exception, e:
logging.error('cannot find emscripten version ' + str(e))
EMSCRIPTEN_VERSION = 'unknown'
def generate_sanity():
return EMSCRIPTEN_VERSION + '|' + get_llvm_target() + '|' + LLVM_ROOT + '|' + get_clang_version()
def check_sanity(force=False):
try:
if os.environ.get('EMCC_SKIP_SANITY_CHECK') == '1':
return
reason = None
if not CONFIG_FILE:
return # config stored directly in EM_CONFIG => skip sanity checks
else:
settings_mtime = os.stat(CONFIG_FILE).st_mtime
sanity_file = CONFIG_FILE + '_sanity'
if os.path.exists(sanity_file):
try:
sanity_mtime = os.stat(sanity_file).st_mtime
if sanity_mtime <= settings_mtime:
reason = 'settings file has changed'
else:
sanity_data = open(sanity_file).read()
if sanity_data != generate_sanity():
reason = 'system change: %s vs %s' % (generate_sanity(), sanity_data)
else:
if not force: return # all is well
except Exception, e:
reason = 'unknown: ' + str(e)
if reason:
logging.warning('(Emscripten: %s, clearing cache)' % reason)
Cache.erase()
force = False # the check actually failed, so definitely write out the sanity file, to avoid others later seeing failures too
# some warning, mostly not fatal checks - do them even if EM_IGNORE_SANITY is on
check_llvm_version()
check_node_version()
if os.environ.get('EMCC_FAST_COMPILER') == '0':
logging.critical('Non-fastcomp compiler is no longer available, please use fastcomp or an older version of emscripten')
sys.exit(1)
fastcomp_ok = check_fastcomp()
if os.environ.get('EM_IGNORE_SANITY'):
logging.info('EM_IGNORE_SANITY set, ignoring sanity checks')
return
logging.info('(Emscripten: Running sanity checks)')
if not check_engine(COMPILER_ENGINE):
logging.critical('The JavaScript shell used for compiling (%s) does not seem to work, check the paths in %s' % (COMPILER_ENGINE, EM_CONFIG))
sys.exit(1)
if NODE_JS != COMPILER_ENGINE:
if not check_engine(NODE_JS):
logging.critical('Node.js (%s) does not seem to work, check the paths in %s' % (NODE_JS, EM_CONFIG))
sys.exit(1)
for cmd in [CLANG, LINK_CMD[0], LLVM_AR, LLVM_OPT, LLVM_AS, LLVM_DIS, LLVM_NM, LLVM_INTERPRETER]:
if not os.path.exists(cmd) and not os.path.exists(cmd + '.exe'): # .exe extension required for Windows
logging.critical('Cannot find %s, check the paths in %s' % (cmd, EM_CONFIG))
sys.exit(1)
if not fastcomp_ok:
logging.critical('failing sanity checks due to previous fastcomp failure')
sys.exit(1)
try:
subprocess.call([JAVA, '-version'], stdout=PIPE, stderr=PIPE)
except:
logging.warning('java does not seem to exist, required for closure compiler, which is optional (define JAVA in ~/.emscripten if you want it)')
if not os.path.exists(CLOSURE_COMPILER):
logging.warning('Closure compiler (%s) does not exist, check the paths in %s. -O2 and above will fail' % (CLOSURE_COMPILER, EM_CONFIG))
# Sanity check passed!
if not force:
# Only create/update this file if the sanity check succeeded, i.e., we got here
f = open(sanity_file, 'w')
f.write(generate_sanity())
f.close()
except Exception, e:
# Any error here is not worth failing on
print 'WARNING: sanity check failed to run', e
# Tools/paths
try:
LLVM_ADD_VERSION
except NameError:
LLVM_ADD_VERSION = os.getenv('LLVM_ADD_VERSION')
try:
CLANG_ADD_VERSION
except NameError:
CLANG_ADD_VERSION = os.getenv('CLANG_ADD_VERSION')
USING_PNACL_TOOLCHAIN = os.path.exists(os.path.join(LLVM_ROOT, 'pnacl-clang'))
def modify_prefix(tool):
if USING_PNACL_TOOLCHAIN:
if tool.startswith('llvm-'):
tool = tool[5:]
tool = 'pnacl-' + tool
if WINDOWS:
tool += '.bat'
return tool
# Some distributions ship with multiple llvm versions so they add
# the version to the binaries, cope with that
def build_llvm_tool_path(tool):
tool = modify_prefix(tool)
if LLVM_ADD_VERSION:
return os.path.join(LLVM_ROOT, tool + "-" + LLVM_ADD_VERSION)
else:
return os.path.join(LLVM_ROOT, tool)
# Some distributions ship with multiple clang versions so they add
# the version to the binaries, cope with that
def build_clang_tool_path(tool):
tool = modify_prefix(tool)
if CLANG_ADD_VERSION:
return os.path.join(LLVM_ROOT, tool + "-" + CLANG_ADD_VERSION)
else:
return os.path.join(LLVM_ROOT, tool)
# Whenever building a native executable for OSX, we must provide the OSX SDK version we want to target.
def osx_find_native_sdk_path():
try:
sdk_root = '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs'
sdks = os.walk(sdk_root).next()[1]
sdk_path = os.path.join(sdk_root, sdks[0]) # Just pick first one found, we don't care which one we found.
logging.debug('Targeting OSX SDK found at ' + sdk_path)
return sdk_path
except:
logging.warning('Could not find native OSX SDK path to target!')
return None
# These extra args need to be passed to Clang when targeting a native host system executable
CACHED_CLANG_NATIVE_ARGS=None
def get_clang_native_args():
global CACHED_CLANG_NATIVE_ARGS
if CACHED_CLANG_NATIVE_ARGS is not None: return CACHED_CLANG_NATIVE_ARGS
CACHED_CLANG_NATIVE_ARGS = []
if sys.platform == 'darwin':
sdk_path = osx_find_native_sdk_path()
if sdk_path:
CACHED_CLANG_NATIVE_ARGS = ['-isysroot', osx_find_native_sdk_path()]
elif os.name == 'nt':
CACHED_CLANG_NATIVE_ARGS = ['-DWIN32']
# TODO: If Windows.h et al. are needed, will need to add something like '-isystemC:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Include'.
return CACHED_CLANG_NATIVE_ARGS
CLANG_CC=os.path.expanduser(build_clang_tool_path('clang'))
CLANG_CPP=os.path.expanduser(build_clang_tool_path('clang++'))
CLANG=CLANG_CPP
if USING_PNACL_TOOLCHAIN:
# The PNaCl toolchain doesn't have llvm-link, but we can fake it
LINK_CMD = [build_llvm_tool_path('llvm-ld'), '-nostdlib', '-r']
else:
LINK_CMD = [build_llvm_tool_path('llvm-link')]
LLVM_AR=build_llvm_tool_path('llvm-ar')
LLVM_OPT=os.path.expanduser(build_llvm_tool_path('opt'))
LLVM_AS=os.path.expanduser(build_llvm_tool_path('llvm-as'))
LLVM_DIS=os.path.expanduser(build_llvm_tool_path('llvm-dis'))
LLVM_NM=os.path.expanduser(build_llvm_tool_path('llvm-nm'))
LLVM_INTERPRETER=os.path.expanduser(build_llvm_tool_path('lli'))
LLVM_COMPILER=os.path.expanduser(build_llvm_tool_path('llc'))
EMSCRIPTEN = path_from_root('emscripten.py')
DEMANGLER = path_from_root('third_party', 'demangler.py')
NAMESPACER = path_from_root('tools', 'namespacer.py')
EMCC = path_from_root('emcc')
EMXX = path_from_root('em++')
EMAR = path_from_root('emar')
EMRANLIB = path_from_root('emranlib')
EMCONFIG = path_from_root('em-config')
EMLINK = path_from_root('emlink.py')
EMMAKEN = path_from_root('tools', 'emmaken.py')
AUTODEBUGGER = path_from_root('tools', 'autodebugger.py')
BINDINGS_GENERATOR = path_from_root('tools', 'bindings_generator.py')
EXEC_LLVM = path_from_root('tools', 'exec_llvm.py')
FILE_PACKAGER = path_from_root('tools', 'file_packager.py')
# Temp dir. Create a random one, unless EMCC_DEBUG is set, in which case use TEMP_DIR/emscripten_temp
def safe_ensure_dirs(dirname):
try:
os.makedirs(dirname)
except os.error, e:
# Ignore error for already existing dirname
if e.errno != errno.EEXIST:
raise e
# FIXME: Notice that this will result in a false positive,
# should the dirname be a file! There seems to no way to
# handle this atomically in Python 2.x.
# There is an additional option for Python 3.x, though.
# Returns a path to EMSCRIPTEN_TEMP_DIR, creating one if it didn't exist.
def get_emscripten_temp_dir():
global configuration, EMSCRIPTEN_TEMP_DIR
if not EMSCRIPTEN_TEMP_DIR:
EMSCRIPTEN_TEMP_DIR = tempfile.mkdtemp(prefix='emscripten_temp_', dir=configuration.TEMP_DIR)
def prepare_to_clean_temp(d):
def clean_temp():
try_delete(d)
atexit.register(clean_temp)
prepare_to_clean_temp(EMSCRIPTEN_TEMP_DIR) # this global var might change later
return EMSCRIPTEN_TEMP_DIR
class Configuration:
def __init__(self, environ=os.environ):
self.DEBUG = environ.get('EMCC_DEBUG')
if self.DEBUG == "0":
self.DEBUG = None
self.DEBUG_CACHE = self.DEBUG and "cache" in self.DEBUG
self.EMSCRIPTEN_TEMP_DIR = None
try:
self.TEMP_DIR = TEMP_DIR
except NameError:
self.TEMP_DIR = find_temp_directory()
if self.TEMP_DIR == None:
logging.critical('TEMP_DIR not defined in ' + os.path.expanduser('~\\.emscripten') + ", and could not detect a suitable directory! Please configure .emscripten to contain a variable TEMP_DIR='/path/to/temp/dir'.")
logging.debug('TEMP_DIR not defined in ~/.emscripten, using ' + self.TEMP_DIR)
if not os.path.isdir(self.TEMP_DIR):
logging.critical("The temp directory TEMP_DIR='" + self.TEMP_DIR + "' doesn't seem to exist! Please make sure that the path is correct.")
self.CANONICAL_TEMP_DIR = os.path.join(self.TEMP_DIR, 'emscripten_temp')
if self.DEBUG:
try:
self.EMSCRIPTEN_TEMP_DIR = self.CANONICAL_TEMP_DIR
safe_ensure_dirs(self.EMSCRIPTEN_TEMP_DIR)
except Exception, e:
logging.error(str(e) + 'Could not create canonical temp dir. Check definition of TEMP_DIR in ~/.emscripten')
def get_temp_files(self):
return tempfiles.TempFiles(
tmp=self.TEMP_DIR if not self.DEBUG else get_emscripten_temp_dir(),
save_debug_files=os.environ.get('EMCC_DEBUG_SAVE'))
def apply_configuration():
global configuration, DEBUG, EMSCRIPTEN_TEMP_DIR, DEBUG_CACHE, CANONICAL_TEMP_DIR, TEMP_DIR
configuration = Configuration()
DEBUG = configuration.DEBUG
EMSCRIPTEN_TEMP_DIR = configuration.EMSCRIPTEN_TEMP_DIR
DEBUG_CACHE = configuration.DEBUG_CACHE
CANONICAL_TEMP_DIR = configuration.CANONICAL_TEMP_DIR
TEMP_DIR = configuration.TEMP_DIR
apply_configuration()
logging.basicConfig(format='%(levelname)-8s %(name)s: %(message)s') # can add %(asctime)s to see timestamps
def set_logging():
logger = logging.getLogger()
logger.setLevel(logging.DEBUG if os.environ.get('EMCC_DEBUG') else logging.INFO)
set_logging()
# EM_CONFIG stuff
try:
JS_ENGINES
except:
try:
JS_ENGINES = [JS_ENGINE]
except Exception, e:
print 'ERROR: %s does not seem to have JS_ENGINES or JS_ENGINE set up' % EM_CONFIG
raise
try:
CLOSURE_COMPILER
except:
CLOSURE_COMPILER = path_from_root('third_party', 'closure-compiler', 'compiler.jar')
try:
PYTHON
except:
logging.debug('PYTHON not defined in ~/.emscripten, using "%s"' % (sys.executable,))
PYTHON = sys.executable
try:
JAVA
except:
logging.debug('JAVA not defined in ~/.emscripten, using "java"')
JAVA = 'java'
# Additional compiler options
# Target choice. Must be synced with src/settings.js (TARGET_*)
def get_llvm_target():
return 'asmjs-unknown-emscripten'
LLVM_TARGET = get_llvm_target()
# COMPILER_OPTS: options passed to clang when generating bitcode for us
try:
COMPILER_OPTS # Can be set in EM_CONFIG, optionally
except:
COMPILER_OPTS = []
COMPILER_OPTS = COMPILER_OPTS + [#'-fno-threadsafe-statics', # disabled due to issue 1289
'-target', LLVM_TARGET,
'-D__EMSCRIPTEN_major__=' + str(EMSCRIPTEN_VERSION_MAJOR),
'-D__EMSCRIPTEN_minor__=' + str(EMSCRIPTEN_VERSION_MINOR),
'-D__EMSCRIPTEN_tiny__=' + str(EMSCRIPTEN_VERSION_TINY)]
# Changes to default clang behavior
if LLVM_TARGET == 'asmjs-unknown-emscripten':
# Implicit functions can cause horribly confusing asm.js function pointer type errors, see #2175
# If your codebase really needs them - very unrecommended! - you can disable the error with
# -Wno-error=implicit-function-declaration
# or disable even a warning about it with
# -Wno-implicit-function-declaration
COMPILER_OPTS += ['-Werror=implicit-function-declaration']
USE_EMSDK = not os.environ.get('EMMAKEN_NO_SDK')
if USE_EMSDK:
# Disable system C and C++ include directories, and add our own (using -idirafter so they are last, like system dirs, which
# allows projects to override them)
C_INCLUDE_PATHS = [path_from_root('system', 'local', 'include'),
path_from_root('system', 'include', 'compat'),
path_from_root('system', 'include'),
path_from_root('system', 'include', 'emscripten'),
path_from_root('system', 'include', 'libc'),
path_from_root('system', 'lib', 'libc', 'musl', 'arch', 'js'),
]
CXX_INCLUDE_PATHS = [path_from_root('system', 'include', 'libcxx')
]
C_OPTS = ['-nostdinc', '-Xclang', '-nobuiltininc', '-Xclang', '-nostdsysteminc',
]
def include_directive(paths):
result = []
for path in paths:
result += ['-Xclang', '-isystem' + path]
return result
EMSDK_OPTS = C_OPTS + include_directive(C_INCLUDE_PATHS) + include_directive(CXX_INCLUDE_PATHS)
EMSDK_CXX_OPTS = []
COMPILER_OPTS += EMSDK_OPTS
else:
EMSDK_OPTS = []
EMSDK_CXX_OPTS = []
#print >> sys.stderr, 'SDK opts', ' '.join(EMSDK_OPTS)
#print >> sys.stderr, 'Compiler opts', ' '.join(COMPILER_OPTS)
# Engine tweaks
try:
if SPIDERMONKEY_ENGINE:
new_spidermonkey = SPIDERMONKEY_ENGINE
if '-w' not in str(new_spidermonkey):
new_spidermonkey += ['-w']
SPIDERMONKEY_ENGINE = fix_js_engine(SPIDERMONKEY_ENGINE, new_spidermonkey)
except NameError:
pass
# If we have 'env', we should use that to find python, because |python| may fail while |env python| may work
# (For example, if system python is 3.x while we need 2.x, and env gives 2.x if told to do so.)
ENV_PREFIX = []
if not WINDOWS:
try:
assert 'Python' in Popen(['env', 'python', '-V'], stdout=PIPE, stderr=STDOUT).communicate()[0]
ENV_PREFIX = ['env']
except:
pass
# Utilities
def check_engine(engine):
# TODO: we call this several times, perhaps cache the results?
try:
if not CONFIG_FILE:
return True # config stored directly in EM_CONFIG => skip engine check
return 'hello, world!' in run_js(path_from_root('src', 'hello_world.js'), engine)
except Exception, e:
print 'Checking JS engine %s failed. Check %s. Details: %s' % (str(engine), EM_CONFIG, str(e))
return False
def make_js_command(filename, engine=None, *args):
if engine is None:
engine = JS_ENGINES[0]
return jsrun.make_command(filename, engine, *args)
def run_js(filename, engine=None, *args, **kw):
if engine is None:
engine = JS_ENGINES[0]
return jsrun.run_js(filename, engine, *args, **kw)
def to_cc(cxx):
# By default, LLVM_GCC and CLANG are really the C++ versions. This gets an explicit C version
return cxx.replace('clang++', 'clang').replace('g++', 'gcc')
def line_splitter(data):
"""Silly little tool to split JSON arrays over many lines."""
out = ''
counter = 0
for i in range(len(data)):
out += data[i]
if data[i] == ' ' and counter > 60:
out += '\n'
counter = 0
else:
counter += 1
return out
def limit_size(string, MAX=800*20):
if len(string) < MAX: return string
return string[0:MAX/2] + '\n[..]\n' + string[-MAX/2:]
def read_pgo_data(filename):
'''
Reads the output of PGO and generates proper information for CORRECT_* == 2 's *_LINES options
'''
signs_lines = []
overflows_lines = []
for line in open(filename, 'r'):
try:
if line.rstrip() == '': continue
if '%0 failures' in line: continue
left, right = line.split(' : ')
signature = left.split('|')[1]
if 'Sign' in left:
signs_lines.append(signature)
elif 'Overflow' in left:
overflows_lines.append(signature)
except:
pass
return {
'signs_lines': signs_lines,
'overflows_lines': overflows_lines
}
def unique_ordered(values): # return a list of unique values in an input list, without changing order (list(set(.)) would change order randomly)
seen = set()
def check(value):
if value in seen: return False
seen.add(value)
return True
return filter(check, values)
def expand_response(data):
if type(data) == str and data[0] == '@':
return json.loads(open(data[1:]).read())
return data
# Settings. A global singleton. Not pretty, but nicer than passing |, settings| everywhere
class Settings2(type):
class __impl:
attrs = {}
def __init__(self):
self.reset()
@classmethod
def reset(self):
self.attrs = { 'QUANTUM_SIZE': 4 }
self.load()
# Given some emcc-type args (-O3, -s X=Y, etc.), fill Settings with the right settings
@classmethod
def load(self, args=[]):
# Load the JS defaults into python
settings = open(path_from_root('src', 'settings.js')).read().replace('//', '#')
settings = re.sub(r'var ([\w\d]+)', r'self.attrs["\1"]', settings)
exec settings
# Apply additional settings. First -O, then -s
for i in range(len(args)):
if args[i].startswith('-O'):
v = args[i][2]
if v in ['s', 'z']: v = '2'
level = eval(v)
self.apply_opt_level(level)
for i in range(len(args)):
if args[i] == '-s':
declare = re.sub(r'([\w\d]+)\s*=\s*(.+)', r'self.attrs["\1"]=\2;', args[i+1])
exec declare
# Transforms the Settings information into emcc-compatible args (-s X=Y, etc.). Basically
# the reverse of load_settings, except for -Ox which is relevant there but not here
@classmethod
def serialize(self):
ret = []
for key, value in self.attrs.iteritems():
if key == key.upper(): # this is a hack. all of our settings are ALL_CAPS, python internals are not
jsoned = json.dumps(value, sort_keys=True)
ret += ['-s', key + '=' + jsoned]
return ret
@classmethod
def copy(self, values):
self.attrs = values
@classmethod
def apply_opt_level(self, opt_level, noisy=False):
if opt_level >= 1:
self.attrs['ASM_JS'] = 1
self.attrs['ASSERTIONS'] = 0
self.attrs['DISABLE_EXCEPTION_CATCHING'] = 1
self.attrs['ALIASING_FUNCTION_POINTERS'] = 1
def __getattr__(self, attr):
if attr in self.attrs:
return self.attrs[attr]
else:
raise AttributeError
def __setattr__(self, attr, value):
if not attr in self.attrs:
import difflib
logging.warning('''Assigning a non-existent settings attribute "%s"''' % attr)
suggestions = ', '.join(difflib.get_close_matches(attr, self.attrs.keys()))
if suggestions:
logging.warning(''' - did you mean one of %s?''' % suggestions)
logging.warning(''' - perhaps a typo in emcc's -s X=Y notation?''')
logging.warning(''' - (see src/settings.js for valid values)''')
self.attrs[attr] = value
__instance = None
@staticmethod
def instance():
if Settings2.__instance is None:
Settings2.__instance = Settings2.__impl()
return Settings2.__instance
def __getattr__(self, attr):
return getattr(self.instance(), attr)
def __setattr__(self, attr, value):
return setattr(self.instance(), attr, value)
class Settings(object):
__metaclass__ = Settings2
# Building
class Building:
COMPILER = CLANG
LLVM_OPTS = False
COMPILER_TEST_OPTS = [] # For use of the test runner
JS_ENGINE_OVERRIDE = None # Used to pass the JS engine override from runner.py -> test_benchmark.py
@staticmethod
def get_building_env(native=False):
env = os.environ.copy()
if native:
env['CC'] = CLANG_CC
env['CXX'] = CLANG_CPP
env['LD'] = CLANG
env['CFLAGS'] = '-O2 -fno-math-errno'
return env
env['CC'] = EMCC if not WINDOWS else 'python %r' % EMCC
env['CXX'] = EMXX if not WINDOWS else 'python %r' % EMXX
env['AR'] = EMAR if not WINDOWS else 'python %r' % EMAR