Skip to content

Commit fd71dae

Browse files
authored
optional param to prevent function overwriting (#16364)
1 parent e98561b commit fd71dae

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/utility.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,23 @@ function sum(x) {
8686
return x.reduce((a, b) => a + b, 0);
8787
}
8888

89-
function mergeInto(obj, other) {
89+
// options is optional input object containing mergeInto params
90+
// currently, it can contain
91+
//
92+
// key: noOverride, value: true
93+
// if it is set, it prevents symbol redefinition and shows error
94+
// in case of redefinition
95+
function mergeInto(obj, other, options = null) {
96+
// check for unintended symbol redefinition
97+
if (options && options.noOverride) {
98+
for (const key of Object.keys(other)) {
99+
if (obj.hasOwnProperty(key)) {
100+
error('Symbol re-definition in JavaScript library: ' + key + '. Do not use noOverride if this is intended');
101+
return;
102+
}
103+
}
104+
}
105+
90106
return Object.assign(obj, other);
91107
}
92108

tests/test_other.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3404,6 +3404,38 @@ def test_compilation_database(self):
34043404
self.run_process([EMCC, 'a.c', '-MJ', 'hello.json', '-c', '-o', 'test.o'])
34053405
self.assertContained('"file": "a.c", "output": "test.o"', read_file('hello.json'))
34063406

3407+
def test_duplicate_js_functions(self):
3408+
create_file('duplicated_func.c', '''
3409+
#include <stdio.h>
3410+
extern int duplicatedFunc();
3411+
3412+
int main() {
3413+
int res = duplicatedFunc();
3414+
printf("*%d*\\n", res);
3415+
return 0;
3416+
}
3417+
''')
3418+
create_file('duplicated_func_1.js', '''
3419+
mergeInto(LibraryManager.library, {
3420+
duplicatedFunc : function() {
3421+
return 1;
3422+
}
3423+
}, { noOverride: true }
3424+
);
3425+
''')
3426+
create_file('duplicated_func_2.js', '''
3427+
mergeInto(LibraryManager.library, {
3428+
duplicatedFunc : function() {
3429+
return 2;
3430+
}
3431+
}, { noOverride: true }
3432+
);
3433+
''')
3434+
3435+
self.emcc_args += ['--js-library', 'duplicated_func_1.js', '--js-library', 'duplicated_func_2.js']
3436+
err = self.expect_fail([EMCC, 'duplicated_func.c'] + self.get_emcc_args())
3437+
self.assertContained('error: Symbol re-definition in JavaScript library: duplicatedFunc. Do not use noOverride if this is intended', err)
3438+
34073439
def test_js_lib_quoted_key(self):
34083440
create_file('lib.js', r'''
34093441
mergeInto(LibraryManager.library, {

0 commit comments

Comments
 (0)