-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathlink.py
3133 lines (2628 loc) · 130 KB
/
link.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 2011 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 base64
import glob
import hashlib
import json
import logging
import os
import re
import shlex
import stat
import shutil
import time
from subprocess import PIPE
from urllib.parse import quote
from . import building
from . import cache
from . import config
from . import diagnostics
from . import emscripten
from . import feature_matrix
from . import filelock
from . import js_manipulation
from . import ports
from . import shared
from . import system_libs
from . import utils
from . import webassembly
from . import extract_metadata
from .utils import read_file, write_file, delete_file
from .utils import removeprefix, exit_with_error
from .shared import in_temp, safe_copy, do_replace, OFormat
from .shared import DEBUG, WINDOWS, DYNAMICLIB_ENDINGS, STATICLIB_ENDINGS
from .shared import unsuffixed, unsuffixed_basename, get_file_suffix
from .settings import settings, default_setting, user_settings, JS_ONLY_SETTINGS, DEPRECATED_SETTINGS
from .minimal_runtime_shell import generate_minimal_runtime_html
import tools.line_endings
logger = logging.getLogger('link')
DEFAULT_SHELL_HTML = utils.path_from_root('src/shell.html')
DEFAULT_ASYNCIFY_IMPORTS = ['__asyncjs__*']
DEFAULT_ASYNCIFY_EXPORTS = [
'main',
'__main_argc_argv',
]
VALID_ENVIRONMENTS = ('web', 'webview', 'worker', 'node', 'shell')
EXECUTABLE_ENDINGS = ['.wasm', '.html', '.js', '.mjs', '.out', '']
# Supported LLD flags which we will pass through to the linker.
SUPPORTED_LINKER_FLAGS = (
'--start-group', '--end-group',
'-(', '-)',
'--whole-archive', '--no-whole-archive',
'-whole-archive', '-no-whole-archive'
)
# Unsupported LLD flags which we will ignore.
# Maps to true if the flag takes an argument.
UNSUPPORTED_LLD_FLAGS = {
# macOS-specific linker flag that libtool (ltmain.sh) will if macOS is detected.
'-bind_at_load': False,
# wasm-ld doesn't support soname or other dynamic linking flags (yet). Ignore them
# in order to aid build systems that want to pass these flags.
'-soname': True,
'-allow-shlib-undefined': False,
'-rpath': True,
'-rpath-link': True,
'-version-script': True,
'-install_name': True,
}
UBSAN_SANITIZERS = {
'alignment',
'bool',
'builtin',
'bounds',
'enum',
'float-cast-overflow',
'float-divide-by-zero',
'function',
'implicit-unsigned-integer-truncation',
'implicit-signed-integer-truncation',
'implicit-integer-sign-change',
'integer-divide-by-zero',
'nonnull-attribute',
'null',
'nullability-arg',
'nullability-assign',
'nullability-return',
'object-size',
'pointer-overflow',
'return',
'returns-nonnull-attribute',
'shift',
'signed-integer-overflow',
'unreachable',
'unsigned-integer-overflow',
'vla-bound',
'vptr',
'undefined',
'undefined-trap',
'implicit-integer-truncation',
'implicit-integer-arithmetic-value-change',
'implicit-conversion',
'integer',
'nullability',
}
final_js = None
# this function uses the global 'final' variable, which contains the current
# final output file. if a method alters final, and calls this method, then it
# must modify final globally (i.e. it can't receive final as a param and
# return it)
# TODO: refactor all this, a singleton that abstracts over the final output
# and saving of intermediates
def save_intermediate(name, suffix='js'):
if not DEBUG:
return
if not final_js:
logger.debug(f'(not saving intermediate {name} because not generating JS)')
return
building.save_intermediate(final_js, f'{name}.{suffix}')
def save_intermediate_with_wasm(name, wasm_binary):
if not DEBUG:
return
save_intermediate(name) # save the js
building.save_intermediate(wasm_binary, name + '.wasm')
def base64_encode(filename):
data = utils.read_binary(filename)
b64 = base64.b64encode(data)
return b64.decode('ascii')
def align_to_wasm_page_boundary(address):
page_size = webassembly.WASM_PAGE_SIZE
return ((address + (page_size - 1)) // page_size) * page_size
def will_metadce():
# The metadce JS parsing code does not currently support the JS that gets generated
# when assertions are enabled.
if settings.ASSERTIONS:
return False
return settings.OPT_LEVEL >= 3 or settings.SHRINK_LEVEL >= 1
def setup_environment_settings():
# Environment setting based on user input
environments = settings.ENVIRONMENT.split(',')
if any([x for x in environments if x not in VALID_ENVIRONMENTS]):
exit_with_error(f'Invalid environment specified in "ENVIRONMENT": {settings.ENVIRONMENT}. Should be one of: {",".join(VALID_ENVIRONMENTS)}')
settings.ENVIRONMENT_MAY_BE_WEB = not settings.ENVIRONMENT or 'web' in environments
settings.ENVIRONMENT_MAY_BE_WEBVIEW = not settings.ENVIRONMENT or 'webview' in environments
settings.ENVIRONMENT_MAY_BE_NODE = not settings.ENVIRONMENT or 'node' in environments
settings.ENVIRONMENT_MAY_BE_SHELL = not settings.ENVIRONMENT or 'shell' in environments
# The worker case also includes Node.js workers when pthreads are
# enabled and Node.js is one of the supported environments for the build to
# run on. Node.js workers are detected as a combination of
# ENVIRONMENT_IS_WORKER and ENVIRONMENT_IS_NODE.
settings.ENVIRONMENT_MAY_BE_WORKER = \
not settings.ENVIRONMENT or \
'worker' in environments or \
(settings.ENVIRONMENT_MAY_BE_NODE and settings.PTHREADS)
if not settings.ENVIRONMENT_MAY_BE_WORKER and settings.PROXY_TO_WORKER:
exit_with_error('if you specify --proxy-to-worker and specify a "-sENVIRONMENT=" directive, it must include "worker" as a target! (Try e.g. -sENVIRONMENT=web,worker)')
if not settings.ENVIRONMENT_MAY_BE_WORKER and settings.SHARED_MEMORY:
exit_with_error('when building with multithreading enabled and a "-sENVIRONMENT=" directive is specified, it must include "worker" as a target! (Try e.g. -sENVIRONMENT=web,worker)')
def generate_js_sym_info():
# Runs the js compiler to generate a list of all symbols available in the JS
# libraries. This must be done separately for each linker invocation since the
# list of symbols depends on what settings are used.
# TODO(sbc): Find a way to optimize this. Potentially we could add a super-set
# mode of the js compiler that would generate a list of all possible symbols
# that could be checked in.
_, forwarded_data = emscripten.compile_javascript(symbols_only=True)
# When running in symbols_only mode compiler.mjs outputs a flat list of C symbols.
return json.loads(forwarded_data)
@ToolchainProfiler.profile_block('JS symbol generation')
def get_js_sym_info():
# Avoiding using the cache when generating struct info since
# this step is performed while the cache is locked.
if DEBUG or settings.BOOTSTRAPPING_STRUCT_INFO or config.FROZEN_CACHE:
return generate_js_sym_info()
# We define a cache hit as when the settings and `--js-library` contents are
# identical.
# Ignore certain settings that can are no relevant to library deps. Here we
# skip PRE_JS_FILES/POST_JS_FILES which don't effect the library symbol list
# and can contain full paths to temporary files.
skip_settings = {'PRE_JS_FILES', 'POST_JS_FILES'}
input_files = [json.dumps(settings.external_dict(skip_keys=skip_settings), sort_keys=True, indent=2)]
for jslib in sorted(glob.glob(utils.path_from_root('src') + '/library*.js')):
input_files.append(read_file(jslib))
for jslib in settings.JS_LIBRARIES:
if not os.path.isabs(jslib):
jslib = utils.path_from_root('src', jslib)
input_files.append(read_file(jslib))
content = '\n'.join(input_files)
content_hash = hashlib.sha1(content.encode('utf-8')).hexdigest()
def build_symbol_list(filename):
"""Only called when there is no existing symbol list for a given content hash.
"""
library_syms = generate_js_sym_info()
write_file(filename, json.dumps(library_syms, separators=(',', ':'), indent=2))
# We need to use a separate lock here for symbol lists because, unlike with system libraries,
# it's normally for these file to get pruned as part of normal operation. This means that it
# can be deleted between the `cache.get()` then the `read_file`.
with filelock.FileLock(cache.get_path(cache.get_path('symbol_lists.lock'))):
filename = cache.get(f'symbol_lists/{content_hash}.json', build_symbol_list)
library_syms = json.loads(read_file(filename))
# Limit of the overall size of the cache to 100 files.
# This code will get test coverage since a full test run of `other` or `core`
# generates ~1000 unique symbol lists.
cache_limit = 500
root = cache.get_path('symbol_lists')
if len(os.listdir(root)) > cache_limit:
files = []
for f in os.listdir(root):
f = os.path.join(root, f)
files.append((f, os.path.getmtime(f)))
files.sort(key=lambda x: x[1])
# Delete all but the newest N files
for f, _ in files[:-cache_limit]:
delete_file(f)
return library_syms
def filter_link_flags(flags, using_lld):
def is_supported(f):
if using_lld:
for flag, takes_arg in UNSUPPORTED_LLD_FLAGS.items():
# lld allows various flags to have either a single -foo or double --foo
if f.startswith(flag) or f.startswith('-' + flag):
diagnostics.warning('linkflags', 'ignoring unsupported linker flag: `%s`', f)
# Skip the next argument if this linker flag takes and argument and that
# argument was not specified as a separately (i.e. it was specified as
# single arg containing an `=` char.)
skip_next = takes_arg and '=' not in f
return False, skip_next
return True, False
else:
if f in SUPPORTED_LINKER_FLAGS:
return True, False
# Silently ignore -l/-L flags when not using lld. If using lld allow
# them to pass through the linker
if f.startswith('-l') or f.startswith('-L'):
return False, False
diagnostics.warning('linkflags', 'ignoring unsupported linker flag: `%s`', f)
return False, False
results = []
skip_next = False
for f in flags:
if skip_next:
skip_next = False
continue
keep, skip_next = is_supported(f[1])
if keep:
results.append(f)
return results
def fix_windows_newlines(text):
# Avoid duplicating \r\n to \r\r\n when writing out text.
if WINDOWS:
text = text.replace('\r\n', '\n')
return text
def read_js_files(files):
contents = []
for f in files:
content = read_file(f)
if content.startswith('#preprocess\n'):
contents.append(shared.read_and_preprocess(f, expand_macros=True))
else:
contents.append(content)
contents = '\n'.join(contents)
return fix_windows_newlines(contents)
def should_run_binaryen_optimizer():
# run the binaryen optimizer in -O2+. in -O0 we don't need it obviously, while
# in -O1 we don't run it as the LLVM optimizer has been run, and it does the
# great majority of the work; not running the binaryen optimizer in that case
# keeps -O1 mostly-optimized while compiling quickly and without rewriting
# DWARF etc.
return settings.OPT_LEVEL >= 2
def get_binaryen_passes():
passes = []
optimizing = should_run_binaryen_optimizer()
# wasm-emscripten-finalize will strip the features section for us
# automatically, but if we did not modify the wasm then we didn't run it,
# and in an optimized build we strip it manually here. (note that in an
# unoptimized build we might end up with the features section, if we neither
# optimize nor run wasm-emscripten-finalize, but a few extra bytes in the
# binary don't matter in an unoptimized build)
if optimizing:
passes += ['--strip-target-features']
# safe heap must run before post-emscripten, so post-emscripten can apply the sbrk ptr
if settings.SAFE_HEAP:
passes += ['--safe-heap']
# sign-ext is enabled by default by llvm. If the target browser settings don't support
# this we lower it away here using a binaryen pass.
if not feature_matrix.caniuse(feature_matrix.Feature.SIGN_EXT):
logger.debug('lowering sign-ext feature due to incompatible target browser engines')
passes += ['--signext-lowering']
if optimizing:
passes += ['--post-emscripten']
if settings.SIDE_MODULE:
passes += ['--pass-arg=post-emscripten-side-module']
if optimizing:
passes += [building.opt_level_to_str(settings.OPT_LEVEL, settings.SHRINK_LEVEL)]
# when optimizing, use the fact that low memory is never used (1024 is a
# hardcoded value in the binaryen pass). we also cannot do it when the stack
# is first, as then the stack is in the low memory that should be unused.
if optimizing and settings.GLOBAL_BASE >= 1024 and not settings.STACK_FIRST:
passes += ['--low-memory-unused']
if settings.AUTODEBUG:
# adding '--flatten' here may make these even more effective
passes += ['--instrument-locals']
passes += ['--log-execution']
passes += ['--instrument-memory']
if settings.LEGALIZE_JS_FFI:
# legalize it again now, as the instrumentation may need it
passes += ['--legalize-js-interface']
passes += building.js_legalization_pass_flags()
if settings.EMULATE_FUNCTION_POINTER_CASTS:
# note that this pass must run before asyncify, as if it runs afterwards we only
# generate the byn$fpcast_emu functions after asyncify runs, and so we wouldn't
# be able to further process them.
passes += ['--fpcast-emu']
if settings.ASYNCIFY == 1:
passes += ['--asyncify']
if settings.MAIN_MODULE or settings.SIDE_MODULE:
passes += ['--pass-arg=asyncify-relocatable']
if settings.ASSERTIONS:
passes += ['--pass-arg=asyncify-asserts']
if settings.ASYNCIFY_ADVISE:
passes += ['--pass-arg=asyncify-verbose']
if settings.ASYNCIFY_IGNORE_INDIRECT:
passes += ['--pass-arg=asyncify-ignore-indirect']
if settings.ASYNCIFY_PROPAGATE_ADD:
passes += ['--pass-arg=asyncify-propagate-addlist']
passes += ['--pass-arg=asyncify-imports@%s' % ','.join(settings.ASYNCIFY_IMPORTS)]
# shell escaping can be confusing; try to emit useful warnings
def check_human_readable_list(items):
for item in items:
if item.count('(') != item.count(')'):
logger.warning('emcc: ASYNCIFY list contains an item without balanced parentheses ("(", ")"):')
logger.warning(' ' + item)
logger.warning('This may indicate improper escaping that led to splitting inside your names.')
logger.warning('Try using a response file. e.g: [email protected]. The format is a simple')
logger.warning('text file, one line per function.')
break
if settings.ASYNCIFY_REMOVE:
check_human_readable_list(settings.ASYNCIFY_REMOVE)
passes += ['--pass-arg=asyncify-removelist@%s' % ','.join(settings.ASYNCIFY_REMOVE)]
if settings.ASYNCIFY_ADD:
check_human_readable_list(settings.ASYNCIFY_ADD)
passes += ['--pass-arg=asyncify-addlist@%s' % ','.join(settings.ASYNCIFY_ADD)]
if settings.ASYNCIFY_ONLY:
check_human_readable_list(settings.ASYNCIFY_ONLY)
passes += ['--pass-arg=asyncify-onlylist@%s' % ','.join(settings.ASYNCIFY_ONLY)]
if settings.MEMORY64 == 2:
passes += ['--memory64-lowering', '--table64-lowering']
if settings.BINARYEN_IGNORE_IMPLICIT_TRAPS:
passes += ['--ignore-implicit-traps']
# normally we can assume the memory, if imported, has not been modified
# beforehand (in fact, in most cases the memory is not even imported anyhow,
# but it is still safe to pass the flag), and is therefore filled with zeros.
# the one exception is dynamic linking of a side module: the main module is ok
# as it is loaded first, but the side module may be assigned memory that was
# previously used.
if optimizing and not settings.SIDE_MODULE:
passes += ['--zero-filled-memory']
# LLVM output always has immutable initial table contents: the table is
# fixed and may only be appended to at runtime (that is true even in
# relocatable mode)
if optimizing:
passes += ['--pass-arg=directize-initial-contents-immutable']
if settings.BINARYEN_EXTRA_PASSES:
# BINARYEN_EXTRA_PASSES is comma-separated, and we support both '-'-prefixed and
# unprefixed pass names
extras = settings.BINARYEN_EXTRA_PASSES.split(',')
passes += [('--' + p) if p[0] != '-' else p for p in extras if p]
# Run the translator to the new EH instructions with exnref
if settings.WASM_EXNREF:
passes += ['--emit-exnref']
# If we are going to run metadce then that means we will be running binaryen
# tools after the main invocation, whose flags are determined here
# (specifically we will run metadce and possibly also wasm-opt for import/
# export minification). And when we run such a tool it will "undo" any
# StackIR optimizations (since the conversion to BinaryenIR undoes them as it
# restructures the code). We could re-run those opts, but it is most efficient
# to just not do them now if we'll invoke other tools later, and we'll do them
# only in the very last invocation.
if will_metadce():
passes += ['--no-stack-ir']
return passes
def make_js_executable(script):
src = read_file(script)
cmd = config.NODE_JS
if settings.MEMORY64 == 1:
cmd += shared.node_memory64_flags()
elif settings.WASM_BIGINT:
cmd += shared.node_bigint_flags(config.NODE_JS)
if len(cmd) > 1 or not os.path.isabs(cmd[0]):
# Using -S (--split-string) here means that arguments to the executable are
# correctly parsed. We don't do this by default because old versions of env
# don't support -S.
cmd = '/usr/bin/env -S ' + shared.shlex_join(cmd)
else:
cmd = shared.shlex_join(cmd)
logger.debug('adding `#!` to JavaScript file: %s' % cmd)
# add shebang
with open(script, 'w') as f:
f.write('#!%s\n' % cmd)
f.write(src)
try:
os.chmod(script, stat.S_IMODE(os.stat(script).st_mode) | stat.S_IXUSR) # make executable
except OSError:
pass # can fail if e.g. writing the executable to /dev/null
def do_split_module(wasm_file, options):
os.replace(wasm_file, wasm_file + '.orig')
args = ['--instrument']
if options.requested_debug:
# Tell wasm-split to preserve function names.
args += ['-g']
building.run_binaryen_command('wasm-split', wasm_file + '.orig', outfile=wasm_file, args=args)
def get_worker_js_suffix():
return '.worker.mjs' if settings.EXPORT_ES6 else '.worker.js'
def setup_pthreads():
if settings.RELOCATABLE:
# pthreads + dynamic linking has certain limitations
if settings.SIDE_MODULE:
diagnostics.warning('experimental', '-sSIDE_MODULE + pthreads is experimental')
elif settings.MAIN_MODULE:
diagnostics.warning('experimental', '-sMAIN_MODULE + pthreads is experimental')
elif settings.LINKABLE:
diagnostics.warning('experimental', '-sLINKABLE + pthreads is experimental')
if settings.ALLOW_MEMORY_GROWTH:
diagnostics.warning('pthreads-mem-growth', '-pthread + ALLOW_MEMORY_GROWTH may run non-wasm code slowly, see https://github.com/WebAssembly/design/issues/1271')
default_setting('DEFAULT_PTHREAD_STACK_SIZE', settings.STACK_SIZE)
if not settings.MINIMAL_RUNTIME and 'instantiateWasm' not in settings.INCOMING_MODULE_JS_API:
# pthreads runtime depends on overriding instantiateWasm
settings.INCOMING_MODULE_JS_API.append('instantiateWasm')
# Functions needs by runtime_pthread.js
settings.REQUIRED_EXPORTS += [
'_emscripten_thread_free_data',
'_emscripten_thread_crashed',
'emscripten_main_runtime_thread_id',
'emscripten_main_thread_process_queued_calls',
'_emscripten_run_on_main_thread_js',
'emscripten_stack_set_limits',
]
if settings.EMBIND:
settings.REQUIRED_EXPORTS.append('_embind_initialize_bindings')
if settings.MAIN_MODULE:
settings.REQUIRED_EXPORTS += [
'_emscripten_dlsync_self',
'_emscripten_dlsync_self_async',
'_emscripten_proxy_dlsync',
'_emscripten_proxy_dlsync_async',
'__dl_seterr',
]
# runtime_pthread.js depends on these library symbols
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += [
'$PThread',
'$establishStackSpace',
'$invokeEntryPoint',
]
if settings.MINIMAL_RUNTIME:
building.user_requested_exports.add('exit')
def set_initial_memory():
user_specified_initial_heap = 'INITIAL_HEAP' in user_settings
# INITIAL_HEAP cannot be used when the memory object is created in JS: we don't know
# the size of static data here and thus the total initial memory size.
if settings.IMPORTED_MEMORY:
if user_specified_initial_heap:
# Some of these could (and should) be implemented.
exit_with_error('INITIAL_HEAP is currently not compatible with IMPORTED_MEMORY (which is enabled indirectly via SHARED_MEMORY, RELOCATABLE, ASYNCIFY_LAZY_LOAD_CODE)')
# The default for imported memory is to fall back to INITIAL_MEMORY.
settings.INITIAL_HEAP = -1
if not user_specified_initial_heap:
# For backwards compatibility, we will only use INITIAL_HEAP by default when the user
# specified neither INITIAL_MEMORY nor MAXIMUM_MEMORY. Both place an upper bounds on
# the overall initial linear memory (stack + static data + heap), and we do not know
# the size of static data at this stage. Setting any non-zero initial heap value in
# this scenario would risk pushing users over the limit they have set.
user_specified_initial = settings.INITIAL_MEMORY != -1
user_specified_maximum = 'MAXIMUM_MEMORY' in user_settings or 'WASM_MEM_MAX' in user_settings or 'BINARYEN_MEM_MAX' in user_settings
if user_specified_initial or user_specified_maximum:
settings.INITIAL_HEAP = -1
# Apply the default if we are going with INITIAL_MEMORY.
if settings.INITIAL_HEAP == -1 and settings.INITIAL_MEMORY == -1:
default_setting('INITIAL_MEMORY', 16 * 1024 * 1024)
def check_memory_setting(setting):
if settings[setting] % webassembly.WASM_PAGE_SIZE != 0:
exit_with_error(f'{setting} must be a multiple of WebAssembly page size (64KiB), was {settings[setting]}')
if settings[setting] >= 2**53:
exit_with_error(f'{setting} must be smaller than 2^53 bytes due to JS Numbers (doubles) being used to hold pointer addresses in JS side')
# Due to the aforementioned lack of knowledge about the static data size, we delegate
# checking the overall consistency of these settings to wasm-ld.
if settings.INITIAL_HEAP != -1:
check_memory_setting('INITIAL_HEAP')
if settings.INITIAL_MEMORY != -1:
check_memory_setting('INITIAL_MEMORY')
if settings.INITIAL_MEMORY < settings.STACK_SIZE:
exit_with_error(f'INITIAL_MEMORY must be larger than STACK_SIZE, was {settings.INITIAL_MEMORY} (STACK_SIZE={settings.STACK_SIZE})')
check_memory_setting('MAXIMUM_MEMORY')
if settings.MEMORY_GROWTH_LINEAR_STEP != -1:
check_memory_setting('MEMORY_GROWTH_LINEAR_STEP')
# Set an upper estimate of what MAXIMUM_MEMORY should be. Take note that this value
# may not be precise, and is only an upper bound of the exact value calculated later
# by the linker.
def set_max_memory():
# With INITIAL_HEAP, we only know the lower bound on initial memory size.
initial_memory_known = settings.INITIAL_MEMORY != -1
if not settings.ALLOW_MEMORY_GROWTH:
if 'MAXIMUM_MEMORY' in user_settings:
diagnostics.warning('unused-command-line-argument', 'MAXIMUM_MEMORY is only meaningful with ALLOW_MEMORY_GROWTH')
# Optimization: lower the default maximum memory to initial memory if possible.
if initial_memory_known:
settings.MAXIMUM_MEMORY = settings.INITIAL_MEMORY
# Automaticaly up the default maximum when the user requested a large minimum.
if 'MAXIMUM_MEMORY' not in user_settings:
if settings.ALLOW_MEMORY_GROWTH:
if any([settings.INITIAL_HEAP != -1 and settings.INITIAL_HEAP >= 2 * 1024 * 1024 * 1024,
initial_memory_known and settings.INITIAL_MEMORY > 2 * 1024 * 1024 * 1024]):
settings.MAXIMUM_MEMORY = 4 * 1024 * 1024 * 1024
# INITIAL_MEMORY sets a lower bound for MAXIMUM_MEMORY
if initial_memory_known and settings.INITIAL_MEMORY > settings.MAXIMUM_MEMORY:
settings.MAXIMUM_MEMORY = settings.INITIAL_MEMORY
# A similar check for INITIAL_HEAP would not be precise and so is delegated to wasm-ld.
if initial_memory_known and settings.MAXIMUM_MEMORY < settings.INITIAL_MEMORY:
exit_with_error('MAXIMUM_MEMORY cannot be less than INITIAL_MEMORY')
def inc_initial_memory(delta):
# Both INITIAL_HEAP and INITIAL_MEMORY can be set at the same time. Increment both.
if settings.INITIAL_HEAP != -1:
settings.INITIAL_HEAP += delta
if settings.INITIAL_MEMORY != -1:
settings.INITIAL_MEMORY += delta
def check_browser_versions():
# Map of setting all VM version settings to the minimum version
# we support.
min_version_settings = {
'MIN_FIREFOX_VERSION': feature_matrix.OLDEST_SUPPORTED_FIREFOX,
'MIN_CHROME_VERSION': feature_matrix.OLDEST_SUPPORTED_CHROME,
'MIN_SAFARI_VERSION': feature_matrix.OLDEST_SUPPORTED_SAFARI,
'MIN_NODE_VERSION': feature_matrix.OLDEST_SUPPORTED_NODE,
}
if settings.LEGACY_VM_SUPPORT:
# Default all browser versions to zero
for key in min_version_settings.keys():
default_setting(key, 0)
for key, oldest in min_version_settings.items():
if settings[key] != 0 and settings[key] < oldest:
exit_with_error(f'{key} older than {oldest} is not supported')
@ToolchainProfiler.profile_block('linker_setup')
def phase_linker_setup(options, state, newargs):
system_libpath = '-L' + str(cache.get_lib_dir(absolute=True))
state.append_link_flag(system_libpath)
# We used to do this check during on startup during `check_sanity`, but
# we now only do it when linking, in order to reduce the overhead when
# only compiling.
if not shared.SKIP_SUBPROCS:
shared.check_llvm_version()
autoconf = os.environ.get('EMMAKEN_JUST_CONFIGURE') or 'conftest.c' in state.orig_args or 'conftest.cpp' in state.orig_args
if autoconf:
# configure tests want a more shell-like style, where we emit return codes on exit()
settings.EXIT_RUNTIME = 1
# use node.js raw filesystem access, to behave just like a native executable
settings.NODERAWFS = 1
# Add `#!` line to output JS and make it executable.
options.executable = True
if 'noExitRuntime' in settings.INCOMING_MODULE_JS_API:
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE.append('$noExitRuntime')
if settings.OPT_LEVEL >= 1:
default_setting('ASSERTIONS', 0)
if options.emrun:
options.pre_js.append(utils.path_from_root('src/emrun_prejs.js'))
options.post_js.append(utils.path_from_root('src/emrun_postjs.js'))
# emrun mode waits on program exit
settings.EXIT_RUNTIME = 1
if options.cpu_profiler:
options.post_js.append(utils.path_from_root('src/cpuprofiler.js'))
if not settings.RUNTIME_DEBUG:
settings.RUNTIME_DEBUG = bool(settings.LIBRARY_DEBUG or
settings.GL_DEBUG or
settings.DYLINK_DEBUG or
settings.OPENAL_DEBUG or
settings.SYSCALL_DEBUG or
settings.WEBSOCKET_DEBUG or
settings.SOCKET_DEBUG or
settings.FETCH_DEBUG or
settings.EXCEPTION_DEBUG or
settings.PTHREADS_DEBUG or
settings.ASYNCIFY_DEBUG)
if options.memory_profiler:
settings.MEMORYPROFILER = 1
if settings.PTHREADS_PROFILING:
if not settings.ASSERTIONS:
exit_with_error('PTHREADS_PROFILING only works with ASSERTIONS enabled')
options.post_js.append(utils.path_from_root('src/threadprofiler.js'))
options.extern_pre_js = read_js_files(options.extern_pre_js)
options.extern_post_js = read_js_files(options.extern_post_js)
# TODO: support source maps with js_transform
if options.js_transform and settings.GENERATE_SOURCE_MAP:
logger.warning('disabling source maps because a js transform is being done')
settings.GENERATE_SOURCE_MAP = 0
# options.output_file is the user-specified one, target is what we will generate
if options.output_file:
target = options.output_file
# check for the existence of the output directory now, to avoid having
# to do so repeatedly when each of the various output files (.mem, .wasm,
# etc) are written. This gives a more useful error message than the
# IOError and python backtrace that users would otherwise see.
dirname = os.path.dirname(target)
if dirname and not os.path.isdir(dirname):
exit_with_error("specified output file (%s) is in a directory that does not exist" % target)
elif autoconf:
# Autoconf expects the executable output file to be called `a.out`
target = 'a.out'
elif settings.SIDE_MODULE:
target = 'a.out.wasm'
else:
target = 'a.out.js'
final_suffix = get_file_suffix(target)
for s, reason in DEPRECATED_SETTINGS.items():
if s in user_settings:
diagnostics.warning('deprecated', f'{s} is deprecated ({reason}). Please open a bug if you have a continuing need for this setting')
if settings.EXTRA_EXPORTED_RUNTIME_METHODS:
settings.EXPORTED_RUNTIME_METHODS += settings.EXTRA_EXPORTED_RUNTIME_METHODS
# If no output format was specified we try to deduce the format based on
# the output filename extension
if not options.oformat and (options.relocatable or (options.shared and not settings.SIDE_MODULE)):
# Until we have a better story for actually producing runtime shared libraries
# we support a compatibility mode where shared libraries are actually just
# object files linked with `wasm-ld --relocatable` or `llvm-link` in the case
# of LTO.
if final_suffix in EXECUTABLE_ENDINGS:
diagnostics.warning('emcc', '-shared/-r used with executable output suffix. This behaviour is deprecated. Please remove -shared/-r to build an executable or avoid the executable suffix (%s) when building object files.' % final_suffix)
else:
if options.shared:
diagnostics.warning('emcc', 'linking a library with `-shared` will emit a static object file. This is a form of emulation to support existing build systems. If you want to build a runtime shared library use the SIDE_MODULE setting.')
options.oformat = OFormat.OBJECT
if not options.oformat:
if settings.SIDE_MODULE or final_suffix == '.wasm':
options.oformat = OFormat.WASM
elif final_suffix == '.mjs':
options.oformat = OFormat.MJS
elif final_suffix == '.html':
options.oformat = OFormat.HTML
else:
options.oformat = OFormat.JS
if options.oformat in (OFormat.WASM, OFormat.OBJECT):
for s in JS_ONLY_SETTINGS:
if s in user_settings:
diagnostics.warning('unused-command-line-argument', f'{s} is only valid when generating JavaScript output')
if options.oformat == OFormat.MJS:
settings.EXPORT_ES6 = 1
settings.MODULARIZE = 1
if options.oformat in (OFormat.WASM, OFormat.BARE):
if options.emit_tsd:
exit_with_error('Wasm only output is not compatible --emit-tsd')
# If the user asks directly for a wasm file then this *is* the target
wasm_target = target
elif settings.SINGLE_FILE or settings.WASM == 0:
# In SINGLE_FILE or WASM2JS mode the wasm file is not part of the output at
# all so we generate it the temp directory.
wasm_target = in_temp(shared.replace_suffix(target, '.wasm'))
else:
# Otherwise the wasm file is produced alongside the final target.
wasm_target = get_secondary_target(target, '.wasm')
if settings.SAFE_HEAP not in [0, 1, 2]:
exit_with_error('emcc: SAFE_HEAP must be 0, 1 or 2')
if not settings.WASM:
# When the user requests non-wasm output, we enable wasm2js. that is,
# we still compile to wasm normally, but we compile the final output
# to js.
settings.WASM = 1
settings.WASM2JS = 1
if settings.WASM == 2:
# Requesting both Wasm and Wasm2JS support
settings.WASM2JS = 1
if options.oformat == OFormat.WASM and not settings.SIDE_MODULE:
# if the output is just a wasm file, it will normally be a standalone one,
# as there is no JS. an exception are side modules, as we can't tell at
# compile time whether JS will be involved or not - the main module may
# have JS, and the side module is expected to link against that.
# we also do not support standalone mode in fastcomp.
settings.STANDALONE_WASM = 1
if settings.LZ4:
settings.EXPORTED_RUNTIME_METHODS += ['LZ4']
if settings.PURE_WASI:
settings.STANDALONE_WASM = 1
settings.WASM_BIGINT = 1
# WASI does not support Emscripten (JS-based) exception catching, which the
# JS-based longjmp support also uses. Emscripten EH is by default disabled
# so we don't need to do anything here.
if not settings.WASM_EXCEPTIONS:
default_setting('SUPPORT_LONGJMP', 0)
if options.no_entry:
settings.EXPECT_MAIN = 0
elif settings.STANDALONE_WASM:
if '_main' in settings.EXPORTED_FUNCTIONS:
# TODO(sbc): Make this into a warning?
logger.debug('including `_main` in EXPORTED_FUNCTIONS is not necessary in standalone mode')
else:
# In normal non-standalone mode we have special handling of `_main` in EXPORTED_FUNCTIONS.
# 1. If the user specifies exports, but doesn't include `_main` we assume they want to build a
# reactor.
# 2. If the user doesn't export anything we default to exporting `_main` (unless `--no-entry`
# is specified (see above).
if 'EXPORTED_FUNCTIONS' in user_settings:
if '_main' in settings.USER_EXPORTS:
settings.EXPORTED_FUNCTIONS.remove('_main')
settings.EXPORT_IF_DEFINED.append('main')
else:
settings.EXPECT_MAIN = 0
else:
settings.EXPORT_IF_DEFINED.append('main')
if settings.STANDALONE_WASM:
# In STANDALONE_WASM mode we either build a command or a reactor.
# See https://github.com/WebAssembly/WASI/blob/main/design/application-abi.md
# For a command we always want EXIT_RUNTIME=1
# For a reactor we always want EXIT_RUNTIME=0
if 'EXIT_RUNTIME' in user_settings:
exit_with_error('explicitly setting EXIT_RUNTIME not compatible with STANDALONE_WASM. EXIT_RUNTIME will always be True for programs (with a main function) and False for reactors (not main function).')
settings.EXIT_RUNTIME = settings.EXPECT_MAIN
settings.IGNORE_MISSING_MAIN = 0
# the wasm must be runnable without the JS, so there cannot be anything that
# requires JS legalization
default_setting('LEGALIZE_JS_FFI', 0)
if 'MEMORY_GROWTH_LINEAR_STEP' in user_settings:
exit_with_error('MEMORY_GROWTH_LINEAR_STEP is not compatible with STANDALONE_WASM')
if 'MEMORY_GROWTH_GEOMETRIC_CAP' in user_settings:
exit_with_error('MEMORY_GROWTH_GEOMETRIC_CAP is not compatible with STANDALONE_WASM')
if settings.MINIMAL_RUNTIME:
exit_with_error('MINIMAL_RUNTIME reduces JS size, and is incompatible with STANDALONE_WASM which focuses on ignoring JS anyhow and being 100% wasm')
# Note the exports the user requested
building.user_requested_exports.update(settings.EXPORTED_FUNCTIONS)
if '_main' in settings.EXPORTED_FUNCTIONS or 'main' in settings.EXPORT_IF_DEFINED:
settings.EXPORT_IF_DEFINED.append('__main_argc_argv')
elif settings.ASSERTIONS and not settings.STANDALONE_WASM:
# In debug builds when `main` is not explicitly requested as an
# export we still add it to EXPORT_IF_DEFINED so that we can warn
# users who forget to explicitly export `main`.
# See other.test_warn_unexported_main.
# This is not needed in STANDALONE_WASM mode since we export _start
# (unconditionally) rather than main.
settings.EXPORT_IF_DEFINED += ['main', '__main_argc_argv']
if settings.ASSERTIONS:
# Exceptions are thrown with a stack trace by default when ASSERTIONS is
# set and when building with either -fexceptions or -fwasm-exceptions.
if 'EXCEPTION_STACK_TRACES' in user_settings and not settings.EXCEPTION_STACK_TRACES:
exit_with_error('EXCEPTION_STACK_TRACES cannot be disabled when ASSERTIONS are enabled')
if settings.WASM_EXCEPTIONS or not settings.DISABLE_EXCEPTION_CATCHING:
settings.EXCEPTION_STACK_TRACES = 1
# -sASSERTIONS implies basic stack overflow checks, and ASSERTIONS=2
# implies full stack overflow checks. However, we don't set this default in
# PURE_WASI, or when we are linking without standard libraries because
# STACK_OVERFLOW_CHECK depends on emscripten_stack_get_end which is defined
# in libcompiler-rt.
if not settings.PURE_WASI and '-nostdlib' not in newargs and '-nodefaultlibs' not in newargs:
default_setting('STACK_OVERFLOW_CHECK', max(settings.ASSERTIONS, settings.STACK_OVERFLOW_CHECK))
# For users that opt out of WARN_ON_UNDEFINED_SYMBOLS we assume they also
# want to opt out of ERROR_ON_UNDEFINED_SYMBOLS.
if user_settings.get('WARN_ON_UNDEFINED_SYMBOLS') == '0':
default_setting('ERROR_ON_UNDEFINED_SYMBOLS', 0)
# It is unlikely that developers targeting "native web" APIs with MINIMAL_RUNTIME need
# errno support by default.
if settings.MINIMAL_RUNTIME:
# Require explicit -lfoo.js flags to link with JS libraries.
default_setting('AUTO_JS_LIBRARIES', 0)
# When using MINIMAL_RUNTIME, symbols should only be exported if requested.
default_setting('EXPORT_KEEPALIVE', 0)
if settings.STRICT_JS and (settings.MODULARIZE or settings.EXPORT_ES6):
exit_with_error("STRICT_JS doesn't work with MODULARIZE or EXPORT_ES6")
if not options.shell_path:
# Minimal runtime uses a different default shell file
if settings.MINIMAL_RUNTIME:
options.shell_path = options.shell_path = utils.path_from_root('src/shell_minimal_runtime.html')
else:
options.shell_path = DEFAULT_SHELL_HTML
if settings.STRICT:
if not settings.MODULARIZE and not settings.EXPORT_ES6:
default_setting('STRICT_JS', 1)
default_setting('DEFAULT_TO_CXX', 0)
default_setting('IGNORE_MISSING_MAIN', 0)
default_setting('AUTO_NATIVE_LIBRARIES', 0)
if settings.MAIN_MODULE != 1:
# These two settings cannot be disabled with MAIN_MODULE=1 because all symbols
# are needed in this mode.
default_setting('AUTO_JS_LIBRARIES', 0)
default_setting('ALLOW_UNIMPLEMENTED_SYSCALLS', 0)
if options.oformat == OFormat.HTML and options.shell_path == DEFAULT_SHELL_HTML:
# Out default shell.html file has minimal set of INCOMING_MODULE_JS_API elements that it expects
default_setting('INCOMING_MODULE_JS_API', 'canvas,monitorRunDependencies,onAbort,onExit,print,setStatus'.split(','))
else:
default_setting('INCOMING_MODULE_JS_API', [])
if not settings.MINIMAL_RUNTIME and not settings.STRICT:
# Export the HEAP object by default, when not running in STRICT mode
settings.EXPORTED_RUNTIME_METHODS.extend([
'HEAPF32',
'HEAPF64',
'HEAP_DATA_VIEW',
'HEAP8', 'HEAPU8',
'HEAP16', 'HEAPU16',
'HEAP32', 'HEAPU32',
'HEAP64', 'HEAPU64',
])
# Default to TEXTDECODER=2 (always use TextDecoder to decode UTF-8 strings)
# in -Oz builds, since custom decoder for UTF-8 takes up space.
# In pthreads enabled builds, TEXTDECODER==2 may not work, see
# https://github.com/whatwg/encoding/issues/172
# When supporting shell environments, do not do this as TextDecoder is not
# widely supported there.
if settings.SHRINK_LEVEL >= 2 and not settings.SHARED_MEMORY and \
not settings.ENVIRONMENT_MAY_BE_SHELL:
default_setting('TEXTDECODER', 2)
# If set to 1, we will run the autodebugger (the automatic debugging tool, see
# tools/autodebugger). Note that this will disable inclusion of libraries. This
# is useful because including dlmalloc makes it hard to compare native and js
# builds
if os.environ.get('EMCC_AUTODEBUG'):
settings.AUTODEBUG = 1
# Use settings
if settings.DEBUG_LEVEL > 1 and options.use_closure_compiler:
diagnostics.warning('emcc', 'disabling closure because debug info was requested')
options.use_closure_compiler = False
if settings.WASM == 2 and settings.SINGLE_FILE:
exit_with_error('cannot have both WASM=2 and SINGLE_FILE enabled at the same time')
if settings.SEPARATE_DWARF and settings.WASM2JS:
exit_with_error('cannot have both SEPARATE_DWARF and WASM2JS at the same time (as there is no wasm file)')
if settings.MINIMAL_RUNTIME_STREAMING_WASM_COMPILATION and settings.MINIMAL_RUNTIME_STREAMING_WASM_INSTANTIATION:
exit_with_error('MINIMAL_RUNTIME_STREAMING_WASM_COMPILATION and MINIMAL_RUNTIME_STREAMING_WASM_INSTANTIATION are mutually exclusive!')
if options.emrun:
if settings.MINIMAL_RUNTIME:
exit_with_error('--emrun is not compatible with MINIMAL_RUNTIME')
if options.use_closure_compiler:
settings.USE_CLOSURE_COMPILER = 1
if 'CLOSURE_WARNINGS' in user_settings:
if settings.CLOSURE_WARNINGS not in ['quiet', 'warn', 'error']:
exit_with_error('invalid option -sCLOSURE_WARNINGS=%s specified! Allowed values are "quiet", "warn" or "error".' % settings.CLOSURE_WARNINGS)
diagnostics.warning('deprecated', 'CLOSURE_WARNINGS is deprecated, use -Wclosure/-Wno-closure instead')
closure_warnings = diagnostics.manager.warnings['closure']
if settings.CLOSURE_WARNINGS == 'error':
closure_warnings['error'] = True
closure_warnings['enabled'] = True
elif settings.CLOSURE_WARNINGS == 'warn':
closure_warnings['error'] = False
closure_warnings['enabled'] = True
elif settings.CLOSURE_WARNINGS == 'quiet':
closure_warnings['error'] = False
closure_warnings['enabled'] = False
if not settings.MINIMAL_RUNTIME:
if not settings.BOOTSTRAPPING_STRUCT_INFO:
if settings.DYNCALLS:
# Include dynCall() function by default in DYNCALLS builds in classic runtime; in MINIMAL_RUNTIME, must add this explicitly.
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$dynCall']
if settings.ASSERTIONS:
# "checkUnflushedContent()" and "missingLibrarySymbol()" depend on warnOnce
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$warnOnce']
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$getValue', '$setValue']
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$ExitStatus']