-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathbuilding.py
1550 lines (1322 loc) · 60 KB
/
building.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2020 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 .toolchain_profiler import ToolchainProfiler
import json
import logging
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from subprocess import PIPE
from . import diagnostics
from . import response_file
from . import shared
from . import webassembly
from . import config
from . import utils
from .shared import CLANG_CC, CLANG_CXX, PYTHON
from .shared import LLVM_NM, EMCC, EMAR, EMXX, EMRANLIB, WASM_LD, LLVM_AR
from .shared import LLVM_LINK, LLVM_OBJCOPY
from .shared import try_delete, run_process, check_call, exit_with_error
from .shared import path_from_root
from .shared import asmjs_mangle, DEBUG
from .shared import TEMP_DIR
from .shared import CANONICAL_TEMP_DIR, LLVM_DWARFDUMP, demangle_c_symbol_name
from .shared import get_emscripten_temp_dir, exe_suffix, is_c_symbol
from .utils import WINDOWS
from .settings import settings
logger = logging.getLogger('building')
# Building
binaryen_checked = False
EXPECTED_BINARYEN_VERSION = 106
# cache results of nm - it can be slow to run
nm_cache = {}
_is_ar_cache = {}
# the exports the user requested
user_requested_exports = set()
# llvm-ar appears to just use basenames inside archives. as a result, files
# with the same basename will trample each other when we extract them. to help
# warn of such situations, we warn if there are duplicate entries in the
# archive
def warn_if_duplicate_entries(archive_contents, archive_filename):
if len(archive_contents) != len(set(archive_contents)):
msg = '%s: archive file contains duplicate entries. This is not supported by emscripten. Only the last member with a given name will be linked in which can result in undefined symbols. You should either rename your source files, or use `emar` to create you archives which works around this issue.' % archive_filename
warned = set()
for i in range(len(archive_contents)):
curr = archive_contents[i]
if curr not in warned and curr in archive_contents[i + 1:]:
msg += '\n duplicate: %s' % curr
warned.add(curr)
diagnostics.warning('emcc', msg)
# Extracts the given list of archive files and outputs their contents
def extract_archive_contents(archive_files):
archive_results = shared.run_multiple_processes([[LLVM_AR, 't', a] for a in archive_files], pipe_stdout=True)
unpack_temp_dir = tempfile.mkdtemp('_archive_contents', 'emscripten_temp_')
def clean_at_exit():
try_delete(unpack_temp_dir)
shared.atexit.register(clean_at_exit)
archive_contents = []
for i in range(len(archive_results)):
a = archive_results[i]
contents = [l for l in a.splitlines() if len(l)]
if len(contents) == 0:
logger.debug('Archive %s appears to be empty (recommendation: link an .so instead of .a)' % a)
# `ar` files can only contains filenames. Just to be sure, verify that each
# file has only as filename component and is not absolute
for f in contents:
assert not os.path.dirname(f)
assert not os.path.isabs(f)
warn_if_duplicate_entries(contents, a)
archive_contents += [{
'archive_name': archive_files[i],
'o_files': [os.path.join(unpack_temp_dir, c) for c in contents]
}]
shared.run_multiple_processes([[LLVM_AR, 'xo', a] for a in archive_files], cwd=unpack_temp_dir)
# check that all files were created
for a in archive_contents:
missing_contents = [x for x in a['o_files'] if not os.path.exists(x)]
if missing_contents:
exit_with_error(f'llvm-ar failed to extract file(s) {missing_contents} from archive file {f}!')
return archive_contents
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 [v for v in values if check(v)]
# .. but for Popen, we cannot have doublequotes, so provide functionality to
# remove them when needed.
def remove_quotes(arg):
if isinstance(arg, list):
return [remove_quotes(a) for a in arg]
if arg.startswith('"') and arg.endswith('"'):
return arg[1:-1].replace('\\"', '"')
elif arg.startswith("'") and arg.endswith("'"):
return arg[1:-1].replace("\\'", "'")
else:
return arg
def get_building_env():
env = os.environ.copy()
# point CC etc. to the em* tools.
env['CC'] = EMCC
env['CXX'] = EMXX
env['AR'] = EMAR
env['LD'] = EMCC
env['NM'] = LLVM_NM
env['LDSHARED'] = EMCC
env['RANLIB'] = EMRANLIB
env['EMSCRIPTEN_TOOLS'] = path_from_root('tools')
env['HOST_CC'] = CLANG_CC
env['HOST_CXX'] = CLANG_CXX
env['HOST_CFLAGS'] = '-W' # if set to nothing, CFLAGS is used, which we don't want
env['HOST_CXXFLAGS'] = '-W' # if set to nothing, CXXFLAGS is used, which we don't want
env['PKG_CONFIG_LIBDIR'] = shared.Cache.get_sysroot_dir('local', 'lib', 'pkgconfig') + os.path.pathsep + shared.Cache.get_sysroot_dir('lib', 'pkgconfig')
env['PKG_CONFIG_PATH'] = os.environ.get('EM_PKG_CONFIG_PATH', '')
env['EMSCRIPTEN'] = path_from_root()
env['PATH'] = shared.Cache.get_sysroot_dir('bin') + os.pathsep + env['PATH']
env['CROSS_COMPILE'] = path_from_root('em') # produces /path/to/emscripten/em , which then can have 'cc', 'ar', etc appended to it
return env
def make_paths_absolute(f):
if f.startswith('-'): # skip flags
return f
else:
return os.path.abspath(f)
# Runs llvm-nm for the given list of files.
# The results are populated in nm_cache, and also returned as an array with order corresponding with the input files.
# If a given file cannot be processed, None will be present in its place.
@ToolchainProfiler.profile()
def llvm_nm_multiple(files):
if len(files) == 0:
return []
# Run llvm-nm on files that we haven't cached yet
cmd = [LLVM_NM, '--print-file-name'] + [f for f in files if f not in nm_cache]
cmd = get_command_with_possible_response_file(cmd)
results = run_process(cmd, stdout=PIPE, stderr=PIPE, check=False)
# If one or more of the input files cannot be processed, llvm-nm will return a non-zero error code, but it will still process and print
# out all the other files in order. So even if process return code is non zero, we should always look at what we got to stdout.
if results.returncode != 0:
logger.debug(f'Subcommand {" ".join(cmd)} failed with return code {results.returncode}! (An input file was corrupt?)')
for key, value in parse_llvm_nm_symbols(results.stdout).items():
nm_cache[key] = value
return [nm_cache[f] if f in nm_cache else {'defs': set(), 'undefs': set(), 'parse_error': True} for f in files]
def llvm_nm(file):
return llvm_nm_multiple([file])[0]
@ToolchainProfiler.profile()
def read_link_inputs(files):
# Before performing the link, we need to look at each input file to determine which symbols
# each of them provides. Do this in multiple parallel processes.
archive_names = [] # .a files passed in to the command line to the link
object_names = [] # .o/.bc files passed in to the command line to the link
# Stores the object files contained in different archive files passed as input
ar_contents = {}
for f in files:
absolute_path_f = make_paths_absolute(f)
if absolute_path_f not in ar_contents and is_ar(absolute_path_f):
archive_names.append(absolute_path_f)
elif absolute_path_f not in nm_cache and is_bitcode(absolute_path_f):
object_names.append(absolute_path_f)
# Archives contain objects, so process all archives first in parallel to obtain the object files in them.
archive_contents = extract_archive_contents(archive_names)
for a in archive_contents:
ar_contents[os.path.abspath(a['archive_name'])] = a['o_files']
for o in a['o_files']:
if o not in nm_cache:
object_names.append(o)
# Next, extract symbols from all object files (either standalone or inside archives we just extracted)
# The results are not used here directly, but populated to llvm-nm cache structure.
llvm_nm_multiple(object_names)
return ar_contents
def llvm_backend_args():
# disable slow and relatively unimportant optimization passes
args = ['-combiner-global-alias-analysis=false']
# asm.js-style exception handling
if not settings.DISABLE_EXCEPTION_CATCHING:
args += ['-enable-emscripten-cxx-exceptions']
if settings.EXCEPTION_CATCHING_ALLOWED:
# When 'main' has a non-standard signature, LLVM outlines its content out to
# '__original_main'. So we add it to the allowed list as well.
if 'main' in settings.EXCEPTION_CATCHING_ALLOWED:
settings.EXCEPTION_CATCHING_ALLOWED += ['__original_main']
allowed = ','.join(settings.EXCEPTION_CATCHING_ALLOWED)
args += ['-emscripten-cxx-exceptions-allowed=' + allowed]
# asm.js-style setjmp/longjmp handling
if settings.SUPPORT_LONGJMP == 'emscripten':
args += ['-enable-emscripten-sjlj']
# setjmp/longjmp handling using Wasm EH
elif settings.SUPPORT_LONGJMP == 'wasm':
args += ['-wasm-enable-sjlj']
# better (smaller, sometimes faster) codegen, see binaryen#1054
# and https://bugs.llvm.org/show_bug.cgi?id=39488
args += ['-disable-lsr']
return args
@ToolchainProfiler.profile()
def link_to_object(args, target):
# link using lld unless LTO is requested (lld can't output LTO/bitcode object files).
if not settings.LTO:
link_lld(args + ['--relocatable'], target)
else:
link_bitcode(args, target)
def link_llvm(linker_inputs, target):
# runs llvm-link to link things.
cmd = [LLVM_LINK] + linker_inputs + ['-o', target]
cmd = get_command_with_possible_response_file(cmd)
check_call(cmd)
def lld_flags_for_executable(external_symbols):
cmd = []
if external_symbols:
undefs = shared.get_temp_files().get('.undefined').name
utils.write_file(undefs, '\n'.join(external_symbols))
cmd.append('--allow-undefined-file=%s' % undefs)
else:
cmd.append('--import-undefined')
if settings.IMPORTED_MEMORY:
cmd.append('--import-memory')
if settings.SHARED_MEMORY:
cmd.append('--shared-memory')
if settings.MEMORY64:
cmd.append('-mwasm64')
# wasm-ld can strip debug info for us. this strips both the Names
# section and DWARF, so we can only use it when we don't need any of
# those things.
if settings.DEBUG_LEVEL < 2 and (not settings.EMIT_SYMBOL_MAP and
not settings.EMIT_NAME_SECTION and
not settings.ASYNCIFY):
cmd.append('--strip-debug')
if settings.LINKABLE:
cmd.append('--export-dynamic')
cmd.append('--no-gc-sections')
c_exports = [e for e in settings.EXPORTED_FUNCTIONS if is_c_symbol(e)]
# Strip the leading underscores
c_exports = [demangle_c_symbol_name(e) for e in c_exports]
c_exports += settings.EXPORT_IF_DEFINED
if external_symbols:
# Filter out symbols external/JS symbols
c_exports = [e for e in c_exports if e not in external_symbols]
for export in c_exports:
cmd.append('--export-if-defined=' + export)
for export in settings.REQUIRED_EXPORTS:
if settings.ERROR_ON_UNDEFINED_SYMBOLS:
cmd.append('--export=' + export)
else:
cmd.append('--export-if-defined=' + export)
if settings.RELOCATABLE:
cmd.append('--experimental-pic')
if settings.SIDE_MODULE:
cmd.append('-shared')
else:
cmd.append('-pie')
if not settings.LINKABLE:
cmd.append('--no-export-dynamic')
else:
cmd.append('--export-table')
if settings.ALLOW_TABLE_GROWTH:
cmd.append('--growable-table')
if not settings.SIDE_MODULE:
# Export these two section start symbols so that we can extact the string
# data that they contain.
cmd += [
'-z', 'stack-size=%s' % settings.TOTAL_STACK,
'--initial-memory=%d' % settings.INITIAL_MEMORY,
]
if settings.STANDALONE_WASM:
# when settings.EXPECT_MAIN is set we fall back to wasm-ld default of _start
if not settings.EXPECT_MAIN:
cmd += ['--entry=_initialize']
else:
if settings.EXPECT_MAIN and not settings.IGNORE_MISSING_MAIN:
cmd += ['--entry=main']
else:
cmd += ['--no-entry']
if not settings.ALLOW_MEMORY_GROWTH:
cmd.append('--max-memory=%d' % settings.INITIAL_MEMORY)
elif settings.MAXIMUM_MEMORY != -1:
cmd.append('--max-memory=%d' % settings.MAXIMUM_MEMORY)
if not settings.RELOCATABLE:
cmd.append('--global-base=%s' % settings.GLOBAL_BASE)
return cmd
def link_lld(args, target, external_symbols=None):
if not os.path.exists(WASM_LD):
exit_with_error('linker binary not found in LLVM directory: %s', WASM_LD)
# runs lld to link things.
# lld doesn't currently support --start-group/--end-group since the
# semantics are more like the windows linker where there is no need for
# grouping.
args = [a for a in args if a not in ('--start-group', '--end-group')]
# Emscripten currently expects linkable output (SIDE_MODULE/MAIN_MODULE) to
# include all archive contents.
if settings.LINKABLE:
args.insert(0, '--whole-archive')
args.append('--no-whole-archive')
if settings.STRICT:
args.append('--fatal-warnings')
cmd = [WASM_LD, '-o', target] + args
for a in llvm_backend_args():
cmd += ['-mllvm', a]
if settings.EXCEPTION_HANDLING:
cmd += ['-mllvm', '-wasm-enable-eh']
if settings.EXCEPTION_HANDLING or settings.SUPPORT_LONGJMP == 'wasm':
cmd += ['-mllvm', '-exception-model=wasm']
# For relocatable output (generating an object file) we don't pass any of the
# normal linker flags that are used when building and exectuable
if '--relocatable' not in args and '-r' not in args:
cmd += lld_flags_for_executable(external_symbols)
cmd = get_command_with_possible_response_file(cmd)
check_call(cmd)
def link_bitcode(args, target, force_archive_contents=False):
diagnostics.warning('deprecated', 'bitcode linking with llvm-link is deprecated. Please use emar archives instead. See https://github.com/emscripten-core/emscripten/issues/13492')
# "Full-featured" linking: looks into archives (duplicates lld functionality)
input_files = [a for a in args if not a.startswith('-')]
files_to_link = []
# Tracking unresolveds is necessary for .a linking, see below.
# Specify all possible entry points to seed the linking process.
# For a simple application, this would just be "main".
unresolved_symbols = {func[1:] for func in settings.EXPORTED_FUNCTIONS}
resolved_symbols = set()
# Paths of already included object files from archives.
added_contents = set()
has_ar = any(is_ar(make_paths_absolute(f)) for f in input_files)
# If we have only one archive or the force_archive_contents flag is set,
# then we will add every object file we see, regardless of whether it
# resolves any undefined symbols.
force_add_all = len(input_files) == 1 or force_archive_contents
# Considers an object file for inclusion in the link. The object is included
# if force_add=True or if the object provides a currently undefined symbol.
# If the object is included, the symbol tables are updated and the function
# returns True.
def consider_object(f, force_add=False):
new_symbols = llvm_nm(f)
# Check if the object was valid according to llvm-nm. It also accepts
# native object files.
if new_symbols['parse_error']:
diagnostics.warning('emcc', 'object %s is not valid according to llvm-nm, cannot link', f)
return False
# Check the object is valid for us, and not a native object file.
if not is_bitcode(f):
exit_with_error('unknown file type: %s', f)
provided = new_symbols['defs'].union(new_symbols['commons'])
do_add = force_add or not unresolved_symbols.isdisjoint(provided)
if do_add:
logger.debug('adding object %s to link (forced: %d)' % (f, force_add))
# Update resolved_symbols table with newly resolved symbols
resolved_symbols.update(provided)
# Update unresolved_symbols table by adding newly unresolved symbols and
# removing newly resolved symbols.
unresolved_symbols.update(new_symbols['undefs'].difference(resolved_symbols))
unresolved_symbols.difference_update(provided)
files_to_link.append(f)
return do_add
ar_contents = read_link_inputs(input_files)
# Traverse a single archive. The object files are repeatedly scanned for
# newly satisfied symbols until no new symbols are found. Returns true if
# any object files were added to the link.
def consider_archive(f, force_add):
added_any_objects = False
loop_again = True
logger.debug('considering archive %s' % (f))
contents = ar_contents[f]
while loop_again: # repeatedly traverse until we have everything we need
loop_again = False
for content in contents:
if content in added_contents:
continue
# Link in the .o if it provides symbols, *or* this is a singleton archive (which is
# apparently an exception in gcc ld)
if consider_object(content, force_add=force_add):
added_contents.add(content)
loop_again = True
added_any_objects = True
logger.debug('done running loop of archive %s' % (f))
return added_any_objects
# Rescan a group of archives until we don't find any more objects to link.
def scan_archive_group(group):
loop_again = True
logger.debug('starting archive group loop')
while loop_again:
loop_again = False
for archive in group:
if consider_archive(archive, force_add=False):
loop_again = True
logger.debug('done with archive group loop')
current_archive_group = None
in_whole_archive = False
for a in args:
if a.startswith('-'):
if a in ['--start-group', '-(']:
assert current_archive_group is None, 'Nested --start-group, missing --end-group?'
current_archive_group = []
elif a in ['--end-group', '-)']:
assert current_archive_group is not None, '--end-group without --start-group'
scan_archive_group(current_archive_group)
current_archive_group = None
elif a in ['--whole-archive', '-whole-archive']:
in_whole_archive = True
elif a in ['--no-whole-archive', '-no-whole-archive']:
in_whole_archive = False
else:
# Command line flags should already be vetted by the time this method
# is called, so this is an internal error
exit_with_error('unsupported link flag: %s', a)
else:
lib_path = make_paths_absolute(a)
if is_ar(lib_path):
# Extract object files from ar archives, and link according to gnu ld semantics
# (link in an entire .o from the archive if it supplies symbols still unresolved)
consider_archive(lib_path, in_whole_archive or force_add_all)
# If we're inside a --start-group/--end-group section, add to the list
# so we can loop back around later.
if current_archive_group is not None:
current_archive_group.append(lib_path)
elif is_bitcode(lib_path):
if has_ar:
consider_object(a, force_add=True)
else:
# If there are no archives then we can simply link all valid object
# files and skip the symbol table stuff.
files_to_link.append(a)
else:
exit_with_error('unknown file type: %s', a)
# We have to consider the possibility that --start-group was used without a matching
# --end-group; GNU ld permits this behavior and implicitly treats the end of the
# command line as having an --end-group.
if current_archive_group:
logger.debug('--start-group without matching --end-group, rescanning')
scan_archive_group(current_archive_group)
current_archive_group = None
try_delete(target)
# Finish link
# tolerate people trying to link a.so a.so etc.
files_to_link = unique_ordered(files_to_link)
logger.debug('emcc: linking: %s to %s', files_to_link, target)
link_llvm(files_to_link, target)
def get_command_with_possible_response_file(cmd):
# One of None, 0 or 1. (None: do default decision, 0: force disable, 1: force enable)
force_response_files = os.getenv('EM_FORCE_RESPONSE_FILES')
# 8k is a bit of an arbitrary limit, but a reasonable one
# for max command line size before we use a response file
if (len(shared.shlex_join(cmd)) <= 8192 and force_response_files != '1') or force_response_files == '0':
return cmd
logger.debug('using response file for %s' % cmd[0])
filename = response_file.create_response_file(cmd[1:], TEMP_DIR)
new_cmd = [cmd[0], "@" + filename]
return new_cmd
# Parses the output of llnm-nm and returns a dictionary of symbols for each file in the output.
# This function can be called either for a single file output listing ("llvm-nm a.o", or for
# multiple files listing ("llvm-nm a.o b.o").
def parse_llvm_nm_symbols(output):
# If response files are used in a call to llvm-nm, the output printed by llvm-nm has a
# quirk that it will contain double backslashes as directory separators on Windows. (it will
# not remove the escape characters when printing)
# Therefore canonicalize the output to single backslashes.
output = output.replace('\\\\', '\\')
# a dictionary from 'filename' -> { 'defs': set(), 'undefs': set(), 'commons': set() }
symbols = {}
for line in output.split('\n'):
# Line format: "[archive filename:]object filename: address status name"
entry_pos = line.rfind(':')
if entry_pos < 0:
continue
filename_pos = line.rfind(':', 0, entry_pos)
# Disambiguate between
# C:\bar.o: T main
# and
# /foo.a:bar.o: T main
# (both of these have same number of ':'s, but in the first, the file name on disk is "C:\bar.o", in second, it is "/foo.a")
if filename_pos < 0 or line[filename_pos + 1] in '/\\':
filename_pos = entry_pos
filename = line[:filename_pos]
status = line[entry_pos + 11] # Skip address, which is always fixed-length 8 chars.
symbol = line[entry_pos + 13:]
if filename not in symbols:
record = symbols.setdefault(filename, {
'defs': set(),
'undefs': set(),
'commons': set(),
'parse_error': False
})
if status == 'U':
record['undefs'] |= {symbol}
elif status == 'C':
record['commons'] |= {symbol}
elif status == status.upper():
record['defs'] |= {symbol}
return symbols
def emar(action, output_filename, filenames, stdout=None, stderr=None, env=None):
try_delete(output_filename)
cmd = [EMAR, action, output_filename] + filenames
cmd = get_command_with_possible_response_file(cmd)
run_process(cmd, stdout=stdout, stderr=stderr, env=env)
if 'c' in action:
assert os.path.exists(output_filename), 'emar could not create output file: ' + output_filename
def opt_level_to_str(opt_level, shrink_level=0):
# convert opt_level/shrink_level pair to a string argument like -O1
if opt_level == 0:
return '-O0'
if shrink_level == 1:
return '-Os'
elif shrink_level >= 2:
return '-Oz'
else:
return f'-O{min(opt_level, 3)}'
def js_optimizer(filename, passes):
from . import js_optimizer
try:
return js_optimizer.run(filename, passes)
except subprocess.CalledProcessError as e:
exit_with_error("'%s' failed (%d)", ' '.join(e.cmd), e.returncode)
# run JS optimizer on some JS, ignoring asm.js contents if any - just run on it all
def acorn_optimizer(filename, passes, extra_info=None, return_output=False):
optimizer = path_from_root('tools/acorn-optimizer.js')
original_filename = filename
if extra_info is not None:
temp_files = shared.get_temp_files()
temp = temp_files.get('.js').name
shutil.copyfile(filename, temp)
with open(temp, 'a') as f:
f.write('// EXTRA_INFO: ' + extra_info)
filename = temp
cmd = config.NODE_JS + [optimizer, filename] + passes
# Keep JS code comments intact through the acorn optimization pass so that JSDoc comments
# will be carried over to a later Closure run.
if settings.USE_CLOSURE_COMPILER:
cmd += ['--closureFriendly']
if settings.EXPORT_ES6:
cmd += ['--exportES6']
if settings.VERBOSE:
cmd += ['verbose']
if not return_output:
next = original_filename + '.jso.js'
shared.get_temp_files().note(next)
check_call(cmd, stdout=open(next, 'w'))
save_intermediate(next, '%s.js' % passes[0])
return next
output = check_call(cmd, stdout=PIPE).stdout
return output
WASM_CALL_CTORS = '__wasm_call_ctors'
# evals ctors. if binaryen_bin is provided, it is the dir of the binaryen tool
# for this, and we are in wasm mode
def eval_ctors(js_file, wasm_file, debug_info):
if settings.MINIMAL_RUNTIME:
CTOR_ADD_PATTERN = f"asm['{WASM_CALL_CTORS}']();" # TODO test
else:
CTOR_ADD_PATTERN = f"addOnInit(Module['asm']['{WASM_CALL_CTORS}']);"
js = utils.read_file(js_file)
has_wasm_call_ctors = False
# eval the ctor caller as well as main, or, in standalone mode, the proper
# entry/init function
if not settings.STANDALONE_WASM:
ctors = []
kept_ctors = []
has_wasm_call_ctors = CTOR_ADD_PATTERN in js
if has_wasm_call_ctors:
ctors += [WASM_CALL_CTORS]
if settings.HAS_MAIN:
ctors += ['main']
# TODO perhaps remove the call to main from the JS? or is this an abi
# we want to preserve?
kept_ctors += ['main']
if not ctors:
logger.info('ctor_evaller: no ctors')
return
args = ['--ctors=' + ','.join(ctors)]
if kept_ctors:
args += ['--kept-exports=' + ','.join(kept_ctors)]
else:
if settings.EXPECT_MAIN:
ctor = '_start'
else:
ctor = '_initialize'
args = ['--ctors=' + ctor, '--kept-exports=' + ctor]
if settings.EVAL_CTORS == 2:
args += ['--ignore-external-input']
logger.info('ctor_evaller: trying to eval global ctors (' + ' '.join(args) + ')')
out = run_binaryen_command('wasm-ctor-eval', wasm_file, wasm_file, args=args, stdout=PIPE, debug=debug_info)
logger.info('\n\n' + out)
num_successful = out.count('success on')
if num_successful and has_wasm_call_ctors:
js = js.replace(CTOR_ADD_PATTERN, '')
utils.write_file(js_file, js)
def get_closure_compiler():
# First check if the user configured a specific CLOSURE_COMPILER in thier settings
if config.CLOSURE_COMPILER:
return config.CLOSURE_COMPILER
# Otherwise use the one installed vai npm
cmd = shared.get_npm_cmd('google-closure-compiler')
if not WINDOWS:
# Work around an issue that Closure compiler can take up a lot of memory and crash in an error
# "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap
# out of memory"
cmd.insert(-1, '--max_old_space_size=8192')
return cmd
def check_closure_compiler(cmd, args, env, allowed_to_fail):
cmd = cmd + args + ['--version']
try:
output = run_process(cmd, stdout=PIPE, env=env).stdout
except Exception as e:
if allowed_to_fail:
return False
if isinstance(e, subprocess.CalledProcessError):
sys.stderr.write(e.stdout)
sys.stderr.write(str(e) + '\n')
exit_with_error('closure compiler (%s) did not execute properly!' % shared.shlex_join(cmd))
if 'Version:' not in output:
if allowed_to_fail:
return False
exit_with_error('unrecognized closure compiler --version output (%s):\n%s' % (shared.shlex_join(cmd), output))
return True
# Remove this once we require python3.7 and can use std.isascii.
# See: https://docs.python.org/3/library/stdtypes.html#str.isascii
def isascii(s):
try:
s.encode('ascii')
except UnicodeEncodeError:
return False
else:
return True
def get_closure_compiler_and_env(user_args):
env = shared.env_with_node_in_path()
closure_cmd = get_closure_compiler()
native_closure_compiler_works = check_closure_compiler(closure_cmd, user_args, env, allowed_to_fail=True)
if not native_closure_compiler_works and not any(a.startswith('--platform') for a in user_args):
# Run with Java Closure compiler as a fallback if the native version does not work
user_args.append('--platform=java')
check_closure_compiler(closure_cmd, user_args, env, allowed_to_fail=False)
if config.JAVA and '--platform=java' in user_args:
# Closure compiler expects JAVA_HOME to be set *and* java.exe to be in the PATH in order
# to enable use the java backend. Without this it will only try the native and JavaScript
# versions of the compiler.
java_bin = os.path.dirname(config.JAVA)
if java_bin:
def add_to_path(dirname):
env['PATH'] = env['PATH'] + os.pathsep + dirname
add_to_path(java_bin)
java_home = os.path.dirname(java_bin)
env.setdefault('JAVA_HOME', java_home)
return closure_cmd, env
@ToolchainProfiler.profile()
def closure_transpile(filename, pretty):
user_args = []
closure_cmd, env = get_closure_compiler_and_env(user_args)
closure_cmd += ['--language_out', 'ES5']
closure_cmd += ['--compilation_level', 'WHITESPACE_ONLY']
return run_closure_cmd(closure_cmd, filename, env, pretty)
@ToolchainProfiler.profile()
def closure_compiler(filename, pretty, advanced=True, extra_closure_args=None):
user_args = []
env_args = os.environ.get('EMCC_CLOSURE_ARGS')
if env_args:
user_args += shlex.split(env_args)
if extra_closure_args:
user_args += extra_closure_args
closure_cmd, env = get_closure_compiler_and_env(user_args)
# Closure externs file contains known symbols to be extern to the minification, Closure
# should not minify these symbol names.
CLOSURE_EXTERNS = [path_from_root('src/closure-externs/closure-externs.js')]
# Closure compiler needs to know about all exports that come from the wasm module, because to optimize for small code size,
# the exported symbols are added to global scope via a foreach loop in a way that evades Closure's static analysis. With an explicit
# externs file for the exports, Closure is able to reason about the exports.
if settings.WASM_FUNCTION_EXPORTS and not settings.DECLARE_ASM_MODULE_EXPORTS:
# Generate an exports file that records all the exported symbols from the wasm module.
module_exports_suppressions = '\n'.join(['/**\n * @suppress {duplicate, undefinedVars}\n */\nvar %s;\n' % asmjs_mangle(i) for i in settings.WASM_FUNCTION_EXPORTS])
exports_file = shared.get_temp_files().get('_module_exports.js')
exports_file.write(module_exports_suppressions.encode())
exports_file.close()
CLOSURE_EXTERNS += [exports_file.name]
# Node.js specific externs
if shared.target_environment_may_be('node'):
NODE_EXTERNS_BASE = path_from_root('third_party/closure-compiler/node-externs')
NODE_EXTERNS = os.listdir(NODE_EXTERNS_BASE)
NODE_EXTERNS = [os.path.join(NODE_EXTERNS_BASE, name) for name in NODE_EXTERNS
if name.endswith('.js')]
CLOSURE_EXTERNS += [path_from_root('src/closure-externs/node-externs.js')] + NODE_EXTERNS
# V8/SpiderMonkey shell specific externs
if shared.target_environment_may_be('shell'):
V8_EXTERNS = [path_from_root('src/closure-externs/v8-externs.js')]
SPIDERMONKEY_EXTERNS = [path_from_root('src/closure-externs/spidermonkey-externs.js')]
CLOSURE_EXTERNS += V8_EXTERNS + SPIDERMONKEY_EXTERNS
# Web environment specific externs
if shared.target_environment_may_be('web') or shared.target_environment_may_be('worker'):
BROWSER_EXTERNS_BASE = path_from_root('src/closure-externs/browser-externs')
if os.path.isdir(BROWSER_EXTERNS_BASE):
BROWSER_EXTERNS = os.listdir(BROWSER_EXTERNS_BASE)
BROWSER_EXTERNS = [os.path.join(BROWSER_EXTERNS_BASE, name) for name in BROWSER_EXTERNS
if name.endswith('.js')]
CLOSURE_EXTERNS += BROWSER_EXTERNS
if settings.DYNCALLS:
CLOSURE_EXTERNS += [path_from_root('src/closure-externs/dyncall-externs.js')]
if settings.MINIMAL_RUNTIME and settings.USE_PTHREADS:
CLOSURE_EXTERNS += [path_from_root('src/closure-externs/minimal_runtime_worker_externs.js')]
args = ['--compilation_level', 'ADVANCED_OPTIMIZATIONS' if advanced else 'SIMPLE_OPTIMIZATIONS']
# Keep in sync with ecmaVersion in tools/acorn-optimizer.js
args += ['--language_in', 'ECMASCRIPT_2020']
# Tell closure not to do any transpiling or inject any polyfills.
# At some point we may want to look into using this as way to convert to ES5 but
# babel is perhaps a better tool for that.
if settings.TRANSPILE_TO_ES5:
args += ['--language_out', 'ES5']
else:
args += ['--language_out', 'NO_TRANSPILE']
# Tell closure never to inject the 'use strict' directive.
args += ['--emit_use_strict=false']
if settings.IGNORE_CLOSURE_COMPILER_ERRORS:
args.append('--jscomp_off=*')
# Specify input file relative to the temp directory to avoid specifying non-7-bit-ASCII path names.
for e in CLOSURE_EXTERNS:
args += ['--externs', e]
args += user_args
cmd = closure_cmd + args
return run_closure_cmd(cmd, filename, env, pretty=pretty)
def run_closure_cmd(cmd, filename, env, pretty):
cmd += ['--js', filename]
# Closure compiler is unable to deal with path names that are not 7-bit ASCII:
# https://github.com/google/closure-compiler/issues/3784
tempfiles = shared.get_temp_files()
def move_to_safe_7bit_ascii_filename(filename):
if isascii(filename):
return os.path.abspath(filename)
safe_filename = tempfiles.get('.js').name # Safe 7-bit filename
shutil.copyfile(filename, safe_filename)
return os.path.relpath(safe_filename, tempfiles.tmpdir)
for i in range(len(cmd)):
for prefix in ('--externs', '--js'):
# Handle the case where the the flag and the value are two separate arguments.
if cmd[i] == prefix:
cmd[i + 1] = move_to_safe_7bit_ascii_filename(cmd[i + 1])
# and the case where they are one argument, e.g. --externs=foo.js
elif cmd[i].startswith(prefix + '='):
# Replace the argument with a version that has a safe filename.
filename = cmd[i].split('=', 1)[1]
cmd[i] = '='.join([prefix, move_to_safe_7bit_ascii_filename(filename)])
outfile = tempfiles.get('.cc.js').name # Safe 7-bit filename
# Specify output file relative to the temp directory to avoid specifying non-7-bit-ASCII path names.
cmd += ['--js_output_file', os.path.relpath(outfile, tempfiles.tmpdir)]
if pretty:
cmd += ['--formatting', 'PRETTY_PRINT']
shared.print_compiler_stage(cmd)
# Closure compiler does not work if any of the input files contain characters outside the
# 7-bit ASCII range. Therefore make sure the command line we pass does not contain any such
# input files by passing all input filenames relative to the cwd. (user temp directory might
# be in user's home directory, and user's profile name might contain unicode characters)
proc = run_process(cmd, stderr=PIPE, check=False, env=env, cwd=tempfiles.tmpdir)
# XXX Closure bug: if Closure is invoked with --create_source_map, Closure should create a
# outfile.map source map file (https://github.com/google/closure-compiler/wiki/Source-Maps)
# But it looks like it creates such files on Linux(?) even without setting that command line
# flag (and currently we don't), so delete the produced source map file to not leak files in
# temp directory.
try_delete(outfile + '.map')
# Print Closure diagnostics result up front.
if proc.returncode != 0:
logger.error('Closure compiler run failed:\n')
elif len(proc.stderr.strip()) > 0:
if settings.CLOSURE_WARNINGS == 'error':
logger.error('Closure compiler completed with warnings and -sCLOSURE_WARNINGS=error enabled, aborting!\n')
elif settings.CLOSURE_WARNINGS == 'warn':
logger.warn('Closure compiler completed with warnings:\n')
# Print input file (long wall of text!)
if DEBUG == 2 and (proc.returncode != 0 or (len(proc.stderr.strip()) > 0 and settings.CLOSURE_WARNINGS != 'quiet')):
input_file = open(filename, 'r').read().splitlines()
for i in range(len(input_file)):
sys.stderr.write(f'{i + 1}: {input_file[i]}\n')
if proc.returncode != 0:
logger.error(proc.stderr) # print list of errors (possibly long wall of text if input was minified)
# Exit and print final hint to get clearer output
msg = f'closure compiler failed (rc: {proc.returncode}): {shared.shlex_join(cmd)}'
if not pretty:
msg += ' the error message may be clearer with -g1 and EMCC_DEBUG=2 set'
exit_with_error(msg)
if len(proc.stderr.strip()) > 0 and settings.CLOSURE_WARNINGS != 'quiet':
# print list of warnings (possibly long wall of text if input was minified)
if settings.CLOSURE_WARNINGS == 'error':
logger.error(proc.stderr)
else:
logger.warn(proc.stderr)
# Exit and/or print final hint to get clearer output
if not pretty:
logger.warn('(rerun with -g1 linker flag for an unminified output)')
elif DEBUG != 2:
logger.warn('(rerun with EMCC_DEBUG=2 enabled to dump Closure input file)')
if settings.CLOSURE_WARNINGS == 'error':
exit_with_error('closure compiler produced warnings and -sCLOSURE_WARNINGS=error enabled')
return outfile
# minify the final wasm+JS combination. this is done after all the JS
# and wasm optimizations; here we do the very final optimizations on them
def minify_wasm_js(js_file, wasm_file, expensive_optimizations, minify_whitespace, debug_info):
# start with JSDCE, to clean up obvious JS garbage. When optimizing for size,
# use AJSDCE (aggressive JS DCE, performs multiple iterations). Clean up
# whitespace if necessary too.
passes = []
if not settings.LINKABLE:
passes.append('JSDCE' if not expensive_optimizations else 'AJSDCE')
if minify_whitespace:
passes.append('minifyWhitespace')
if passes:
logger.debug('running cleanup on shell code: ' + ' '.join(passes))
js_file = acorn_optimizer(js_file, passes)
# if we can optimize this js+wasm combination under the assumption no one else
# will see the internals, do so
if not settings.LINKABLE:
# if we are optimizing for size, shrink the combined wasm+JS
# TODO: support this when a symbol map is used
if expensive_optimizations:
js_file = metadce(js_file, wasm_file, minify_whitespace=minify_whitespace, debug_info=debug_info)
# now that we removed unneeded communication between js and wasm, we can clean up
# the js some more.
passes = ['AJSDCE']
if minify_whitespace:
passes.append('minifyWhitespace')
logger.debug('running post-meta-DCE cleanup on shell code: ' + ' '.join(passes))
js_file = acorn_optimizer(js_file, passes)
if settings.MINIFY_WASM_IMPORTS_AND_EXPORTS:
js_file = minify_wasm_imports_and_exports(js_file, wasm_file, minify_whitespace=minify_whitespace, minify_exports=settings.MINIFY_ASMJS_EXPORT_NAMES, debug_info=debug_info)
return js_file
# run binaryen's wasm-metadce to dce both js and wasm
def metadce(js_file, wasm_file, minify_whitespace, debug_info):
logger.debug('running meta-DCE')
temp_files = shared.get_temp_files()
# first, get the JS part of the graph
if settings.MAIN_MODULE:
# For the main module we include all exports as possible roots, not just function exports.
# This means that any usages of data symbols within the JS or in the side modules can/will keep
# these exports alive on the wasm module.
# This is important today for weak data symbols that are defined by the main and the side module
# (i.e. RTTI info). We want to make sure the main module's symbols get added to asmLibraryArg
# when the main module is loaded. If this doesn't happen then the symbols in the side module
# will take precedence.
exports = settings.WASM_EXPORTS