-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathlink.py
More file actions
3186 lines (2667 loc) · 129 KB
/
link.py
File metadata and controls
3186 lines (2667 loc) · 129 KB
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.
import base64
import json
import logging
import os
import re
import shlex
import shutil
import stat
from subprocess import PIPE
from urllib.parse import quote
from . import (
building,
cache,
config,
diagnostics,
emscripten,
extract_metadata,
feature_matrix,
js_manipulation,
ports,
shared,
system_libs,
utils,
webassembly,
)
from .cmdline import OFormat
from .feature_matrix import Feature
from .minimal_runtime_shell import generate_minimal_runtime_html
from .settings import (
DEPRECATED_SETTINGS,
EXPERIMENTAL_SETTINGS,
INCOMPATIBLE_SETTINGS,
JS_ONLY_SETTINGS,
default_setting,
settings,
user_settings,
)
from .shared import DEBUG, DYLIB_EXTENSIONS, do_replace, in_temp
from .toolchain_profiler import ToolchainProfiler
from .utils import (
WINDOWS,
delete_file,
exit_with_error,
get_file_suffix,
read_file,
safe_copy,
unsuffixed,
unsuffixed_basename,
write_file,
)
logger = logging.getLogger('link')
DEFAULT_SHELL_HTML = utils.path_from_root('html/shell.html')
DEFAULT_ASYNCIFY_IMPORTS = ['__asyncjs__*']
DEFAULT_ASYNCIFY_EXPORTS = [
'main',
'__main_argc_argv',
]
VALID_ENVIRONMENTS = {'web', 'webview', 'worker', 'node', 'shell', 'worklet'}
EXECUTABLE_EXTENSIONS = ['.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',
'-rpath',
)
# 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.
'-allow-shlib-undefined': False,
'-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():
# The worker environment is automatically added if any of the pthread or Worker features are used.
# Note: we need to actually modify ENVIRONMENTS variable here before the parsing,
# because some JS code reads it back so modifying parsed info alone is not sufficient.
maybe_web_worker = not settings.ENVIRONMENT or 'worker' in settings.ENVIRONMENT
if settings.SHARED_MEMORY and settings.ENVIRONMENT:
settings.ENVIRONMENT.append('worker')
if settings.AUDIO_WORKLET:
settings.ENVIRONMENT.append('worklet')
# Environment setting based on user input
if any(x for x in settings.ENVIRONMENT 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 settings.ENVIRONMENT
settings.ENVIRONMENT_MAY_BE_WEBVIEW = not settings.ENVIRONMENT or 'webview' in settings.ENVIRONMENT
settings.ENVIRONMENT_MAY_BE_NODE = not settings.ENVIRONMENT or 'node' in settings.ENVIRONMENT
settings.ENVIRONMENT_MAY_BE_SHELL = not settings.ENVIRONMENT or 'shell' in settings.ENVIRONMENT
settings.ENVIRONMENT_MAY_BE_WORKER = not settings.ENVIRONMENT or 'worker' in settings.ENVIRONMENT
settings.ENVIRONMENT_MAY_BE_AUDIO_WORKLET = not settings.ENVIRONMENT or 'worklet' in settings.ENVIRONMENT
if not settings.ENVIRONMENT_MAY_BE_NODE:
if 'MIN_NODE_VERSION' in user_settings and settings.MIN_NODE_VERSION != feature_matrix.UNSUPPORTED:
diagnostics.warning('unused-command-line-argument', 'ignoring MIN_NODE_VERSION because `node` environment is not enabled')
settings.MIN_NODE_VERSION = feature_matrix.UNSUPPORTED
if not (settings.ENVIRONMENT_MAY_BE_WEB or maybe_web_worker or settings.ENVIRONMENT_MAY_BE_WEBVIEW):
for browser in ('FIREFOX', 'SAFARI', 'CHROME'):
key = f'MIN_{browser}_VERSION'
if key in user_settings and settings[key] != feature_matrix.UNSUPPORTED:
diagnostics.warning('unused-command-line-argument', 'ignoring %s because `web`, `worker` and `webview` environments are not enabled', key)
settings[key] = feature_matrix.UNSUPPORTED
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.
"""
output = emscripten.compile_javascript(symbols_only=True)
# When running in symbols_only mode compiler.mjs outputs symbol metadata as JSON.
return json.loads(output)
@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()
content_hash = emscripten.generate_js_compiler_input_hash(symbols_only=True)
def generate_json():
library_syms = generate_js_sym_info()
return json.dumps(library_syms, separators=(',', ':'), indent=2)
# Limit of the overall size of the cache.
# This code will get test coverage since a full test run of `other` or `core`
# generates ~1000 unique symbol lists.
file_content = emscripten.get_cached_file('symbol_lists', f'{content_hash}.json', generate_json, cache_limit=500)
return json.loads(file_content)
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, '-' + flag)):
diagnostics.warning('linkflags', 'ignoring unsupported linker flag: `%s`', f)
# Skip the next argument if this linker flag takes an argument and that
# argument was not specified 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 not f.startswith('-') or 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', '-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)
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(building.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_lowering_passes():
passes = []
# The following features are all enabled in llvm by default and therefore
# enabled in the emscripten system libraries. This means that we need to
# lower them away using binaryen passes, if they are not enabled in the
# feature matrix.
# This can happen if the feature is explicitly disabled on the command line,
# or when targeting an VM/engine that does not support the feature.
# List of [<feature_name>, <lowering_flag>, <feature_flags>] triples.
features = [
[Feature.SIGN_EXT, '--signext-lowering', ['--enable-sign-ext']],
[Feature.NON_TRAPPING_FPTOINT, '--llvm-nontrapping-fptoint-lowering', ['--enable-nontrapping-float-to-int']],
[Feature.BULK_MEMORY, '--llvm-memory-copy-fill-lowering', ['--enable-bulk-memory', '--enable-bulk-memory-opt']],
]
for feature, lowering_flag, feature_flags in features:
if not feature_matrix.caniuse(feature):
logger.debug(f'lowering {feature.name} feature due to incompatible target browser engines')
for f in feature_flags:
# Remove features from binaryen_features, otherwise future runs of binaryen
# could re-introduce the feature.
if f in building.binaryen_features:
building.binaryen_features.remove(f)
passes.append(lowering_flag)
return passes
def get_binaryen_passes(options):
passes = get_binaryen_lowering_passes()
optimizing = should_run_binaryen_optimizer()
# safe heap must run before post-emscripten, so post-emscripten can apply the sbrk ptr
if settings.SAFE_HEAP:
passes += ['--safe-heap']
if settings.EMULATE_FUNCTION_POINTER_CASTS:
# fpcast-emu must run before -Ox so that directize (inside -Ox) sees
# the rewritten table entries with matching types. It must also run
# before asyncify so the byn$fpcast-emu thunks get instrumented.
passes += ['--fpcast-emu']
if optimizing:
# 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)
passes += ['--strip-target-features']
passes += ['--post-emscripten']
if settings.SIDE_MODULE:
passes += ['--pass-arg=post-emscripten-side-module']
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 settings.GLOBAL_BASE >= 1024 and not settings.STACK_FIRST:
passes += ['--low-memory-unused']
if options.fast_math:
passes += ['--fast-math']
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.ASYNCIFY == 1:
passes += ['--asyncify']
if settings.MAIN_MODULE:
passes += ['--pass-arg=asyncify-export-globals']
elif settings.SIDE_MODULE:
passes += ['--pass-arg=asyncify-import-globals']
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: -sASYNCIFY_ONLY=@funcs.txt. 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]
# 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)
# By default, the resulting script will run under the version of node in the PATH.
if settings.EXECUTABLE == 1:
settings.EXECUTABLE = '/usr/bin/env node'
logger.debug(f'adding `#!` to JavaScript file: {settings.EXECUTABLE}')
# add shebang
with open(script, 'w', encoding='utf-8') as f:
f.write(f'#!{settings.EXECUTABLE}\n')
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():
# pthreads + dynamic linking has certain limitations
if settings.MAIN_MODULE:
diagnostics.warning('experimental', 'dynamic linking + pthreads is experimental')
if settings.ALLOW_MEMORY_GROWTH and not settings.GROWABLE_ARRAYBUFFERS:
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)
# Functions needs by runtime_pthread.js
settings.REQUIRED_EXPORTS += [
'_emscripten_thread_free_data',
'_emscripten_thread_crashed',
]
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')
# 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
# Automatically 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:
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')
def add_system_js_lib(lib):
lib = utils.path_from_root('src/lib', lib)
assert os.path.exists(lib)
settings.JS_LIBRARIES.append(lib)
def check_settings():
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')
for name, msg in EXPERIMENTAL_SETTINGS.items():
if getattr(settings, name):
diagnostics.warning('experimental', msg)
for a, b, reason in INCOMPATIBLE_SETTINGS:
invert_b = b.startswith('NO_')
if invert_b:
b = b[3:]
b_val = getattr(settings, b)
if invert_b:
b_val = not b_val
if getattr(settings, a) and b_val:
msg = f'{a} is not compatible with {b}'
if invert_b:
msg += '=0'
if reason:
msg += f' ({reason})'
exit_with_error(msg)
@ToolchainProfiler.profile()
def setup_sanitizers(options):
assert options.sanitize
if settings.WASM_WORKERS:
exit_with_error('WASM_WORKERS is not currently compatible with `-fsanitize` tools')
if 'leak' in options.sanitize or 'address' in options.sanitize:
# These symbols are needed by `noLeakCheck` which used to implement
# the `__noleakcheck` attribute. However this dependency is not yet represented in the JS
# symbol graph generated when we run the compiler with `--symbols-only`.
settings.REQUIRED_EXPORTS += ['__lsan_disable', '__lsan_enable']
if ('leak' in options.sanitize or 'address' in options.sanitize) and not settings.ALLOW_MEMORY_GROWTH:
# Increase the minimum memory requirements to account for extra memory
# that the sanitizers might need (in addition to the shadow memory
# requirements handled below).
# These values are designed be an over-estimate of the actual requirements and
# are based on experimentation with different tests/programs under asan and
# lsan.
inc_initial_memory(50 * 1024 * 1024)
if settings.PTHREADS:
inc_initial_memory(50 * 1024 * 1024)
if options.sanitize & UBSAN_SANITIZERS:
if options.sanitize_minimal_runtime:
settings.UBSAN_RUNTIME = 1
else:
settings.UBSAN_RUNTIME = 2
if 'leak' in options.sanitize:
settings.USE_LSAN = 1
default_setting('EXIT_RUNTIME', 1)
if 'address' in options.sanitize:
settings.USE_ASAN = 1
default_setting('EXIT_RUNTIME', 1)
if not settings.UBSAN_RUNTIME:
settings.UBSAN_RUNTIME = 2
settings.REQUIRED_EXPORTS += emscripten.ASAN_C_HELPERS
if settings.ASYNCIFY and not settings.ASYNCIFY_ONLY:
# we do not want asyncify to instrument these helpers - they just access
# memory as small getters/setters, so they cannot pause anyhow, and also
# we access them in the runtime as we prepare to rewind, which would hit
# an asyncify assertion, if asyncify instrumented them.
#
# note that if ASYNCIFY_ONLY was set by the user then we do not need to
# do anything (as the user's list won't contain these functions), and if
# we did add them, the pass would assert on incompatible lists, hence the
# condition in the above if.
settings.ASYNCIFY_REMOVE.append("__asan_*")
if settings.ASAN_SHADOW_SIZE != -1:
diagnostics.warning('emcc', 'ASAN_SHADOW_SIZE is ignored and will be removed in a future release')
if 'GLOBAL_BASE' in user_settings:
exit_with_error("ASan does not support custom GLOBAL_BASE")
# Increase the INITIAL_MEMORY and shift GLOBAL_BASE to account for
# the ASan shadow region which starts at address zero.
# The shadow region is 1/8th the size of the total memory and is
# itself part of the total memory.
# We use the following variables in this calculation:
# - user_mem : memory usable/visible by the user program.
# - shadow_size : memory used by asan for shadow memory.
# - total_mem : the sum of the above. this is the size of the wasm memory (and must be aligned to WASM_PAGE_SIZE)
user_mem = settings.MAXIMUM_MEMORY
if not settings.ALLOW_MEMORY_GROWTH and settings.INITIAL_MEMORY != -1:
user_mem = settings.INITIAL_MEMORY
# Given the know value of user memory size we can work backwards
# to find the total memory and the shadow size based on the fact
# that the user memory is 7/8ths of the total memory.
# (i.e. user_mem == total_mem * 7 / 8
# TODO-Bug?: this does not look to handle 4GB MAXIMUM_MEMORY correctly.
total_mem = user_mem * 8 / 7
# But we might need to re-align to wasm page size
total_mem = int(align_to_wasm_page_boundary(total_mem))
# The shadow size is 1/8th the resulting rounded up size
shadow_size = total_mem // 8
# We start our global data after the shadow memory.
# We don't need to worry about alignment here. wasm-ld will take care of that.
settings.GLOBAL_BASE = shadow_size
# Adjust INITIAL_MEMORY (if needed) to account for the shifted global base.
if settings.INITIAL_MEMORY != -1:
if settings.ALLOW_MEMORY_GROWTH:
settings.INITIAL_MEMORY += align_to_wasm_page_boundary(shadow_size)
else:
settings.INITIAL_MEMORY = total_mem
if settings.SAFE_HEAP:
# SAFE_HEAP instruments ASan's shadow memory accesses.
# Since the shadow memory starts at 0, the act of accessing the shadow memory is detected
# by SAFE_HEAP as a null pointer dereference.
exit_with_error('ASan does not work with SAFE_HEAP')
if settings.MEMORY64:
exit_with_error('MEMORY64 does not yet work with ASAN')
if settings.GENERATE_SOURCE_MAP:
settings.LOAD_SOURCE_MAP = 1
def get_dylibs(options, linker_args):
"""Find all the Wasm dynamic libraries specified on the command line,
either via `-lfoo` or via `libfoo.so` directly."""
dylibs = []
for arg in linker_args:
if arg.startswith('-l'):
for ext in DYLIB_EXTENSIONS:
path = find_library('lib' + arg[2:] + ext, options.lib_dirs)
if path and building.is_wasm_dylib(path):
dylibs.append(path)
elif building.is_wasm_dylib(arg):
dylibs.append(arg)
return dylibs
@ToolchainProfiler.profile_block('linker_setup')
def phase_linker_setup(options, linker_args): # noqa: C901, PLR0912, PLR0915
"""Future modifications should consider refactoring to reduce complexity.
* The McCabe cyclomatiic complexity is currently 244 vs 10 recommended.
* There are currently 252 branches vs 12 recommended.
* There are currently 563 statements vs 50 recommended.
To revalidate these numbers, run `ruff check --select=C901,PLR091`.
"""
setup_environment_settings()
apply_library_settings(linker_args)
if settings.SIDE_MODULE or settings.MAIN_MODULE:
default_setting('FAKE_DYLIBS', 0)
if options.shared and not settings.FAKE_DYLIBS:
default_setting('SIDE_MODULE', 1)
if not settings.FAKE_DYLIBS:
options.dylibs = get_dylibs(options, linker_args)
# If there are any dynamically linked libraries on the command line then
# need to enable `MAIN_MODULE` in order to produce JS code that can load them.
if not settings.MAIN_MODULE and not settings.SIDE_MODULE and options.dylibs:
default_setting('MAIN_MODULE', 2)
linker_args += calc_extra_ldflags(options)
# 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 options.input_files or 'conftest.cpp' in options.input_files
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.
settings.EXECUTABLE = config.NODE_JS[0]
# autoconf declares functions without their proper signatures, and STRICT causes that to trip up by passing --fatal-warnings to the linker.
if settings.STRICT:
exit_with_error('autoconfiguring is not compatible with STRICT')
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'))
if settings.MINIMAL_RUNTIME:
exit_with_error('--emrun is not compatible with MINIMAL_RUNTIME')
# emrun mode waits on program exit
if user_settings.get('EXIT_RUNTIME') == '0':
exit_with_error('--emrun is not compatible with EXIT_RUNTIME=0')
settings.EXIT_RUNTIME = 1
# emrun_postjs.js needs this library function.
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$addOnExit']
if options.cpu_profiler:
options.post_js.append(utils.path_from_root('src/cpuprofiler.js'))
# Unless RUNTIME_DEBUG is explicitly set then we enable it when any of the
# more specific debug settings are present.
default_setting('RUNTIME_DEBUG', int(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:
options.post_js.append(utils.path_from_root('src/threadprofiler.js'))
settings.REQUIRED_EXPORTS.append('emscripten_main_runtime_thread_id')
# threadprofiler.js needs these library functions.
settings.DEFAULT_LIBRARY_FUNCS_TO_INCLUDE += ['$addOnInit', '$addOnExit']
# 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)
# Set the EXPORT_ES6 default early since it affects the setting of the
# default oformat below.
if settings.WASM_ESM_INTEGRATION or settings.SOURCE_PHASE_IMPORTS or settings.MODULARIZE == 'instance':
default_setting('EXPORT_ES6', 1)
# 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 settings.FAKE_DYLIBS and not settings.SIDE_MODULE)):
# With FAKE_DYLIBS we generate an normal object file rather than an shared object.
# This is linked with `wasm-ld --relocatable` or (`llvm-link` in the case of LTO).
if final_suffix in EXECUTABLE_EXTENSIONS:
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 and 'FAKE_DYLIBS' not in user_settings:
diagnostics.warning('emcc', 'linking a library with `-shared` will emit a static object file (FAKE_DYLIBS defaults to true). If you want to build a runtime shared library use the SIDE_MODULE or FAKE_DYLIBS=0.')
options.oformat = OFormat.OBJECT
if not options.oformat:
if settings.SIDE_MODULE or final_suffix == '.wasm':
options.oformat = OFormat.WASM
elif final_suffix == '.html':
options.oformat = OFormat.HTML
elif final_suffix == '.mjs' or settings.EXPORT_ES6:
options.oformat = OFormat.MJS
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')
# When there is no final suffix or the suffix is `.out` (as in `a.out`) then default to
# making the resulting file exectuable.
if settings.ENVIRONMENT_MAY_BE_NODE and options.oformat == OFormat.JS and final_suffix in {'', '.out'}:
default_setting('EXECUTABLE', 1)
if settings.EXECUTABLE and not settings.ENVIRONMENT_MAY_BE_NODE:
exit_with_error('EXECUTABLE requires `node` in ENVRIONMENT')
if options.oformat == OFormat.MJS:
default_setting('EXPORT_ES6', 1)
settings.OUTPUT_FORMAT = options.oformat.name
if settings.SUPPORT_BIG_ENDIAN and settings.WASM2JS:
exit_with_error('WASM2JS is currently not compatible with SUPPORT_BIG_ENDIAN')
if settings.WASM_ESM_INTEGRATION:
default_setting('MODULARIZE', 'instance')
if not settings.EXPORT_ES6:
exit_with_error('WASM_ESM_INTEGRATION requires EXPORT_ES6')
if settings.MODULARIZE != 'instance':
exit_with_error('WASM_ESM_INTEGRATION requires MODULARIZE=instance')
if settings.MAIN_MODULE:
exit_with_error('WASM_ESM_INTEGRATION is not compatible with dynamic linking')
if settings.ASYNCIFY:
exit_with_error('WASM_ESM_INTEGRATION is not compatible with -sASYNCIFY')
if settings.WASM_WORKERS:
exit_with_error('WASM_ESM_INTEGRATION is not compatible with WASM_WORKERS')
if not settings.WASM_ASYNC_COMPILATION:
exit_with_error('WASM_ESM_INTEGRATION is not compatible with WASM_ASYNC_COMPILATION=0')
if not settings.WASM:
exit_with_error('WASM_ESM_INTEGRATION is not compatible with WASM2JS')
if settings.ABORT_ON_WASM_EXCEPTIONS:
exit_with_error('WASM_ESM_INTEGRATION is not compatible with ABORT_ON_WASM_EXCEPTIONS')
if settings.MODULARIZE and settings.MODULARIZE not in {1, 'instance'}:
exit_with_error(f'Invalid setting "{settings.MODULARIZE}" for MODULARIZE.')
def limit_incoming_module_api():
if options.oformat == OFormat.HTML and options.shell_html == DEFAULT_SHELL_HTML:
# Our 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 settings.ASYNCIFY == 1:
# ASYNCIFY=1 wraps only wasm exports so we need to enable legacy
# dyncalls via dynCall_xxx exports.
# See: https://github.com/emscripten-core/emscripten/issues/12066
settings.DYNCALLS = 1
if settings.MODULARIZE == 'instance':
diagnostics.warning('experimental', 'MODULARIZE=instance is still experimental. Many features may not work or will change.')
if not settings.EXPORT_ES6:
exit_with_error('MODULARIZE=instance requires EXPORT_ES6')
if settings.MINIMAL_RUNTIME:
exit_with_error('MODULARIZE=instance is not compatible with MINIMAL_RUNTIME')
if options.use_preload_plugins or len(options.preload_files):
exit_with_error('MODULARIZE=instance is not compatible with --embed-file/--preload-file')
if settings.MINIMAL_RUNTIME and len(options.preload_files):
exit_with_error('MINIMAL_RUNTIME is not compatible with --preload-file')
if options.oformat in {OFormat.WASM, OFormat.BARE}:
if options.emit_tsd:
exit_with_error('Wasm only output is not compatible with --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: