Open History to see the last commit
1import {readFileSync,writeFileSync} from 'node:fs'
2import {join} from 'node:path'
3
4// Apply after stageAtomicWait. Keep argument conversion and error order intact.
5export function stageSharedAtomicPointers(directory){
6 const path=join(directory,'quickjs.c')
7 let source=readFileSync(path,'utf8')
8 const edit=(name,next,change)=>{
9 const marker='static JSValue '+name+'(JSContext *ctx,'
10 if(source.split(marker).length!==2)throw Error('Unexpected atomic pointer function: '+name)
11 const start=source.indexOf(marker),end=source.indexOf(next,start+marker.length)
12 if(end<0)throw Error('Missing atomic pointer function boundary: '+name)
13 let body=source.slice(start,end)
14 const replace=(before,after)=>{
15 if(body.split(before).length!==2)throw Error('Unexpected atomic pointer site in '+name+': '+before)
16 body=body.replace(before,after)
17 }
18 change(replace)
19 source=source.slice(0,start)+body+source.slice(end)
20 }
21 const capture=` /* Keep the validated byte offset, never repeat index coercion. */
22 JSObject *shared_array = JS_VALUE_GET_OBJ(argv[0]);
23 uintptr_t shared_offset = (uintptr_t)ptr - (uintptr_t)shared_array->u.array.u.uint8_ptr;
24`
25 const refresh=` if (abuf->shared)
26 ptr = shared_array->u.array.u.uint8_ptr + shared_offset;
27`
28 edit('js_atomics_op','static JSValue js_atomics_store(',replace=>{
29 replace(' rep_val = 0;',capture+' rep_val = 0;')
30 replace(' switch(op | (size_log2 << 3)) {',refresh+'\n switch(op | (size_log2 << 3)) {')
31 })
32 edit('js_atomics_store','static JSValue js_atomics_isLockFree(',replace=>{
33 replace(' if (size_log2 == 3) {',capture+' if (size_log2 == 3) {')
34 replace(' atomic_store((_Atomic(uint64_t) *)ptr, v64);',refresh+' atomic_store((_Atomic(uint64_t) *)ptr, v64);')
35 replace(' switch(size_log2) {',refresh+' switch(size_log2) {')
36 })
37 edit('js_atomics_wait','static JSValue js_atomics_notify(',replace=>{
38 replace(' if (size_log2 == 3) {',capture+' if (size_log2 == 3) {')
39 replace(' ret = QTS_FiberAtomicWait(ctx, ptr, size_log2, v, isnan(d) ? INFINITY : d < 0 ? 0 : d);',
40 ' ptr = shared_array->u.array.u.uint8_ptr + shared_offset;\n ret = QTS_FiberAtomicWait(ctx, ptr, size_log2, v, isnan(d) ? INFINITY : d < 0 ? 0 : d);')
41 })
42 edit('js_atomics_notify','static const JSCFunctionListEntry js_atomics_funcs[]',replace=>{
43 replace(' if (JS_IsUndefined(argv[2])) {',capture+' if (JS_IsUndefined(argv[2])) {')
44 replace(' n = abuf->shared ? QTS_FiberAtomicNotify(ptr, count) : 0;',refresh+' n = abuf->shared ? QTS_FiberAtomicNotify(ptr, count) : 0;')
45 })
46 writeFileSync(path,source)
47}