-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathtest_other.py
14650 lines (12804 loc) · 565 KB
/
test_other.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
# coding=utf-8
# Copyright 2013 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.
# noqa: E241
from functools import wraps
import glob
import gzip
import importlib
import itertools
import json
import os
import re
import select
import shlex
import shutil
import subprocess
import sys
import tarfile
import time
from pathlib import Path
from subprocess import PIPE, STDOUT
if __name__ == '__main__':
raise Exception('do not run this file directly; do something like: test/runner other')
from tools.shared import config
from tools.shared import EMCC, EMXX, EMAR, EMRANLIB, FILE_PACKAGER, WINDOWS, LLVM_NM
from tools.shared import CLANG_CC, CLANG_CXX, LLVM_AR, LLVM_DWARFDUMP, LLVM_DWP, EMCMAKE, EMCONFIGURE, WASM_LD
from common import RunnerCore, path_from_root, is_slow_test, ensure_dir, disabled, make_executable
from common import env_modify, no_mac, no_windows, only_windows, requires_native_clang, with_env_modify
from common import create_file, parameterized, NON_ZERO, node_pthreads, TEST_ROOT, test_file
from common import compiler_for, EMBUILDER, requires_v8, requires_node, requires_wasm64, requires_node_canary
from common import requires_wasm_eh, crossplatform, with_both_sjlj, also_with_standalone_wasm
from common import also_with_minimal_runtime, also_with_wasm_bigint, also_with_wasm64, flaky
from common import EMTEST_BUILD_VERBOSE, PYTHON, WEBIDL_BINDER
from common import requires_network
from tools import shared, building, utils, response_file, cache
from tools.utils import read_file, write_file, delete_file, read_binary
import common
import jsrun
import clang_native
from tools import line_endings
from tools import webassembly
from tools.settings import settings
scons_path = shutil.which('scons')
emmake = shared.bat_suffix(path_from_root('emmake'))
emconfig = shared.bat_suffix(path_from_root('em-config'))
emsize = shared.bat_suffix(path_from_root('emsize'))
emprofile = shared.bat_suffix(path_from_root('emprofile'))
emstrip = shared.bat_suffix(path_from_root('emstrip'))
emsymbolizer = shared.bat_suffix(path_from_root('emsymbolizer'))
wasm_opt = Path(building.get_binaryen_bin(), 'wasm-opt')
def uses_canonical_tmp(func):
"""Decorator that signals the use of the canonical temp by a test method.
This decorator takes care of cleaning the directory after the
test to satisfy the leak detector.
"""
@wraps(func)
def decorated(self, *args, **kwargs):
# Before running the test completely remove the canonical_tmp
if os.path.exists(self.canonical_temp_dir):
shutil.rmtree(self.canonical_temp_dir)
try:
func(self, *args, **kwargs)
finally:
# Make sure the test isn't lying about the fact that it uses
# canonical_tmp
self.assertTrue(os.path.exists(self.canonical_temp_dir))
# Remove the temp dir in a try-finally, as otherwise if the
# test fails we would not clean it up, and if leak detection
# is set we will show that error instead of the actual one.
shutil.rmtree(self.canonical_temp_dir)
return decorated
def with_both_compilers(f):
assert callable(f)
f._parameterize = {'': (EMCC,),
'emxx': (EMXX,)}
return f
def also_with_wasmfs(f):
assert callable(f)
@wraps(f)
def metafunc(self, wasmfs):
if wasmfs:
self.set_setting('WASMFS')
self.emcc_args.append('-DWASMFS')
f(self)
else:
f(self)
metafunc._parameterize = {'': (False,),
'wasmfs': (True,)}
return metafunc
def wasmfs_all_backends(f):
def metafunc(self, backend):
self.set_setting('WASMFS')
self.emcc_args.append('-DWASMFS')
self.emcc_args.append(f'-D{backend}')
f(self)
metafunc._parameterize = {'': ('WASMFS_MEMORY_BACKEND',),
'node': ('WASMFS_NODE_BACKEND',)}
return metafunc
def also_with_wasmfs_all_backends(f):
assert callable(f)
@wraps(f)
def metafunc(self, backend):
if backend:
self.set_setting('WASMFS')
self.emcc_args.append('-DWASMFS')
self.emcc_args.append(f'-D{backend}')
f(self)
else:
f(self)
metafunc._parameterize = {'': (None,),
'wasmfs': ('WASMFS_MEMORY_BACKEND',),
'wasmfs_node': ('WASMFS_NODE_BACKEND',)}
return metafunc
def requires_ninja(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
if not shutil.which('ninja'):
self.fail('test requires ninja to be installed (available in PATH)')
return func(self, *args, **kwargs)
return decorated
def requires_scons(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
if not shutil.which('scons'):
if 'EMTEST_SKIP_SCONS' in os.environ:
self.skipTest('test requires scons and EMTEST_SKIP_SCONS is set')
else:
self.fail('scons required to run this test. Use EMTEST_SKIP_SCONS to skip')
return func(self, *args, **kwargs)
return decorated
def requires_pkg_config(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
if not shutil.which('pkg-config'):
if 'EMTEST_SKIP_PKG_CONFIG' in os.environ:
self.skipTest('test requires pkg-config and EMTEST_SKIP_PKG_CONFIG is set')
else:
self.fail('pkg-config is required to run this test')
return func(self, *args, **kwargs)
return decorated
def llvm_nm(file):
output = shared.run_process([LLVM_NM, file], stdout=PIPE).stdout
symbols = {
'defs': set(),
'undefs': set(),
'commons': set(),
}
for line in output.splitlines():
# Skip address, which is always fixed-length 8 chars (plus 2
# leading chars `: ` and one trailing space)
status = line[9]
symbol = line[11:]
if status == 'U':
symbols['undefs'].add(symbol)
elif status == 'C':
symbols['commons'].add(symbol)
elif status == status.upper():
symbols['defs'].add(symbol)
return symbols
def get_file_gzipped_size(f):
f_gz = f + '.gz'
with gzip.open(f_gz, 'wb') as gzf:
gzf.write(read_binary(f))
size = os.path.getsize(f_gz)
delete_file(f_gz)
return size
class other(RunnerCore):
def assertIsObjectFile(self, filename):
self.assertTrue(building.is_wasm(filename))
def assertIsWasmDylib(self, filename):
self.assertTrue(building.is_wasm_dylib(filename))
def do_other_test(self, testname, emcc_args=None, **kwargs):
return self.do_run_in_out_file_test(test_file('other', testname), emcc_args=emcc_args, **kwargs)
def run_on_pty(self, cmd):
master, slave = os.openpty()
output = []
print(cmd)
try:
with env_modify({'TERM': 'xterm-color'}):
proc = subprocess.Popen(cmd, stdout=slave, stderr=slave)
while proc.poll() is None:
r, w, x = select.select([master], [], [], 1)
if r:
output.append(os.read(master, 1024))
return (proc.returncode, b''.join(output))
finally:
os.close(master)
os.close(slave)
def parse_wasm(self, filename):
wat = self.get_wasm_text(filename)
imports = []
exports = []
funcs = []
for line in wat.splitlines():
line = line.strip()
if line.startswith('(import '):
line = line.strip('()')
parts = line.split()
module = parts[1].strip('"')
name = parts[2].strip('"')
imports.append('%s.%s' % (module, name))
if line.startswith('(export '):
line = line.strip('()')
name = line.split()[1].strip('"')
exports.append(name)
if line.startswith('(func '):
line = line.strip('()')
name = line.split()[1].strip('"')
funcs.append(name)
return imports, exports, funcs
# Test that running `emcc -v` always works even in the presence of `EMCC_CFLAGS`.
# This needs to work because many tools run `emcc -v` internally and it should
# always work even if the user has `EMCC_CFLAGS` set.
@with_env_modify({'EMCC_CFLAGS': '-should -be -ignored'})
@with_both_compilers
@crossplatform
def test_emcc_v(self, compiler):
# -v, without input files
proc = self.run_process([compiler, '-v'], stdout=PIPE, stderr=PIPE)
self.assertEqual(proc.stdout, '')
# assert that the emcc message comes first. We had a bug where the sub-process output
# from clang would be flushed to stderr first.
self.assertContained('emcc (Emscripten gcc/clang-like replacement', proc.stderr)
self.assertTrue(proc.stderr.startswith('emcc (Emscripten gcc/clang-like replacement'))
self.assertContained('clang version ', proc.stderr)
self.assertContained('GNU', proc.stderr)
self.assertContained('Target: wasm32-unknown-emscripten', proc.stderr)
self.assertNotContained('this is dangerous', proc.stderr)
def test_log_subcommands(self):
# `-v` when combined with other arguments will trace the subcommands
# that get run
proc = self.run_process([EMCC, '-v', test_file('hello_world.c')], stdout=PIPE, stderr=PIPE)
self.assertContained(CLANG_CC, proc.stderr)
self.assertContained(WASM_LD, proc.stderr)
self.assertExists('a.out.js')
def test_skip_subcommands(self):
# The -### flag is like `-v` but it doesn't actaully execute the sub-commands
proc = self.run_process([EMCC, '-###', test_file('hello_world.c')], stdout=PIPE, stderr=PIPE)
self.assertContained(CLANG_CC, proc.stderr)
self.assertContained(WASM_LD, proc.stderr)
self.assertNotExists('a.out.js')
def test_emcc_check(self):
proc = self.run_process([EMCC, '--check'], stdout=PIPE, stderr=PIPE)
self.assertEqual(proc.stdout, '')
self.assertContained('emcc (Emscripten gcc/clang-like replacement', proc.stderr)
self.assertContained('Running sanity checks', proc.stderr)
proc = self.run_process([EMCC, '--check'], stdout=PIPE, stderr=PIPE)
self.assertContained('Running sanity checks', proc.stderr)
@with_both_compilers
def test_emcc_generate_config(self, compiler):
config_path = './emscripten_config'
with env_modify({'EM_CONFIG': config_path}):
self.assertNotExists(config_path)
self.run_process([compiler, '--generate-config'])
self.assertExists(config_path)
config_contents = read_file(config_path)
self.assertContained('LLVM_ROOT', config_contents)
os.remove(config_path)
@parameterized({
'': ([],),
'node': (['-sENVIRONMENT=node'],),
})
def test_emcc_output_mjs(self, args):
create_file('extern-post.js', 'await Module();')
self.run_process([EMCC, '-o', 'hello_world.mjs',
'--extern-post-js', 'extern-post.js',
test_file('hello_world.c')] + args)
src = read_file('hello_world.mjs')
self.assertContained('export default Module;', src)
self.assertContained('hello, world!', self.run_js('hello_world.mjs'))
@parameterized({
'': ([],),
'node': (['-sENVIRONMENT=node'],),
})
@node_pthreads
def test_emcc_output_worker_mjs(self, args):
create_file('extern-post.js', 'await Module();')
os.mkdir('subdir')
self.run_process([EMCC, '-o', 'subdir/hello_world.mjs',
'-sEXIT_RUNTIME', '-sPROXY_TO_PTHREAD', '-pthread', '-O1',
'--extern-post-js', 'extern-post.js',
test_file('hello_world.c')] + args)
src = read_file('subdir/hello_world.mjs')
self.assertContained("new URL('hello_world.wasm', import.meta.url)", src)
self.assertContained("new Worker(new URL('hello_world.worker.mjs', import.meta.url), {type: 'module'})", src)
self.assertContained("new Worker(pthreadMainJs, {type: 'module'})", src)
self.assertContained('export default Module;', src)
src = read_file('subdir/hello_world.worker.mjs')
self.assertContained("import('./hello_world.mjs')", src)
self.assertContained('hello, world!', self.run_js('subdir/hello_world.mjs'))
@node_pthreads
def test_emcc_output_worker_mjs_single_file(self):
create_file('extern-post.js', 'await Module();')
self.run_process([EMCC, '-o', 'hello_world.mjs', '-pthread',
'--extern-post-js', 'extern-post.js',
test_file('hello_world.c'), '-sSINGLE_FILE'])
src = read_file('hello_world.mjs')
self.assertNotContained("new URL('data:", src)
self.assertContained("new Worker(new URL('hello_world.worker.mjs', import.meta.url), {type: 'module'})", src)
self.assertContained("new Worker(pthreadMainJs, {type: 'module'})", src)
self.assertContained('hello, world!', self.run_js('hello_world.mjs'))
def test_emcc_output_mjs_closure(self):
create_file('extern-post.js', 'await Module();')
self.run_process([EMCC, '-o', 'hello_world.mjs',
'--extern-post-js', 'extern-post.js',
test_file('hello_world.c'), '--closure=1'])
src = read_file('hello_world.mjs')
self.assertContained('new URL("hello_world.wasm", import.meta.url)', src)
self.assertContained('hello, world!', self.run_js('hello_world.mjs'))
def test_emcc_output_mjs_web_no_import_meta(self):
# Ensure we don't emit import.meta.url at all for:
# ENVIRONMENT=web + EXPORT_ES6 + USE_ES6_IMPORT_META=0
self.run_process([EMCC, '-o', 'hello_world.mjs',
test_file('hello_world.c'),
'-sENVIRONMENT=web', '-sUSE_ES6_IMPORT_META=0'])
src = read_file('hello_world.mjs')
self.assertNotContained('import.meta.url', src)
self.assertContained('export default Module;', src)
def test_export_es6_implies_modularize(self):
self.run_process([EMCC, test_file('hello_world.c'), '-sEXPORT_ES6'])
src = read_file('a.out.js')
self.assertContained('export default Module;', src)
def test_export_es6_requires_modularize(self):
err = self.expect_fail([EMCC, test_file('hello_world.c'), '-sEXPORT_ES6', '-sMODULARIZE=0'])
self.assertContained('EXPORT_ES6 requires MODULARIZE to be set', err)
def test_export_es6_node_requires_import_meta(self):
err = self.expect_fail([EMCC, test_file('hello_world.c'),
'-sENVIRONMENT=node', '-sEXPORT_ES6', '-sUSE_ES6_IMPORT_META=0'])
self.assertContained('EXPORT_ES6 and ENVIRONMENT=*node* requires USE_ES6_IMPORT_META to be set', err)
def test_export_es6_allows_export_in_post_js(self):
self.run_process([EMCC, test_file('hello_world.c'), '-O3', '-sEXPORT_ES6', '--post-js', test_file('export_module.js')])
src = read_file('a.out.js')
self.assertContained('export{doNothing};', src)
@parameterized({
'': (False,),
'package_json': (True,),
})
@parameterized({
'': ([],),
# load a worker before startup to check ES6 modules there as well
# pass -O2 to ensure the worker JS file is minified with Acorn
'pthreads': (['-O2', '-pthread', '-sPTHREAD_POOL_SIZE=1'],),
})
def test_export_es6(self, args, package_json):
self.run_process([EMCC, test_file('hello_world.c'), '-sEXPORT_ES6',
'-o', 'hello.mjs'] + args)
# In ES6 mode we use MODULARIZE, so we must instantiate an instance of the
# module to run it.
create_file('runner.mjs', '''
import Hello from "./hello.mjs";
Hello();
''')
if package_json:
# This makes node load all files in the directory as ES6 modules,
# including the worker.js file.
create_file('package.json', '{"type":"module"}')
self.assertContained('hello, world!', self.run_js('runner.mjs'))
def test_emcc_out_file(self):
# Verify that "-ofile" works in addition to "-o" "file"
self.run_process([EMCC, '-c', '-ofoo.o', test_file('hello_world.c')])
self.assertExists('foo.o')
self.run_process([EMCC, '-ofoo.js', 'foo.o'])
self.assertExists('foo.js')
@parameterized({
'c': [EMCC, '.c'],
'cxx': [EMXX, '.cpp'],
})
def test_emcc_basics(self, compiler, suffix):
# emcc src.cpp ==> writes a.out.js and a.out.wasm
self.run_process([compiler, test_file('hello_world' + suffix)])
self.assertExists('a.out.js')
self.assertExists('a.out.wasm')
self.assertContained('hello, world!', self.run_js('a.out.js'))
# --version
output = self.run_process([compiler, '--version'], stdout=PIPE, stderr=PIPE)
output = output.stdout.replace('\r', '')
self.assertContained('emcc (Emscripten gcc/clang-like replacement', output)
self.assertContained('''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.
''', output)
# --help
output = self.run_process([compiler, '--help'], stdout=PIPE, stderr=PIPE)
self.assertContained('Display this information', output.stdout)
self.assertContained('Most clang options will work', output.stdout)
# -dumpversion
output = self.run_process([compiler, '-dumpversion'], stdout=PIPE, stderr=PIPE)
self.assertEqual(shared.EMSCRIPTEN_VERSION, output.stdout.strip())
# properly report source code errors, and stop there
self.clear()
stderr = self.expect_fail([compiler, test_file('hello_world_error' + suffix)])
self.assertNotContained('IOError', stderr) # no python stack
self.assertNotContained('Traceback', stderr) # no python stack
self.assertContained('error: invalid preprocessing directive', stderr)
self.assertContained(["error: use of undeclared identifier 'cheez", "error: unknown type name 'cheez'"], stderr)
self.assertContained('errors generated.', stderr.splitlines()[-2])
def test_dumpmachine(self):
output = self.run_process([EMCC, '-dumpmachine'], stdout=PIPE, stderr=PIPE).stdout
self.assertContained('wasm32-unknown-emscripten', output)
# Test the -print-target-triple llvm alias for -dumpmachine
output = self.run_process([EMCC, '-print-target-triple'], stdout=PIPE, stderr=PIPE).stdout
self.assertContained('wasm32-unknown-emscripten', output)
output = self.run_process([EMCC, '--print-target-triple'], stdout=PIPE, stderr=PIPE).stdout
self.assertContained('wasm32-unknown-emscripten', output)
# Test that -sMEMORY64 triggers the wasm64 triple
output = self.run_process([EMCC, '-sMEMORY64', '-dumpmachine'], stdout=PIPE, stderr=PIPE).stdout
self.assertContained('wasm64-unknown-emscripten', output)
@parameterized({
'c': [EMCC, '.c'],
'cxx': [EMXX, '.cpp']})
def test_emcc_2(self, compiler, suffix):
# emcc src.cpp -c and emcc -c src.cpp -o src.[o|foo|so] ==> should always give an object file
for args in [[], ['-o', 'src.o'], ['-o', 'src.foo'], ['-o', 'src.so']]:
print('args:', args)
target = args[1] if len(args) == 2 else 'hello_world.o'
self.clear()
self.run_process([compiler, '-c', test_file('hello_world' + suffix)] + args)
self.assertIsObjectFile(target)
syms = llvm_nm(target)
self.assertIn('main', syms['defs'])
# we also expect to have the '__original_main' wrapper and __main_void alias.
# TODO(sbc): Should be 4 once https://reviews.llvm.org/D75277 lands
self.assertIn(len(syms['defs']), (2, 3))
self.run_process([compiler, target, '-o', target + '.js'])
self.assertContained('hello, world!', self.run_js(target + '.js'))
def test_bc_output_warning(self):
err = self.run_process([EMCC, '-c', test_file('hello_world.c'), '-o', 'out.bc'], stderr=PIPE).stderr
self.assertContained('emcc: warning: .bc output file suffix used without -flto or -emit-llvm', err)
@parameterized({
'c': [EMCC, '.c'],
'cxx': [EMXX, '.cpp']})
def test_emcc_3(self, compiler, suffix):
# handle singleton archives
self.run_process([compiler, '-c', test_file('hello_world' + suffix), '-o', 'a.o'])
self.run_process([LLVM_AR, 'r', 'a.a', 'a.o'], stdout=PIPE, stderr=PIPE)
self.run_process([compiler, 'a.a'])
self.assertContained('hello, world!', self.run_js('a.out.js'))
# emcc [..] -o [path] ==> should work with absolute paths
for path in [os.path.abspath(Path('../file1.js')), Path('b_dir/file2.js')]:
print(path)
os.chdir(self.get_dir())
self.clear()
print(os.listdir(os.getcwd()))
ensure_dir('a_dir/b_dir')
os.chdir('a_dir')
# use single file so we don't have more files to clean up
self.run_process([compiler, test_file('hello_world' + suffix), '-o', path, '-sSINGLE_FILE'])
last = os.getcwd()
os.chdir(os.path.dirname(path))
self.assertContained('hello, world!', self.run_js(os.path.basename(path)))
os.chdir(last)
delete_file(path)
@is_slow_test
@parameterized({
'c': [EMCC],
'cxx': [EMXX]})
def test_emcc_4(self, compiler):
# Optimization: emcc src.cpp -o something.js [-Ox]. -O0 is the same as not specifying any optimization setting
# link_param are used after compiling first
for params, opt_level, link_params, closure, has_malloc in [
(['-o', 'something.js'], 0, None, 0, 1),
(['-o', 'something.js', '-O0', '-g'], 0, None, 0, 0),
(['-o', 'something.js', '-O1'], 1, None, 0, 0),
(['-o', 'something.js', '-O1', '-g'], 1, None, 0, 0), # no closure since debug
(['-o', 'something.js', '-O2'], 2, None, 0, 1),
(['-o', 'something.js', '-O2', '-g'], 2, None, 0, 0),
(['-o', 'something.js', '-Os'], 2, None, 0, 1),
(['-o', 'something.js', '-O3'], 3, None, 0, 1),
# and, test compiling first
(['-c', '-o', 'something.o'], 0, [], 0, 0),
(['-c', '-o', 'something.o', '-O0'], 0, [], 0, 0),
(['-c', '-o', 'something.o', '-O1'], 1, ['-O1'], 0, 0),
(['-c', '-o', 'something.o', '-O2'], 2, ['-O2'], 0, 0),
(['-c', '-o', 'something.o', '-O3'], 3, ['-O3'], 0, 0),
(['-O1', '-c', '-o', 'something.o'], 1, [], 0, 0),
# non-wasm
(['-sWASM=0', '-o', 'something.js'], 0, None, 0, 1),
(['-sWASM=0', '-o', 'something.js', '-O0', '-g'], 0, None, 0, 0),
(['-sWASM=0', '-o', 'something.js', '-O1'], 1, None, 0, 0),
(['-sWASM=0', '-o', 'something.js', '-O1', '-g'], 1, None, 0, 0), # no closure since debug
(['-sWASM=0', '-o', 'something.js', '-O2'], 2, None, 0, 1),
(['-sWASM=0', '-o', 'something.js', '-O2', '-g'], 2, None, 0, 0),
(['-sWASM=0', '-o', 'something.js', '-Os'], 2, None, 0, 1),
(['-sWASM=0', '-o', 'something.js', '-O3'], 3, None, 0, 1),
# and, test compiling to bitcode first
(['-flto', '-c', '-o', 'something.o'], 0, [], 0, 0),
(['-flto', '-c', '-o', 'something.o', '-O0'], 0, [], 0, 0),
(['-flto', '-c', '-o', 'something.o', '-O1'], 1, ['-O1'], 0, 0),
(['-flto', '-c', '-o', 'something.o', '-O2'], 2, ['-O2'], 0, 0),
(['-flto', '-c', '-o', 'something.o', '-O3'], 3, ['-O3'], 0, 0),
(['-flto', '-O1', '-c', '-o', 'something.o'], 1, [], 0, 0),
]:
print(params, opt_level, link_params, closure, has_malloc)
self.clear()
keep_debug = '-g' in params
if has_malloc:
filename = test_file('hello_world_loop_malloc.c')
else:
filename = test_file('hello_world_loop.c')
args = [compiler, filename] + params
print('..', args)
output = self.run_process(args, stdout=PIPE, stderr=PIPE)
assert len(output.stdout) == 0, output.stdout
if link_params is not None:
self.assertExists('something.o', output.stderr)
obj_args = [compiler, 'something.o', '-o', 'something.js'] + link_params
print('....', obj_args)
output = self.run_process(obj_args, stdout=PIPE, stderr=PIPE)
self.assertExists('something.js', output.stderr)
self.assertContained('hello, world!', self.run_js('something.js'))
# Verify optimization level etc. in the generated code
# XXX these are quite sensitive, and will need updating when code generation changes
generated = read_file('something.js')
main = self.get_func(generated, '_main') if 'function _main' in generated else generated
assert 'new Uint16Array' in generated and 'new Uint32Array' in generated, 'typed arrays 2 should be used by default'
assert 'SAFE_HEAP_LOAD' not in generated, 'safe heap should not be used by default'
assert 'SAFE_HEAP_STORE' not in generated, 'safe heap should not be used by default'
assert ': while(' not in main, 'when relooping we also js-optimize, so there should be no labelled whiles'
if closure:
if opt_level == 0:
assert '._main =' in generated, 'closure compiler should have been run'
elif opt_level >= 1:
assert '._main=' in generated, 'closure compiler should have been run (and output should be minified)'
else:
# closure has not been run, we can do some additional checks. TODO: figure out how to do these even with closure
assert '._main = ' not in generated, 'closure compiler should not have been run'
if keep_debug:
self.assertContainedIf("assert(!Module['STACK_SIZE']", generated, opt_level == 0)
if 'WASM=0' in params:
looks_unminified = ' = {}' in generated and ' = []' in generated
looks_minified = '={}' in generated and '=[]' and ';var' in generated
assert not (looks_minified and looks_unminified)
if opt_level == 0 or '-g' in params:
assert looks_unminified
elif opt_level >= 2:
assert looks_minified
def test_multiple_sources(self):
# Compiling two sources at a time should work.
cmd = [EMCC, '-c', test_file('twopart_main.cpp'), test_file('twopart_side.c')]
self.run_process(cmd)
# Object files should be generated by default in the current working
# directory, and not alongside the sources.
self.assertExists('twopart_main.o')
self.assertExists('twopart_side.o')
self.assertNotExists(test_file('twopart_main.o'))
self.assertNotExists(test_file('twopart_side.o'))
# But it is an error if '-o' is also specified.
self.clear()
err = self.expect_fail(cmd + ['-o', 'out.o'])
self.assertContained('clang: error: cannot specify -o when generating multiple output files', err)
self.assertNotExists('twopart_main.o')
self.assertNotExists('twopart_side.o')
self.assertNotExists(test_file('twopart_main.o'))
self.assertNotExists(test_file('twopart_side.o'))
def test_tsearch(self):
self.do_other_test('test_tsearch.c')
@crossplatform
def test_libc_progname(self):
self.do_other_test('test_libc_progname.c')
def test_combining_object_files(self):
# Compiling two files with -c will generate separate object files
self.run_process([EMCC, test_file('twopart_main.cpp'), test_file('twopart_side.c'), '-c'])
self.assertExists('twopart_main.o')
self.assertExists('twopart_side.o')
# Linking with just one of them is expected to fail
err = self.expect_fail([EMCC, 'twopart_main.o'])
self.assertContained('undefined symbol: theFunc', err)
# Linking with both should work
self.run_process([EMCC, 'twopart_main.o', 'twopart_side.o'])
self.assertContained('side got: hello from main, over', self.run_js('a.out.js'))
# Combining object files into another object should also work, using the `-r` flag
err = self.run_process([EMCC, '-r', 'twopart_main.o', 'twopart_side.o', '-o', 'combined.o'], stderr=PIPE).stderr
self.assertNotContained('warning:', err)
# Warn about legecy support for outputing object file without `-r`, `-c` or `-shared`
err = self.run_process([EMCC, 'twopart_main.o', 'twopart_side.o', '-o', 'combined2.o'], stderr=PIPE).stderr
self.assertContained('warning: object file output extension (.o) used for non-object output', err)
# Should be two symbols (and in the wasm backend, also __original_main)
syms = llvm_nm('combined.o')
self.assertIn('main', syms['defs'])
# TODO(sbc): Should be 4 once https://reviews.llvm.org/D75277 lands
self.assertIn(len(syms['defs']), (4, 3))
self.run_process([EMCC, 'combined.o', '-o', 'combined.o.js'])
self.assertContained('side got: hello from main, over', self.run_js('combined.o.js'))
def test_combining_object_files_from_archive(self):
# Compiling two files with -c will generate separate object files
self.run_process([EMCC, test_file('twopart_main.cpp'), test_file('twopart_side.c'), '-c'])
self.assertExists('twopart_main.o')
self.assertExists('twopart_side.o')
# Combining object files into a library archive should work
self.run_process([EMAR, 'crs', 'combined.a', 'twopart_main.o', 'twopart_side.o'])
self.assertExists('combined.a')
# Combining library archive into an object should yield a valid object, using the `-r` flag
self.run_process([EMXX, '-r', '-o', 'combined.o', '-Wl,--whole-archive', 'combined.a'])
self.assertIsObjectFile('combined.o')
# Should be two symbols (and in the wasm backend, also __original_main)
syms = llvm_nm('combined.o')
self.assertIn('main', syms['defs'])
# TODO(sbc): Should be 3 once https://reviews.llvm.org/D75277 lands
self.assertIn(len(syms['defs']), (3, 4))
self.run_process([EMXX, 'combined.o', '-o', 'combined.o.js'])
self.assertContained('side got: hello from main, over', self.run_js('combined.o.js'))
def test_js_transform(self):
create_file('t.py', '''
import sys
f = open(sys.argv[1], 'a')
f.write('transformed!')
f.close()
''')
err = self.run_process([EMCC, test_file('hello_world.c'), '-gsource-map', '--js-transform', '%s t.py' % (PYTHON)], stderr=PIPE).stderr
self.assertContained('disabling source maps because a js transform is being done', err)
self.assertIn('transformed!', read_file('a.out.js'))
@parameterized({
'': [[]],
'O1': [['-O1']],
'O2': [['-O2']],
'O3': [['-O3']],
})
def test_emcc_asm_v_wasm(self, opts):
for mode in ([], ['-sWASM=0']):
self.clear()
wasm = '=0' not in str(mode)
print(' mode', mode, 'wasm?', wasm)
self.run_process([EMCC, test_file('hello_world.c'), '-sENVIRONMENT=node,shell'] + opts + mode)
self.assertExists('a.out.js')
if wasm:
self.assertExists('a.out.wasm')
for engine in config.JS_ENGINES:
print(' engine', engine)
out = self.run_js('a.out.js', engine=engine)
self.assertContained('hello, world!', out)
@crossplatform
def test_emcc_cflags(self):
output = self.run_process([EMCC, '--cflags'], stdout=PIPE)
flags = output.stdout.strip()
self.assertContained('-target wasm32-unknown-emscripten', flags)
self.assertContained('--sysroot=', flags)
output = self.run_process([EMXX, '--cflags'], stdout=PIPE)
flags = output.stdout.strip()
self.assertContained('-target wasm32-unknown-emscripten', flags)
self.assertContained('--sysroot=', flags)
# check they work
cmd = [CLANG_CC, test_file('hello_world.c')] + shlex.split(flags.replace('\\', '\\\\')) + ['-c', '-o', 'out.o']
self.run_process(cmd)
self.run_process([EMCC, 'out.o'])
self.assertContained('hello, world!', self.run_js('a.out.js'))
@crossplatform
@parameterized({
'': [[]],
'lto': [['-flto']],
'wasm64': [['-sMEMORY64']],
})
def test_print_search_dirs(self, args):
output = self.run_process([EMCC, '-print-search-dirs'] + args, stdout=PIPE).stdout
output2 = self.run_process([EMCC, '-print-search-dirs'] + args, stdout=PIPE).stdout
self.assertEqual(output, output2)
self.assertContained('programs: =', output)
self.assertContained('libraries: =', output)
libpath = output.split('libraries: =', 1)[1].strip()
libpath = libpath.split(os.pathsep)
libpath = [Path(p) for p in libpath]
settings.LTO = '-flto' in args
settings.MEMORY64 = int('-sMEMORY64' in args)
expected = cache.get_lib_dir(absolute=True)
self.assertIn(expected, libpath)
@crossplatform
@parameterized({
'': [[]],
'lto': [['-flto']],
'wasm64': [['-sMEMORY64']],
})
def test_print_libgcc_file_name(self, args):
output = self.run_process([EMCC, '-print-libgcc-file-name'] + args, stdout=PIPE).stdout
output2 = self.run_process([EMCC, '--print-libgcc-file-name'] + args, stdout=PIPE).stdout
self.assertEqual(output, output2)
settings.LTO = '-flto' in args
settings.MEMORY64 = int('-sMEMORY64' in args)
libdir = cache.get_lib_dir(absolute=True)
expected = os.path.join(libdir, 'libcompiler_rt.a')
self.assertEqual(output.strip(), expected)
@crossplatform
@parameterized({
'': [[]],
'lto': [['-flto']],
'wasm64': [['-sMEMORY64', '-Wno-experimental']],
})
def test_print_file_name(self, args):
# make sure the corresponding version of libc exists in the cache
self.run_process([EMCC, test_file('hello_world.c'), '-O2'] + args)
output = self.run_process([EMCC, '-print-file-name=libc.a'] + args, stdout=PIPE).stdout
output2 = self.run_process([EMCC, '--print-file-name=libc.a'] + args, stdout=PIPE).stdout
self.assertEqual(output, output2)
filename = Path(output)
settings.LTO = '-flto' in args
settings.MEMORY64 = int('-sMEMORY64' in args)
self.assertContained(cache.get_lib_name('libc.a'), str(filename))
def test_emar_em_config_flag(self):
# Test that the --em-config flag is accepted but not passed down do llvm-ar.
# We expand this in case the EM_CONFIG is ~/.emscripten (default)
conf = os.path.expanduser(config.EM_CONFIG)
proc = self.run_process([EMAR, '--em-config', conf, '--version'], stdout=PIPE, stderr=PIPE)
self.assertEqual(proc.stderr, "")
self.assertContained('LLVM', proc.stdout)
def test_em_config_missing_arg(self):
out = self.expect_fail([EMCC, '--em-config'])
self.assertContained('error: --em-config must be followed by a filename', out)
def test_emsize(self):
# test binaryen generated by running:
# emcc test/hello_world.c -Oz --closure 1 -o test/other/test_emsize.js
expected = read_file(test_file('other/test_emsize.out'))
cmd = [emsize, test_file('other/test_emsize.js')]
for command in [cmd, cmd + ['--format=sysv']]:
output = self.run_process(command, stdout=PIPE).stdout
self.assertContained(expected, output)
def test_emstrip(self):
self.run_process([EMCC, test_file('hello_world.c'), '-g', '-o', 'hello.js'])
output = self.run_process([common.LLVM_OBJDUMP, '-h', 'hello.wasm'], stdout=PIPE).stdout
self.assertContained('.debug_info', output)
self.run_process([emstrip, 'hello.wasm'])
output = self.run_process([common.LLVM_OBJDUMP, '-h', 'hello.wasm'], stdout=PIPE).stdout
self.assertNotContained('.debug_info', output)
@is_slow_test
@crossplatform
@parameterized({
# ('directory to the test', 'output filename', ['extra args to pass to
# CMake']) Testing all combinations would be too much work and the test
# would take 10 minutes+ to finish (CMake feature detection is slow), so
# combine multiple features into one to try to cover as much as possible
# while still keeping this test in sensible time limit.
'js': ('target_js', 'test_cmake.js', ['-DCMAKE_BUILD_TYPE=Debug']),
'html': ('target_html', 'hello_world_gles.html', ['-DCMAKE_BUILD_TYPE=Release']),
'library': ('target_library', 'libtest_cmake.a', ['-DCMAKE_BUILD_TYPE=MinSizeRel']),
'static_cpp': ('target_library', 'libtest_cmake.a', ['-DCMAKE_BUILD_TYPE=RelWithDebInfo', '-DCPP_LIBRARY_TYPE=STATIC']),
'stdproperty': ('stdproperty', 'helloworld.js', []),
'post_build': ('post_build', 'hello.js', []),
})
def test_cmake(self, test_dir, output_file, cmake_args):
# Test all supported generators.
if WINDOWS:
generators = ['MinGW Makefiles', 'NMake Makefiles']
else:
generators = ['Unix Makefiles', 'Ninja', 'Eclipse CDT4 - Ninja']
configurations = {
'MinGW Makefiles' : {'build' : ['mingw32-make'] }, # noqa
'NMake Makefiles' : {'build' : ['nmake', '/NOLOGO']}, # noqa
'Unix Makefiles' : {'build' : ['make']}, # noqa
'Ninja' : {'build' : ['ninja']}, # noqa
'Eclipse CDT4 - Ninja': {'build' : ['ninja']}, # noqa
}
for generator in generators:
conf = configurations[generator]
if not shutil.which(conf['build'][0]):
# Use simple test if applicable
print('Skipping %s test for CMake support; build tool found found: %s.' % (generator, conf['build'][0]))
continue
cmakelistsdir = test_file('cmake', test_dir)
builddir = 'out_' + generator.replace(' ', '_').lower()
os.mkdir(builddir)
with utils.chdir(builddir):
# Run Cmake
cmd = [EMCMAKE, 'cmake'] + cmake_args + ['-G', generator, cmakelistsdir]
env = os.environ.copy()
# https://github.com/emscripten-core/emscripten/pull/5145: Check that CMake works even if EMCC_SKIP_SANITY_CHECK=1 is passed.
if test_dir == 'target_html':
env['EMCC_SKIP_SANITY_CHECK'] = '1'
print(str(cmd))
self.run_process(cmd, env=env, stdout=None if EMTEST_BUILD_VERBOSE >= 2 else PIPE, stderr=None if EMTEST_BUILD_VERBOSE >= 1 else PIPE)
# Build
cmd = conf['build']
if EMTEST_BUILD_VERBOSE >= 3 and 'Ninja' not in generator:
cmd += ['VERBOSE=1']
self.run_process(cmd, stdout=None if EMTEST_BUILD_VERBOSE >= 2 else PIPE)
self.assertExists(output_file, 'building a cmake-generated Makefile failed to produce an output file %s!' % output_file)
# Run through node, if CMake produced a .js file.
if output_file.endswith('.js'):
ret = self.run_js(output_file)
self.assertTextDataIdentical(read_file(cmakelistsdir + '/out.txt').strip(), ret.strip())
if test_dir == 'post_build':
ret = self.run_process(['ctest'], env=env)
# Test that the various CMAKE_xxx_COMPILE_FEATURES that are advertised for the Emscripten
# toolchain match with the actual language features that Clang supports.
# If we update LLVM version and this test fails, copy over the new advertised features from Clang
# and place them to cmake/Modules/Platform/Emscripten.cmake.
@no_windows('Skipped on Windows because CMake does not configure native Clang builds well on Windows.')
def test_cmake_compile_features(self):
os.mkdir('build_native')
cmd = ['cmake',
'-DCMAKE_C_COMPILER=' + CLANG_CC, '-DCMAKE_C_FLAGS=--target=' + clang_native.get_native_triple(),
'-DCMAKE_CXX_COMPILER=' + CLANG_CXX, '-DCMAKE_CXX_FLAGS=--target=' + clang_native.get_native_triple(),
test_file('cmake/stdproperty')]
print(str(cmd))
native_features = self.run_process(cmd, stdout=PIPE, cwd='build_native').stdout
os.mkdir('build_emcc')
cmd = [EMCMAKE, 'cmake', test_file('cmake/stdproperty')]
print(str(cmd))
emscripten_features = self.run_process(cmd, stdout=PIPE, cwd='build_emcc').stdout
native_features = '\n'.join([x for x in native_features.split('\n') if '***' in x])
emscripten_features = '\n'.join([x for x in emscripten_features.split('\n') if '***' in x])
self.assertTextDataIdentical(native_features, emscripten_features)
# Test that the user's explicitly specified generator is always honored
# Internally we override the generator on windows, unles the user specifies one
# Test require Ninja to be installed
@requires_ninja
def test_cmake_explicit_generator(self):
# use -Wno-dev to suppress an irrelevant warning about the test files only.
cmd = [EMCMAKE, 'cmake', '-GNinja', '-Wno-dev', test_file('cmake/cpp_lib')]
self.run_process(cmd)
self.assertExists(self.get_dir() + '/build.ninja')
# Tests that it's possible to pass C++11 or GNU++11 build modes to CMake by building code that
# needs C++11 (embind)
@requires_ninja
def test_cmake_with_embind_cpp11_mode(self):
for args in [[], ['-DNO_GNU_EXTENSIONS=1']]:
self.clear()
# Use ninja generator here since we assume its always installed on our build/test machines.
configure = [EMCMAKE, 'cmake', '-GNinja', test_file('cmake/cmake_with_emval')] + args
print(str(configure))
self.run_process(configure)
build = ['cmake', '--build', '.']
print(str(build))
self.run_process(build)
out = self.run_js('cmake_with_emval.js')
if '-DNO_GNU_EXTENSIONS=1' in args:
self.assertContained('Hello! __STRICT_ANSI__: 1, __cplusplus: 201103', out)
else:
self.assertContained('Hello! __STRICT_ANSI__: 0, __cplusplus: 201103', out)
# Tests that the Emscripten CMake toolchain option
def test_cmake_bitcode_static_libraries(self):
# Test that this option produces an error
err = self.expect_fail([EMCMAKE, 'cmake', test_file('cmake/static_lib'), '-DEMSCRIPTEN_GENERATE_BITCODE_STATIC_LIBRARIES=ON'])
self.assertContained('EMSCRIPTEN_GENERATE_BITCODE_STATIC_LIBRARIES is not compatible with the', err)
@parameterized({
'': ['0'],
'_suffix': ['1'],
})
def test_cmake_static_lib(self, custom):
# Test that one is able to use custom suffixes for static libraries.
# (sometimes projects want to emulate stuff, and do weird things like files
# with ".so" suffix which are in fact either ar archives or bitcode files)
self.run_process([EMCMAKE, 'cmake', f'-DSET_CUSTOM_SUFFIX_IN_PROJECT={custom}', test_file('cmake/static_lib')])
self.run_process(['cmake', '--build', '.'])
if custom == '1':
self.assertTrue(building.is_ar('myprefix_static_lib.somecustomsuffix'))
else:
self.assertTrue(building.is_ar('libstatic_lib.a'))
# Tests that cmake functions which require evaluation via the node runtime run properly with pthreads
def test_cmake_pthreads(self):
self.run_process([EMCMAKE, 'cmake', '-DCMAKE_C_FLAGS=-pthread', test_file('cmake/target_js')])
# Tests that the CMake variable EMSCRIPTEN_VERSION is properly provided to user CMake scripts
def test_cmake_emscripten_version(self):
self.run_process([EMCMAKE, 'cmake', test_file('cmake/emscripten_version')])
self.clear()
self.run_process([EMCMAKE, 'cmake', test_file('cmake/emscripten_version'), '-DEMSCRIPTEN_FORCE_COMPILERS=OFF'])
def test_cmake_emscripten_system_processor(self):
cmake_dir = test_file('cmake/emscripten_system_processor')
# The default CMAKE_SYSTEM_PROCESSOR is x86.
out = self.run_process([EMCMAKE, 'cmake', cmake_dir], stdout=PIPE).stdout
self.assertContained('CMAKE_SYSTEM_PROCESSOR is x86', out)
# It can be overridden by setting EMSCRIPTEN_SYSTEM_PROCESSOR.
out = self.run_process(
[EMCMAKE, 'cmake', cmake_dir, '-DEMSCRIPTEN_SYSTEM_PROCESSOR=arm'], stdout=PIPE).stdout
self.assertContained('CMAKE_SYSTEM_PROCESSOR is arm', out)
@requires_network
def test_cmake_find_stuff(self):