-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
emcc.py
1651 lines (1413 loc) · 61.9 KB
/
emcc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# 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.
"""emcc - compiler helper script
=============================
emcc is a drop-in replacement for a compiler like gcc or clang.
See emcc --help for details.
emcc can be influenced by a few environment variables:
EMCC_DEBUG - "1" will log out useful information during compilation, as well as
save each compiler step as an emcc-* file in the temp dir
(by default /tmp/emscripten_temp). "2" will save additional emcc-*
steps, that would normally not be separately produced (so this
slows down compilation).
"""
from tools.toolchain_profiler import ToolchainProfiler
import json
import logging
import os
import re
import shlex
import shutil
import sys
import time
import tarfile
from enum import Enum, auto, unique
from subprocess import PIPE
from tools import shared, system_libs, utils, ports
from tools import colored_logger, diagnostics, building
from tools.shared import unsuffixed, unsuffixed_basename, get_file_suffix
from tools.shared import run_process, exit_with_error, DEBUG
from tools.shared import in_temp, OFormat
from tools.shared import DYNAMICLIB_ENDINGS
from tools.response_file import substitute_response_files
from tools import config
from tools import cache
from tools.settings import default_setting, user_settings, settings, MEM_SIZE_SETTINGS, COMPILE_TIME_SETTINGS
from tools.utils import read_file, removeprefix
from tools import feature_matrix
logger = logging.getLogger('emcc')
# In git checkouts of emscripten `bootstrap.py` exists to run post-checkout
# steps. In packaged versions (e.g. emsdk) this file does not exist (because
# it is excluded in tools/install.py) and these steps are assumed to have been
# run already.
if os.path.exists(utils.path_from_root('.git')) and os.path.exists(utils.path_from_root('bootstrap.py')):
import bootstrap
bootstrap.check()
# endings = dot + a suffix, compare against result of shared.suffix()
C_ENDINGS = ['.c', '.i']
CXX_ENDINGS = ['.cppm', '.pcm', '.cpp', '.cxx', '.cc', '.c++', '.CPP', '.CXX', '.C', '.CC', '.C++', '.ii']
OBJC_ENDINGS = ['.m', '.mi']
PREPROCESSED_ENDINGS = ['.i', '.ii']
OBJCXX_ENDINGS = ['.mm', '.mii']
SPECIAL_ENDINGLESS_FILENAMES = [os.devnull]
C_ENDINGS += SPECIAL_ENDINGLESS_FILENAMES # consider the special endingless filenames like /dev/null to be C
SOURCE_ENDINGS = C_ENDINGS + CXX_ENDINGS + OBJC_ENDINGS + OBJCXX_ENDINGS + ['.bc', '.ll', '.S']
ASSEMBLY_ENDINGS = ['.s']
HEADER_ENDINGS = ['.h', '.hxx', '.hpp', '.hh', '.H', '.HXX', '.HPP', '.HH']
# These symbol names are allowed in INCOMING_MODULE_JS_API but are not part of the
# default set.
EXTRA_INCOMING_JS_API = [
'fetchSettings'
]
SIMD_INTEL_FEATURE_TOWER = ['-msse', '-msse2', '-msse3', '-mssse3', '-msse4.1', '-msse4.2', '-msse4', '-mavx']
SIMD_NEON_FLAGS = ['-mfpu=neon']
LINK_ONLY_FLAGS = {
'--bind', '--closure', '--cpuprofiler', '--embed-file',
'--emit-symbol-map', '--emrun', '--exclude-file', '--extern-post-js',
'--extern-pre-js', '--ignore-dynamic-linking', '--js-library',
'--js-transform', '--oformat', '--output_eol',
'--post-js', '--pre-js', '--preload-file', '--profiling-funcs',
'--proxy-to-worker', '--shell-file', '--source-map-base',
'--threadprofiler', '--use-preload-plugins'
}
@unique
class Mode(Enum):
PREPROCESS_ONLY = auto()
PCH = auto()
COMPILE_ONLY = auto()
POST_LINK_ONLY = auto()
COMPILE_AND_LINK = auto()
class EmccState:
def __init__(self, args):
self.mode = Mode.COMPILE_AND_LINK
# Using tuple here to prevent accidental mutation
self.orig_args = tuple(args)
self.has_dash_c = False
self.has_dash_E = False
self.has_dash_S = False
# List of link options paired with their position on the command line [(i, option), ...].
self.link_flags = []
self.lib_dirs = []
def has_link_flag(self, f):
return f in [x for _, x in self.link_flags]
def add_link_flag(self, i, flag):
if flag.startswith('-L'):
self.lib_dirs.append(flag[2:])
# Link flags should be adding in strictly ascending order
assert not self.link_flags or i > self.link_flags[-1][0], self.link_flags
self.link_flags.append((i, flag))
def append_link_flag(self, flag):
if self.link_flags:
index = self.link_flags[-1][0] + 1
else:
index = 1
self.add_link_flag(index, flag)
class EmccOptions:
def __init__(self):
self.target = ''
self.output_file = None
self.no_minify = False
self.post_link = False
self.save_temps = False
self.executable = False
self.compiler_wrapper = None
self.oformat = None
self.requested_debug = ''
self.emit_symbol_map = False
self.use_closure_compiler = None
self.closure_args = []
self.js_transform = None
self.pre_js = [] # before all js
self.post_js = [] # after all js
self.extern_pre_js = [] # before all js, external to optimized code
self.extern_post_js = [] # after all js, external to optimized code
self.preload_files = []
self.embed_files = []
self.exclude_files = []
self.ignore_dynamic_linking = False
self.shell_path = None
self.source_map_base = ''
self.emit_tsd = ''
self.embind_emit_tsd = ''
self.emrun = False
self.cpu_profiler = False
self.memory_profiler = False
self.use_preload_cache = False
self.use_preload_plugins = False
self.valid_abspaths = []
# Specifies the line ending format to use for all generated text files.
# Defaults to using the native EOL on each platform (\r\n on Windows, \n on
# Linux & MacOS)
self.output_eol = os.linesep
self.no_entry = False
self.shared = False
self.relocatable = False
self.reproduce = None
def create_reproduce_file(name, args):
def make_relative(filename):
filename = os.path.normpath(os.path.abspath(filename))
filename = os.path.splitdrive(filename)[1]
filename = filename[1:]
return filename
root = unsuffixed_basename(name)
with tarfile.open(name, 'w') as reproduce_file:
reproduce_file.add(shared.path_from_root('emscripten-version.txt'), os.path.join(root, 'version.txt'))
with shared.get_temp_files().get_file(suffix='.tar') as rsp_name:
with open(rsp_name, 'w') as rsp:
ignore_next = False
output_arg = None
for arg in args:
ignore = ignore_next
ignore_next = False
if arg.startswith('--reproduce='):
continue
if arg.startswith('-o='):
rsp.write('-o\n')
arg = arg[3:]
output_arg = True
ignore = True
if output_arg:
# If -o path contains directories, "emcc @response.txt" will likely
# fail because the archive we are creating doesn't contain empty
# directories for the output path (-o doesn't create directories).
# Strip directories to prevent the issue.
arg = os.path.basename(arg)
output_arg = False
if not arg.startswith('-') and not ignore:
relpath = make_relative(arg)
rsp.write(relpath + '\n')
reproduce_file.add(arg, os.path.join(root, relpath))
else:
rsp.write(arg + '\n')
if ignore:
continue
if arg in ('-MT', '-MF', '-MJ', '-MQ', '-D', '-U', '-o', '-x',
'-Xpreprocessor', '-include', '-imacros', '-idirafter',
'-iprefix', '-iwithprefix', '-iwithprefixbefore',
'-isysroot', '-imultilib', '-A', '-isystem', '-iquote',
'-install_name', '-compatibility_version',
'-current_version', '-I', '-L', '-include-pch',
'-Xlinker', '-Xclang'):
ignore_next = True
if arg == '-o':
output_arg = True
reproduce_file.add(rsp_name, os.path.join(root, 'response.txt'))
def expand_byte_size_suffixes(value):
"""Given a string with KB/MB size suffixes, such as "32MB", computes how
many bytes that is and returns it as an integer.
"""
value = value.strip()
match = re.match(r'^(\d+)\s*([kmgt]?b)?$', value, re.I)
if not match:
exit_with_error("invalid byte size `%s`. Valid suffixes are: kb, mb, gb, tb" % value)
value, suffix = match.groups()
value = int(value)
if suffix:
size_suffixes = {suffix: 1024 ** i for i, suffix in enumerate(['b', 'kb', 'mb', 'gb', 'tb'])}
value *= size_suffixes[suffix.lower()]
return value
def apply_user_settings():
"""Take a map of users settings {NAME: VALUE} and apply them to the global
settings object.
"""
# Stash a copy of all available incoming APIs before the user can potentially override it
settings.ALL_INCOMING_MODULE_JS_API = settings.INCOMING_MODULE_JS_API + EXTRA_INCOMING_JS_API
for key, value in user_settings.items():
if key in settings.internal_settings:
exit_with_error('%s is an internal setting and cannot be set from command line', key)
# map legacy settings which have aliases to the new names
# but keep the original key so errors are correctly reported via the `setattr` below
user_key = key
if key in settings.legacy_settings and key in settings.alt_names:
key = settings.alt_names[key]
# In those settings fields that represent amount of memory, translate suffixes to multiples of 1024.
if key in MEM_SIZE_SETTINGS:
value = str(expand_byte_size_suffixes(value))
filename = None
if value and value[0] == '@':
filename = removeprefix(value, '@')
if not os.path.isfile(filename):
exit_with_error('%s: file not found parsing argument: %s=%s' % (filename, key, value))
value = read_file(filename).strip()
else:
value = value.replace('\\', '\\\\')
expected_type = settings.types.get(key)
if filename and expected_type == list and value.strip()[0] != '[':
# Prefer simpler one-line-per value parser
value = parse_symbol_list_file(value)
else:
try:
value = parse_value(value, expected_type)
except Exception as e:
exit_with_error(f'error parsing "-s" setting "{key}={value}": {e}')
setattr(settings, user_key, value)
if key == 'EXPORTED_FUNCTIONS':
# used for warnings in emscripten.py
settings.USER_EXPORTS = settings.EXPORTED_FUNCTIONS.copy()
# TODO(sbc): Remove this legacy way.
if key == 'WASM_OBJECT_FILES':
settings.LTO = 0 if value else 'full'
if key == 'JSPI':
settings.ASYNCIFY = 2
if key == 'JSPI_IMPORTS':
settings.ASYNCIFY_IMPORTS = value
if key == 'JSPI_EXPORTS':
settings.ASYNCIFY_EXPORTS = value
def cxx_to_c_compiler(cxx):
# Convert C++ compiler name into C compiler name
dirname, basename = os.path.split(cxx)
basename = basename.replace('clang++', 'clang').replace('g++', 'gcc').replace('em++', 'emcc')
return os.path.join(dirname, basename)
def is_dash_s_for_emcc(args, i):
# -s OPT=VALUE or -s OPT or -sOPT are all interpreted as emscripten flags.
# -s by itself is a linker option (alias for --strip-all)
if args[i] == '-s':
if len(args) <= i + 1:
return False
arg = args[i + 1]
else:
arg = removeprefix(args[i], '-s')
arg = arg.split('=')[0]
return arg.isidentifier() and arg.isupper()
def parse_s_args(args):
settings_changes = []
for i in range(len(args)):
if args[i].startswith('-s'):
if is_dash_s_for_emcc(args, i):
if args[i] == '-s':
key = args[i + 1]
args[i + 1] = ''
else:
key = removeprefix(args[i], '-s')
args[i] = ''
# If not = is specified default to 1
if '=' not in key:
key += '=1'
# Special handling of browser version targets. A version -1 means that the specific version
# is not supported at all. Replace those with INT32_MAX to make it possible to compare e.g.
# #if MIN_FIREFOX_VERSION < 68
if re.match(r'MIN_.*_VERSION(=.*)?', key):
try:
if int(key.split('=')[1]) < 0:
key = key.split('=')[0] + '=0x7FFFFFFF'
except Exception:
pass
settings_changes.append(key)
newargs = [a for a in args if a]
return (settings_changes, newargs)
def get_target_flags():
return ['-target', shared.get_llvm_target()]
def get_clang_flags(user_args):
flags = get_target_flags()
# if exception catching is disabled, we can prevent that code from being
# generated in the frontend
if settings.DISABLE_EXCEPTION_CATCHING and not settings.WASM_EXCEPTIONS:
flags.append('-fignore-exceptions')
if settings.INLINING_LIMIT:
flags.append('-fno-inline-functions')
if settings.PTHREADS:
if '-pthread' not in user_args:
flags.append('-pthread')
elif settings.SHARED_MEMORY:
if '-matomics' not in user_args:
flags.append('-matomics')
if '-mbulk-memory' not in user_args:
flags.append('-mbulk-memory')
# In emscripten we currently disable bulk memory by default.
# This should be removed/updated when we als update the default browser targets.
if '-mbulk-memory' not in user_args and '-mno-bulk-memory' not in user_args:
# Bulk memory may be enabled via threads or directly via -s.
if not settings.BULK_MEMORY:
flags.append('-mno-bulk-memory')
if '-mnontrapping-fptoint' not in user_args and '-mno-nontrapping-fptoint' not in user_args:
flags.append('-mno-nontrapping-fptoint')
if settings.RELOCATABLE and '-fPIC' not in user_args:
flags.append('-fPIC')
if settings.RELOCATABLE or settings.LINKABLE or '-fPIC' in user_args:
if not any(a.startswith('-fvisibility') for a in user_args):
# For relocatable code we default to visibility=default in emscripten even
# though the upstream backend defaults visibility=hidden. This matches the
# expectations of C/C++ code in the wild which expects undecorated symbols
# to be exported to other DSO's by default.
flags.append('-fvisibility=default')
if settings.LTO:
if not any(a.startswith('-flto') for a in user_args):
flags.append('-flto=' + settings.LTO)
# setjmp/longjmp handling using Wasm EH
# For non-LTO, '-mllvm -wasm-enable-eh' added in
# building.llvm_backend_args() sets this feature in clang. But in LTO, the
# argument is added to wasm-ld instead, so clang needs to know that EH is
# enabled so that it can be added to the attributes in LLVM IR.
if settings.SUPPORT_LONGJMP == 'wasm':
flags.append('-mexception-handling')
else:
# In LTO mode these args get passed instead at link time when the backend runs.
for a in building.llvm_backend_args():
flags += ['-mllvm', a]
return flags
cflags = None
def get_cflags(user_args, is_cxx):
global cflags
if cflags:
return cflags
# Flags we pass to the compiler when building C/C++ code
# We add these to the user's flags (newargs), but not when building .s or .S assembly files
cflags = get_clang_flags(user_args)
cflags.append('--sysroot=' + cache.get_sysroot(absolute=True))
if settings.EMSCRIPTEN_TRACING:
cflags.append('-D__EMSCRIPTEN_TRACING__=1')
if settings.SHARED_MEMORY:
cflags.append('-D__EMSCRIPTEN_SHARED_MEMORY__=1')
if settings.WASM_WORKERS:
cflags.append('-D__EMSCRIPTEN_WASM_WORKERS__=1')
if not settings.STRICT:
# The preprocessor define EMSCRIPTEN is deprecated. Don't pass it to code
# in strict mode. Code should use the define __EMSCRIPTEN__ instead.
cflags.append('-DEMSCRIPTEN')
# Changes to default clang behavior
# Implicit functions can cause horribly confusing function pointer type errors, see #2175
# If your codebase really needs them - very unrecommended! - you can disable the error with
# -Wno-error=implicit-function-declaration
# or disable even a warning about it with
# -Wno-implicit-function-declaration
# This is already an error in C++ so we don't need to inject extra flags.
if not is_cxx:
cflags += ['-Werror=implicit-function-declaration']
ports.add_cflags(cflags, settings)
def array_contains_any_of(hay, needles):
for n in needles:
if n in hay:
return True
if array_contains_any_of(user_args, SIMD_INTEL_FEATURE_TOWER) or array_contains_any_of(user_args, SIMD_NEON_FLAGS):
if '-msimd128' not in user_args and '-mrelaxed-simd' not in user_args:
exit_with_error('passing any of ' + ', '.join(SIMD_INTEL_FEATURE_TOWER + SIMD_NEON_FLAGS) + ' flags also requires passing -msimd128 (or -mrelaxed-simd)!')
cflags += ['-D__SSE__=1']
if array_contains_any_of(user_args, SIMD_INTEL_FEATURE_TOWER[1:]):
cflags += ['-D__SSE2__=1']
if array_contains_any_of(user_args, SIMD_INTEL_FEATURE_TOWER[2:]):
cflags += ['-D__SSE3__=1']
if array_contains_any_of(user_args, SIMD_INTEL_FEATURE_TOWER[3:]):
cflags += ['-D__SSSE3__=1']
if array_contains_any_of(user_args, SIMD_INTEL_FEATURE_TOWER[4:]):
cflags += ['-D__SSE4_1__=1']
# Handle both -msse4.2 and its alias -msse4.
if array_contains_any_of(user_args, SIMD_INTEL_FEATURE_TOWER[5:]):
cflags += ['-D__SSE4_2__=1']
if array_contains_any_of(user_args, SIMD_INTEL_FEATURE_TOWER[7:]):
cflags += ['-D__AVX__=1']
if array_contains_any_of(user_args, SIMD_NEON_FLAGS):
cflags += ['-D__ARM_NEON__=1']
if '-nostdinc' not in user_args:
if not settings.USE_SDL:
cflags += ['-Xclang', '-iwithsysroot' + os.path.join('/include', 'fakesdl')]
cflags += ['-Xclang', '-iwithsysroot' + os.path.join('/include', 'compat')]
return cflags
def get_library_basename(filename):
"""Similar to get_file_suffix this strips off all numeric suffixes and then
then final non-numeric one. For example for 'libz.so.1.2.8' returns 'libz'"""
filename = os.path.basename(filename)
while filename:
filename, suffix = os.path.splitext(filename)
# Keep stipping suffixes until we strip a non-numeric one.
if not suffix[1:].isdigit():
return filename
#
# Main run() function
#
def run(args):
if shared.run_via_emxx:
clang = shared.CLANG_CXX
else:
clang = shared.CLANG_CC
# Special case the handling of `-v` because it has a special/different meaning
# when used with no other arguments. In particular, we must handle this early
# on, before we inject EMCC_CFLAGS. This is because tools like cmake and
# autoconf will run `emcc -v` to determine the compiler version and we don't
# want that to break for users of EMCC_CFLAGS.
if len(args) == 2 and args[1] == '-v':
# autoconf likes to see 'GNU' in the output to enable shared object support
print(version_string(), file=sys.stderr)
return shared.check_call([clang, '-v'] + get_target_flags(), check=False).returncode
# Additional compiler flags that we treat as if they were passed to us on the
# commandline
EMCC_CFLAGS = os.environ.get('EMCC_CFLAGS')
if EMCC_CFLAGS:
args += shlex.split(EMCC_CFLAGS)
if DEBUG:
logger.warning(f'invocation: {shared.shlex_join(args)} (in {os.getcwd()})')
# Strip args[0] (program name)
args = args[1:]
# Handle some global flags
# read response files very early on
try:
args = substitute_response_files(args)
except IOError as e:
exit_with_error(e)
if '--help' in args:
# Documentation for emcc and its options must be updated in:
# site/source/docs/tools_reference/emcc.rst
# This then gets built (via: `make -C site text`) to:
# site/build/text/docs/tools_reference/emcc.txt
# This then needs to be copied to its final home in docs/emcc.txt from where
# we read it here. We have CI rules that ensure its always up-to-date.
print(read_file(utils.path_from_root('docs/emcc.txt')))
print('''
------------------------------------------------------------------
emcc: supported targets: llvm bitcode, WebAssembly, NOT elf
(autoconf likes to see elf above to enable shared object support)
''')
return 0
## Process argument and setup the compiler
state = EmccState(args)
options, newargs = phase_parse_arguments(state)
if not shared.SKIP_SUBPROCS:
shared.check_sanity()
if '--version' in args:
print(version_string())
print('''\
Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt)
This is free and open source software under the MIT license.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
''')
return 0
if '-dumpversion' in args: # gcc's doc states "Print the compiler version [...] and don't do anything else."
print(utils.EMSCRIPTEN_VERSION)
return 0
if '--cflags' in args:
# fake running the command, to see the full args we pass to clang
args = [x for x in args if x != '--cflags']
with shared.get_temp_files().get_file(suffix='.o') as temp_target:
input_file = 'hello_world.c'
compiler = shared.EMCC
if shared.run_via_emxx:
compiler = shared.EMXX
cmd = [compiler, utils.path_from_root('test', input_file), '-v', '-c', '-o', temp_target] + args
proc = run_process(cmd, stderr=PIPE, check=False)
if proc.returncode != 0:
print(proc.stderr)
exit_with_error('error getting cflags')
lines = [x for x in proc.stderr.splitlines() if clang in x and input_file in x]
if not lines:
exit_with_error(f'unable to parse output of `{cmd}`:\n{proc.stderr}')
parts = shlex.split(lines[0].replace('\\', '\\\\'))
parts = [x for x in parts if x not in ['-c', '-o', '-v', '-emit-llvm'] and input_file not in x and temp_target not in x]
print(shared.shlex_join(parts[1:]))
return 0
if 'EMMAKEN_NO_SDK' in os.environ:
exit_with_error('EMMAKEN_NO_SDK is no longer supported. The standard -nostdlib and -nostdinc flags should be used instead')
if 'EMMAKEN_COMPILER' in os.environ:
exit_with_error('`EMMAKEN_COMPILER` is no longer supported.\n' +
'Please use the `LLVM_ROOT` and/or `COMPILER_WRAPPER` config settings instead')
if 'EMMAKEN_CFLAGS' in os.environ:
exit_with_error('`EMMAKEN_CFLAGS` is no longer supported, please use `EMCC_CFLAGS` instead')
if 'EMCC_REPRODUCE' in os.environ:
options.reproduce = os.environ['EMCC_REPRODUCE']
# For internal consistency, ensure we don't attempt or read or write any link time
# settings until we reach the linking phase.
settings.limit_settings(COMPILE_TIME_SETTINGS)
newargs, input_files = phase_setup(options, state, newargs)
if '-dumpmachine' in newargs or '-print-target-triple' in newargs or '--print-target-triple' in newargs:
print(shared.get_llvm_target())
return 0
if '-print-search-dirs' in newargs or '--print-search-dirs' in newargs:
print(f'programs: ={config.LLVM_ROOT}')
print(f'libraries: ={cache.get_lib_dir(absolute=True)}')
return 0
if '-print-resource-dir' in newargs:
shared.check_call([clang] + newargs)
return 0
if '-print-libgcc-file-name' in newargs or '--print-libgcc-file-name' in newargs:
settings.limit_settings(None)
compiler_rt = system_libs.Library.get_usable_variations()['libcompiler_rt']
print(compiler_rt.get_path(absolute=True))
return 0
print_file_name = [a for a in newargs if a.startswith('-print-file-name=') or a.startswith('--print-file-name=')]
if print_file_name:
libname = print_file_name[-1].split('=')[1]
system_libpath = cache.get_lib_dir(absolute=True)
fullpath = os.path.join(system_libpath, libname)
if os.path.isfile(fullpath):
print(fullpath)
else:
print(libname)
return 0
if options.reproduce:
create_reproduce_file(options.reproduce, args)
if state.mode == Mode.POST_LINK_ONLY:
if len(input_files) != 1:
exit_with_error('--post-link requires a single input file')
# Delay import of link.py to avoid processing this file when only compiling
from tools import link
link.run_post_link(input_files[0][1], options, state, newargs)
return 0
## Compile source code to object files
linker_inputs = phase_compile_inputs(options, state, newargs, input_files)
if state.mode == Mode.COMPILE_AND_LINK:
# Delay import of link.py to avoid processing this file when only compiling
from tools import link
return link.run(linker_inputs, options, state, newargs)
else:
logger.debug('stopping after compile phase')
return 0
def normalize_boolean_setting(name, value):
# boolean NO_X settings are aliases for X
# (note that *non*-boolean setting values have special meanings,
# and we can't just flip them, so leave them as-is to be
# handled in a special way later)
if name.startswith('NO_') and value in ('0', '1'):
name = removeprefix(name, 'NO_')
value = str(1 - int(value))
return name, value
@ToolchainProfiler.profile_block('parse arguments')
def phase_parse_arguments(state):
"""The first phase of the compiler. Parse command line argument and
populate settings.
"""
newargs = list(state.orig_args)
# Scan and strip emscripten specific cmdline warning flags.
# This needs to run before other cmdline flags have been parsed, so that
# warnings are properly printed during arg parse.
newargs = diagnostics.capture_warnings(newargs)
if not diagnostics.is_enabled('deprecated'):
settings.WARN_DEPRECATED = 0
for i in range(len(newargs)):
if newargs[i] in ('-l', '-L', '-I', '-z'):
# Scan for flags that can be written as either one or two arguments
# and normalize them to the single argument form.
newargs[i] += newargs[i + 1]
newargs[i + 1] = ''
options, settings_changes, user_js_defines, newargs = parse_args(newargs)
if options.post_link or options.oformat == OFormat.BARE:
diagnostics.warning('experimental', '--oformat=bare/--post-link are experimental and subject to change.')
explicit_settings_changes, newargs = parse_s_args(newargs)
settings_changes += explicit_settings_changes
for s in settings_changes:
key, value = s.split('=', 1)
key, value = normalize_boolean_setting(key, value)
user_settings[key] = value
# STRICT is used when applying settings so it needs to be applied first before
# calling `apply_user_settings`.
strict_cmdline = user_settings.get('STRICT')
if strict_cmdline:
settings.STRICT = int(strict_cmdline)
# Apply user -jsD settings
for s in user_js_defines:
settings[s[0]] = s[1]
# Apply -s settings in newargs here (after optimization levels, so they can override them)
apply_user_settings()
return options, newargs
@ToolchainProfiler.profile_block('setup')
def phase_setup(options, state, newargs):
"""Second phase: configure and setup the compiler based on the specified settings and arguments.
"""
if settings.RUNTIME_LINKED_LIBS:
newargs += settings.RUNTIME_LINKED_LIBS
# Find input files
# These three arrays are used to store arguments of different types for
# type-specific processing. In order to shuffle the arguments back together
# after processing, all of these arrays hold tuples (original_index, value).
# Note that the index part of the tuple can have a fractional part for input
# arguments that expand into multiple processed arguments, as in -Wl,-f1,-f2.
input_files = []
# find input files with a simple heuristic. we should really analyze
# based on a full understanding of gcc params, right now we just assume that
# what is left contains no more |-x OPT| things
skip = False
has_header_inputs = False
for i in range(len(newargs)):
if skip:
skip = False
continue
arg = newargs[i]
if arg in {'-MT', '-MF', '-MJ', '-MQ', '-D', '-U', '-o', '-x',
'-Xpreprocessor', '-include', '-imacros', '-idirafter',
'-iprefix', '-iwithprefix', '-iwithprefixbefore',
'-isysroot', '-imultilib', '-A', '-isystem', '-iquote',
'-install_name', '-compatibility_version',
'-current_version', '-I', '-L', '-include-pch',
'-undefined', '-target',
'-Xlinker', '-Xclang', '-z'}:
skip = True
if not arg.startswith('-'):
# we already removed -o <target>, so all these should be inputs
newargs[i] = ''
# os.devnul should always be reported as existing but there is bug in windows
# python before 3.8:
# https://bugs.python.org/issue1311
if not os.path.exists(arg) and arg != os.devnull:
exit_with_error('%s: No such file or directory ("%s" was expected to be an input file, based on the commandline arguments provided)', arg, arg)
file_suffix = get_file_suffix(arg)
if file_suffix in HEADER_ENDINGS:
has_header_inputs = True
input_files.append((i, arg))
elif arg.startswith('-L'):
state.add_link_flag(i, arg)
elif arg.startswith('-l'):
state.add_link_flag(i, arg)
elif arg == '-z':
state.add_link_flag(i, newargs[i])
state.add_link_flag(i + 1, newargs[i + 1])
elif arg.startswith('-z'):
state.add_link_flag(i, newargs[i])
elif arg.startswith('-Wl,'):
# Multiple comma separated link flags can be specified. Create fake
# fractional indices for these: -Wl,a,b,c,d at index 4 becomes:
# (4, a), (4.25, b), (4.5, c), (4.75, d)
link_flags_to_add = arg.split(',')[1:]
for flag_index, flag in enumerate(link_flags_to_add):
state.add_link_flag(i + float(flag_index) / len(link_flags_to_add), flag)
elif arg == '-Xlinker':
state.add_link_flag(i + 1, newargs[i + 1])
elif arg == '-s':
state.add_link_flag(i, newargs[i])
elif arg == '-':
input_files.append((i, arg))
newargs[i] = ''
newargs = [a for a in newargs if a]
# SSEx is implemented on top of SIMD128 instruction set, but do not pass SSE flags to LLVM
# so it won't think about generating native x86 SSE code.
newargs = [x for x in newargs if x not in SIMD_INTEL_FEATURE_TOWER and x not in SIMD_NEON_FLAGS]
state.has_dash_c = '-c' in newargs or '--precompile' in newargs
state.has_dash_S = '-S' in newargs
state.has_dash_E = '-E' in newargs
if options.post_link:
state.mode = Mode.POST_LINK_ONLY
elif state.has_dash_E or '-M' in newargs or '-MM' in newargs or '-fsyntax-only' in newargs:
state.mode = Mode.PREPROCESS_ONLY
elif has_header_inputs:
state.mode = Mode.PCH
elif state.has_dash_c or state.has_dash_S:
state.mode = Mode.COMPILE_ONLY
if state.mode in (Mode.COMPILE_ONLY, Mode.PREPROCESS_ONLY):
for key in user_settings:
if key not in COMPILE_TIME_SETTINGS:
diagnostics.warning(
'unused-command-line-argument',
"linker setting ignored during compilation: '%s'" % key)
for arg in state.orig_args:
if arg in LINK_ONLY_FLAGS:
diagnostics.warning(
'unused-command-line-argument',
"linker flag ignored during compilation: '%s'" % arg)
if settings.MAIN_MODULE or settings.SIDE_MODULE:
settings.RELOCATABLE = 1
if 'USE_PTHREADS' in user_settings:
settings.PTHREADS = settings.USE_PTHREADS
# Pthreads and Wasm Workers require targeting shared Wasm memory (SAB).
if settings.PTHREADS or settings.WASM_WORKERS:
settings.SHARED_MEMORY = 1
if settings.SHARED_MEMORY:
settings.BULK_MEMORY = 1
if 'DISABLE_EXCEPTION_CATCHING' in user_settings and 'EXCEPTION_CATCHING_ALLOWED' in user_settings:
# If we get here then the user specified both DISABLE_EXCEPTION_CATCHING and EXCEPTION_CATCHING_ALLOWED
# on the command line. This is no longer valid so report either an error or a warning (for
# backwards compat with the old `DISABLE_EXCEPTION_CATCHING=2`
if user_settings['DISABLE_EXCEPTION_CATCHING'] in ('0', '2'):
diagnostics.warning('deprecated', 'DISABLE_EXCEPTION_CATCHING=X is no longer needed when specifying EXCEPTION_CATCHING_ALLOWED')
else:
exit_with_error('DISABLE_EXCEPTION_CATCHING and EXCEPTION_CATCHING_ALLOWED are mutually exclusive')
if settings.EXCEPTION_CATCHING_ALLOWED:
settings.DISABLE_EXCEPTION_CATCHING = 0
if settings.WASM_EXCEPTIONS:
if user_settings.get('DISABLE_EXCEPTION_CATCHING') == '0':
exit_with_error('DISABLE_EXCEPTION_CATCHING=0 is not compatible with -fwasm-exceptions')
if user_settings.get('DISABLE_EXCEPTION_THROWING') == '0':
exit_with_error('DISABLE_EXCEPTION_THROWING=0 is not compatible with -fwasm-exceptions')
# -fwasm-exceptions takes care of enabling them, so users aren't supposed to
# pass them explicitly, regardless of their values
if 'DISABLE_EXCEPTION_CATCHING' in user_settings or 'DISABLE_EXCEPTION_THROWING' in user_settings:
diagnostics.warning('emcc', 'you no longer need to pass DISABLE_EXCEPTION_CATCHING or DISABLE_EXCEPTION_THROWING when using Wasm exceptions')
settings.DISABLE_EXCEPTION_CATCHING = 1
settings.DISABLE_EXCEPTION_THROWING = 1
if user_settings.get('ASYNCIFY') == '1':
diagnostics.warning('emcc', 'ASYNCIFY=1 is not compatible with -fwasm-exceptions. Parts of the program that mix ASYNCIFY and exceptions will not compile.')
if user_settings.get('SUPPORT_LONGJMP') == 'emscripten':
exit_with_error('SUPPORT_LONGJMP=emscripten is not compatible with -fwasm-exceptions')
if settings.DISABLE_EXCEPTION_THROWING and not settings.DISABLE_EXCEPTION_CATCHING:
exit_with_error("DISABLE_EXCEPTION_THROWING was set (probably from -fno-exceptions) but is not compatible with enabling exception catching (DISABLE_EXCEPTION_CATCHING=0). If you don't want exceptions, set DISABLE_EXCEPTION_CATCHING to 1; if you do want exceptions, don't link with -fno-exceptions")
if options.target.startswith('wasm64'):
default_setting('MEMORY64', 1)
if settings.MEMORY64 and options.target.startswith('wasm32'):
exit_with_error('wasm32 target is not compatible with -sMEMORY64')
# Wasm SjLj cannot be used with Emscripten EH
if settings.SUPPORT_LONGJMP == 'wasm':
# DISABLE_EXCEPTION_THROWING is 0 by default for Emscripten EH throwing, but
# Wasm SjLj cannot be used with Emscripten EH. We error out if
# DISABLE_EXCEPTION_THROWING=0 is explicitly requested by the user;
# otherwise we disable it here.
if user_settings.get('DISABLE_EXCEPTION_THROWING') == '0':
exit_with_error('SUPPORT_LONGJMP=wasm cannot be used with DISABLE_EXCEPTION_THROWING=0')
# We error out for DISABLE_EXCEPTION_CATCHING=0, because it is 1 by default
# and this can be 0 only if the user specifies so.
if user_settings.get('DISABLE_EXCEPTION_CATCHING') == '0':
exit_with_error('SUPPORT_LONGJMP=wasm cannot be used with DISABLE_EXCEPTION_CATCHING=0')
default_setting('DISABLE_EXCEPTION_THROWING', 1)
# SUPPORT_LONGJMP=1 means the default SjLj handling mechanism, which is 'wasm'
# if Wasm EH is used and 'emscripten' otherwise.
if settings.SUPPORT_LONGJMP == 1:
if settings.WASM_EXCEPTIONS:
settings.SUPPORT_LONGJMP = 'wasm'
else:
settings.SUPPORT_LONGJMP = 'emscripten'
# SDL2 requires eglGetProcAddress() to work.
# NOTE: if SDL2 is updated to not rely on eglGetProcAddress(), this can be removed
if settings.USE_SDL == 2 or settings.USE_SDL_MIXER == 2 or settings.USE_SDL_GFX == 2:
default_setting('GL_ENABLE_GET_PROC_ADDRESS', 1)
return (newargs, input_files)
def get_clang_output_extension(state):
if '-emit-llvm' in state.orig_args:
if state.has_dash_S:
return '.ll'
else:
return '.bc'
if state.has_dash_S:
return '.s'
else:
return '.o'
def filter_out_link_flags(args):
rtn = []
def is_link_flag(flag):
if flag in ('-nostdlib', '-nostartfiles', '-nolibc', '-nodefaultlibs', '-s'):
return True
return flag.startswith(('-l', '-L', '-Wl,', '-z'))
skip = False
for arg in args:
if skip:
skip = False
continue
if is_link_flag(arg):
continue
if arg == '-Xlinker':
skip = True
continue
rtn.append(arg)
return rtn
@ToolchainProfiler.profile_block('compile inputs')
def phase_compile_inputs(options, state, newargs, input_files):
if shared.run_via_emxx:
compiler = [shared.CLANG_CXX]
else:
compiler = [shared.CLANG_CC]
if config.COMPILER_WRAPPER:
logger.debug('using compiler wrapper: %s', config.COMPILER_WRAPPER)
compiler.insert(0, config.COMPILER_WRAPPER)
compile_args = newargs
system_libs.ensure_sysroot()
def get_language_mode(args):
return_next = False
for item in args:
if return_next:
return item
if item == '-x':
return_next = True
continue
if item.startswith('-x'):
return removeprefix(item, '-x')
return ''
language_mode = get_language_mode(newargs)
use_cxx = 'c++' in language_mode or shared.run_via_emxx
def get_clang_command():