@oseo/runtime-c 0.0.0-stage → 0.1.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +674 -0
  2. package/MIT-LICENSE.txt +21 -0
  3. package/README.md +1677 -2
  4. package/UNICODE-LICENSE.txt +39 -0
  5. package/dist/index.d.ts +7 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +269 -0
  8. package/dist/index.js.map +1 -0
  9. package/native/oseo_runtime.h +2594 -0
  10. package/native/runtime_agent.c +1693 -0
  11. package/native/runtime_arguments.c +355 -0
  12. package/native/runtime_array.c +5742 -0
  13. package/native/runtime_array_buffer.c +1724 -0
  14. package/native/runtime_async_generator.c +948 -0
  15. package/native/runtime_atomics.c +1259 -0
  16. package/native/runtime_bigint.c +1363 -0
  17. package/native/runtime_bigint_object.c +602 -0
  18. package/native/runtime_binding.c +1005 -0
  19. package/native/runtime_boolean.c +296 -0
  20. package/native/runtime_clock.c +157 -0
  21. package/native/runtime_clock_posix.c +575 -0
  22. package/native/runtime_core.c +464 -0
  23. package/native/runtime_data_view.c +1111 -0
  24. package/native/runtime_date.c +1973 -0
  25. package/native/runtime_descriptor.c +1080 -0
  26. package/native/runtime_disposal.c +1643 -0
  27. package/native/runtime_enumeration.c +612 -0
  28. package/native/runtime_error.c +973 -0
  29. package/native/runtime_event_loop.c +629 -0
  30. package/native/runtime_function.c +3643 -0
  31. package/native/runtime_generator.c +1096 -0
  32. package/native/runtime_internal.h +5554 -0
  33. package/native/runtime_iterator.c +5355 -0
  34. package/native/runtime_json.c +1968 -0
  35. package/native/runtime_map.c +1539 -0
  36. package/native/runtime_math.c +894 -0
  37. package/native/runtime_memory.c +1341 -0
  38. package/native/runtime_module.c +860 -0
  39. package/native/runtime_number.c +2053 -0
  40. package/native/runtime_object.c +399 -0
  41. package/native/runtime_object_builtin.c +3877 -0
  42. package/native/runtime_primitive.c +2244 -0
  43. package/native/runtime_process.c +720 -0
  44. package/native/runtime_promise.c +3354 -0
  45. package/native/runtime_property.c +791 -0
  46. package/native/runtime_proxy.c +1533 -0
  47. package/native/runtime_realm.c +411 -0
  48. package/native/runtime_reflect.c +624 -0
  49. package/native/runtime_regexp.c +3495 -0
  50. package/native/runtime_regexp_matcher.c +3535 -0
  51. package/native/runtime_regexp_symbol.c +1471 -0
  52. package/native/runtime_set.c +1751 -0
  53. package/native/runtime_string.c +2862 -0
  54. package/native/runtime_string_match.c +1161 -0
  55. package/native/runtime_symbol.c +986 -0
  56. package/native/runtime_typed_array.c +5113 -0
  57. package/native/runtime_unicode_tables.h +14647 -0
  58. package/native/runtime_uri.c +676 -0
  59. package/native/runtime_weak_collection.c +1275 -0
  60. package/package.json +38 -3
@@ -0,0 +1,1693 @@
1
+ /* SPDX-License-Identifier: MIT */
2
+ /* Copyright (c) 2026 Hong Minhee; see ../MIT-LICENSE.txt. */
3
+
4
+ /*
5
+ * Feature-test macros must precede every system header, including the
6
+ * ones runtime_internal.h includes, so they come before it here. Beside
7
+ * runtime_clock_posix.c, this is the one runtime translation unit that
8
+ * asks for operating-system interfaces beyond C11: POSIX threads.
9
+ */
10
+ #if defined(__linux__)
11
+ #define _GNU_SOURCE
12
+ #elif defined(__APPLE__)
13
+ #define _DARWIN_C_SOURCE
14
+ #endif
15
+
16
+ #include "runtime_internal.h"
17
+
18
+ #include <math.h>
19
+ #include <stdio.h>
20
+ #include <stdlib.h>
21
+ #include <string.h>
22
+
23
+ #if defined(__linux__) || defined(__APPLE__)
24
+ #include <pthread.h>
25
+ #define OSEO_AGENT_THREADS 1
26
+ typedef pthread_mutex_t AgentMutex;
27
+ typedef pthread_t AgentThread;
28
+ #else
29
+ #define OSEO_AGENT_THREADS 0
30
+ typedef int AgentMutex;
31
+ typedef int AgentThread;
32
+ #endif
33
+
34
+ /*
35
+ * Agent clusters and the test262 host object `$262` (ADR 0026).
36
+ *
37
+ * A program compiled for the test262 host makes its realm the main agent
38
+ * of a cluster. `$262.agent.start` evaluates one of the agent programs the
39
+ * compiler built ahead of time from the case's source templates, each in
40
+ * a new agent with its own realm, heap, clock adapter, and event loop, on
41
+ * a POSIX thread of its own. The agents share Shared Data Blocks, the
42
+ * WaiterList store, and the report queue, all of which live here.
43
+ *
44
+ * Agents of one cluster share one executing thread in the sense of
45
+ * ECMA-262's forward progress rules: exactly one agent, the one holding
46
+ * the turn, evaluates at a time. The turn passes only when the holder
47
+ * suspends (Atomics.wait, `$262.agent.sleep`, a broadcast, a start, or an
48
+ * event loop with nothing due), finishes, or reaches a yield point (every
49
+ * Atomics operation and `$262.agent.getReport`), where it goes to the
50
+ * longest-ready agent. One agent therefore always makes progress, and
51
+ * every access to shared memory happens on the thread that holds the turn
52
+ * after the mutex handoff that gave it the turn, so no two threads ever
53
+ * touch a block or any cluster state concurrently. A blocked agent waits
54
+ * in its own clock adapter, and whoever makes it ready wakes that adapter.
55
+ *
56
+ * All cluster state is guarded by `lock`. Heap values never cross agents:
57
+ * a waiter entry names its owner's heap waiter, which only the owner
58
+ * dereferences, a broadcast carries a referenced Shared Data Block and a
59
+ * scalar id, and a report carries copied UTF-16 units.
60
+ */
61
+
62
+ typedef enum {
63
+ AGENT_STARTING = 0,
64
+ AGENT_READY = 1,
65
+ AGENT_RUNNING = 2,
66
+ AGENT_BLOCKED = 3,
67
+ AGENT_FINISHED = 4,
68
+ } AgentState;
69
+
70
+ struct Agent;
71
+
72
+ /* One waiter of the cluster's WaiterList store. */
73
+ typedef struct AgentWaiter {
74
+ struct AgentWaiter *next;
75
+ /* The owner's list of waitAsync waiters another agent notified. */
76
+ struct AgentWaiter *resolved_next;
77
+ struct Agent *agent;
78
+ const OseoSharedBlock *block;
79
+ size_t byte_index;
80
+ /* The owner's OseoAtomicsWaiter for a waitAsync waiter. */
81
+ OseoValue waiter;
82
+ bool asynchronous;
83
+ bool listed;
84
+ bool notified;
85
+ } AgentWaiter;
86
+
87
+ typedef enum {
88
+ AGENT_ID_UNDEFINED = 0,
89
+ AGENT_ID_NUMBER = 1,
90
+ AGENT_ID_BIGINT = 2,
91
+ } AgentIdKind;
92
+
93
+ /* One broadcast waiting in an agent's inbox. */
94
+ typedef struct AgentBroadcast {
95
+ struct AgentBroadcast *next;
96
+ OseoSharedBlock *block;
97
+ AgentIdKind id_kind;
98
+ double id_number;
99
+ /* A BigInt id as its BigInt64 two's-complement bits. */
100
+ uint64_t id_bits;
101
+ } AgentBroadcast;
102
+
103
+ /* One `$262.agent.report` value, copied out of the reporting heap. */
104
+ typedef struct AgentReport {
105
+ struct AgentReport *next;
106
+ size_t length;
107
+ uint16_t units[];
108
+ } AgentReport;
109
+
110
+ /*
111
+ * One matched numeric hole: a decimal integer literal, or a BigInt literal
112
+ * when `bigint` is set, whose digits create the value on each read.
113
+ */
114
+ typedef struct {
115
+ double number;
116
+ char *digits;
117
+ bool bigint;
118
+ } AgentHole;
119
+
120
+ struct AgentCluster;
121
+
122
+ typedef struct Agent {
123
+ struct AgentCluster *cluster;
124
+ struct Agent *next;
125
+ struct Agent *ready_next;
126
+ /* The agent's realm, NULL until its thread has initialized it. */
127
+ OseoContext *context;
128
+ const OseoAgentProgram *program;
129
+ AgentHole *holes;
130
+ size_t hole_count;
131
+ AgentThread thread;
132
+ AgentState state;
133
+ bool main;
134
+ /* A blocked agent waits for a deadline of its own as well. */
135
+ bool has_deadline;
136
+ /* A blocked agent's event loop is idle, so incoming work ends it. */
137
+ bool wakes_on_work;
138
+ bool leaving;
139
+ size_t listed_async;
140
+ AgentWaiter *resolved_head;
141
+ AgentWaiter *resolved_tail;
142
+ AgentBroadcast *broadcast_head;
143
+ AgentBroadcast *broadcast_tail;
144
+ } Agent;
145
+
146
+ typedef struct AgentCluster {
147
+ AgentMutex lock;
148
+ Agent *main;
149
+ /* Every agent other than the main one, in start order. */
150
+ Agent *agents_head;
151
+ Agent *agents_tail;
152
+ Agent *running;
153
+ Agent *ready_head;
154
+ Agent *ready_tail;
155
+ AgentWaiter *waiters_head;
156
+ AgentWaiter *waiters_tail;
157
+ AgentReport *reports_head;
158
+ AgentReport *reports_tail;
159
+ /* Agents that have not yet retrieved the current broadcast. */
160
+ size_t broadcast_remaining;
161
+ const OseoAgentProgram *programs;
162
+ size_t program_count;
163
+ /* The adapter reading `$262.agent.monotonicNow` counts from. */
164
+ uint64_t origin;
165
+ /* The main context's policy, fixed before any agent starts. */
166
+ OseoUnhandledRejectionPolicy unhandled_rejection_policy;
167
+ } AgentCluster;
168
+
169
+ /* The stack each agent thread gets, which the main thread usually has. */
170
+ #define AGENT_STACK_SIZE ((size_t)8u << 20u)
171
+ #define AGENT_NANOSECONDS_PER_MILLISECOND 1000000.0
172
+
173
+ static Agent *agent_of(const OseoContext *context) {
174
+ return (Agent *)context->agent;
175
+ }
176
+
177
+ /*
178
+ * The two thread facilities the cluster needs, over POSIX threads where the
179
+ * target has them. A target without them keeps every lock a no-op and
180
+ * refuses to start a thread, so `$262.agent.start` reports an owned failure
181
+ * and no second agent ever exists to need the lock.
182
+ */
183
+ #if OSEO_AGENT_THREADS
184
+ static bool agent_mutex_init(AgentMutex *mutex) {
185
+ return pthread_mutex_init(mutex, NULL) == 0;
186
+ }
187
+
188
+ static void agent_mutex_destroy(AgentMutex *mutex) {
189
+ (void)pthread_mutex_destroy(mutex);
190
+ }
191
+
192
+ static void agent_mutex_lock(AgentMutex *mutex) {
193
+ (void)pthread_mutex_lock(mutex);
194
+ }
195
+
196
+ static void agent_mutex_unlock(AgentMutex *mutex) {
197
+ (void)pthread_mutex_unlock(mutex);
198
+ }
199
+
200
+ static bool agent_thread_start(
201
+ AgentThread *thread,
202
+ void *(*run)(void *),
203
+ void *argument
204
+ ) {
205
+ pthread_attr_t attributes;
206
+ if (pthread_attr_init(&attributes) != 0) return false;
207
+ (void)pthread_attr_setstacksize(&attributes, AGENT_STACK_SIZE);
208
+ int created = pthread_create(thread, &attributes, run, argument);
209
+ (void)pthread_attr_destroy(&attributes);
210
+ return created == 0;
211
+ }
212
+
213
+ static void agent_thread_join(AgentThread thread) {
214
+ (void)pthread_join(thread, NULL);
215
+ }
216
+ #else
217
+ static bool agent_mutex_init(AgentMutex *mutex) {
218
+ *mutex = 0;
219
+ return true;
220
+ }
221
+
222
+ static void agent_mutex_destroy(AgentMutex *mutex) {
223
+ (void)mutex;
224
+ }
225
+
226
+ static void agent_mutex_lock(AgentMutex *mutex) {
227
+ (void)mutex;
228
+ }
229
+
230
+ static void agent_mutex_unlock(AgentMutex *mutex) {
231
+ (void)mutex;
232
+ }
233
+
234
+ static bool agent_thread_start(
235
+ AgentThread *thread,
236
+ void *(*run)(void *),
237
+ void *argument
238
+ ) {
239
+ (void)thread;
240
+ (void)run;
241
+ (void)argument;
242
+ return false;
243
+ }
244
+
245
+ static void agent_thread_join(AgentThread thread) {
246
+ (void)thread;
247
+ }
248
+ #endif
249
+
250
+ static void cluster_lock(AgentCluster *cluster) {
251
+ agent_mutex_lock(&cluster->lock);
252
+ }
253
+
254
+ static void cluster_unlock(AgentCluster *cluster) {
255
+ agent_mutex_unlock(&cluster->lock);
256
+ }
257
+
258
+ static void holes_free(AgentHole *holes, size_t count) {
259
+ if (holes == NULL) return;
260
+ for (size_t index = 0u; index < count; index += 1u) {
261
+ free(holes[index].digits);
262
+ }
263
+ free(holes);
264
+ }
265
+
266
+ /*
267
+ * Wakes one blocked agent's own clock wait. Only an agent whose thread is
268
+ * blocked is ever signaled, so its realm and adapter are alive.
269
+ */
270
+ static void agent_signal(Agent *agent) {
271
+ if (agent->context != NULL) (void)oseo_clock_wake(agent->context);
272
+ }
273
+
274
+ static void ready_push(AgentCluster *cluster, Agent *agent) {
275
+ agent->ready_next = NULL;
276
+ if (cluster->ready_tail == NULL) {
277
+ cluster->ready_head = agent;
278
+ } else {
279
+ cluster->ready_tail->ready_next = agent;
280
+ }
281
+ cluster->ready_tail = agent;
282
+ }
283
+
284
+ static Agent *ready_pop(AgentCluster *cluster) {
285
+ Agent *agent = cluster->ready_head;
286
+ if (agent == NULL) return NULL;
287
+ cluster->ready_head = agent->ready_next;
288
+ if (cluster->ready_head == NULL) cluster->ready_tail = NULL;
289
+ agent->ready_next = NULL;
290
+ return agent;
291
+ }
292
+
293
+ /* Hands a free turn to the longest-ready agent, if there is one. */
294
+ static void cluster_dispatch(AgentCluster *cluster) {
295
+ if (cluster->running != NULL) return;
296
+ Agent *next = ready_pop(cluster);
297
+ if (next == NULL) return;
298
+ next->state = AGENT_RUNNING;
299
+ cluster->running = next;
300
+ agent_signal(next);
301
+ }
302
+
303
+ static void agent_make_ready(Agent *agent) {
304
+ if (agent->state != AGENT_BLOCKED) return;
305
+ agent->state = AGENT_READY;
306
+ agent->has_deadline = false;
307
+ agent->wakes_on_work = false;
308
+ ready_push(agent->cluster, agent);
309
+ cluster_dispatch(agent->cluster);
310
+ }
311
+
312
+ static bool agent_has_work(const Agent *agent, const OseoContext *context) {
313
+ return agent->resolved_head != NULL ||
314
+ (agent->broadcast_head != NULL &&
315
+ tag_of(context->agent_broadcast_callback) != OSEO_TAG_UNDEFINED);
316
+ }
317
+
318
+ /*
319
+ * Whether an agent other than `self` can still make progress on its own:
320
+ * it holds or awaits the turn, is starting, waits for a deadline, or has
321
+ * incoming work its idle event loop will take.
322
+ */
323
+ static bool cluster_other_progresses(AgentCluster *cluster, Agent *self) {
324
+ Agent *main = cluster->main;
325
+ for (Agent *agent = main; agent != NULL;
326
+ agent = agent == main ? cluster->agents_head : agent->next) {
327
+ if (agent == self) continue;
328
+ if (agent->state == AGENT_STARTING ||
329
+ agent->state == AGENT_READY ||
330
+ agent->state == AGENT_RUNNING) {
331
+ return true;
332
+ }
333
+ if (agent->state == AGENT_BLOCKED && agent->has_deadline) {
334
+ return true;
335
+ }
336
+ }
337
+ return false;
338
+ }
339
+
340
+ static void cluster_print_stall(const Agent *agent) {
341
+ const OseoContext *context = agent->context;
342
+ (void)fflush(stdout);
343
+ if (context != NULL) {
344
+ (void)fwrite(
345
+ context->source_id,
346
+ 1u,
347
+ context->source_id_length,
348
+ stderr
349
+ );
350
+ }
351
+ (void)fprintf(
352
+ stderr,
353
+ ": error[OSEO3001]: The agent cluster cannot make progress.\n"
354
+ );
355
+ (void)fflush(stderr);
356
+ }
357
+
358
+ /*
359
+ * Runs after the turn became free with no agent ready. When every
360
+ * remaining agent waits without a deadline, nothing can wake any of them:
361
+ * an idle main agent is made ready so its event loop can end, and a main
362
+ * agent suspended in a blocking operation is a deadlock the process
363
+ * reports and exits on, rather than hanging.
364
+ */
365
+ static void cluster_check_progress(AgentCluster *cluster, Agent *self) {
366
+ if (cluster->running != NULL || cluster->ready_head != NULL) return;
367
+ if (cluster_other_progresses(cluster, NULL)) return;
368
+ Agent *main = cluster->main;
369
+ if (main->state == AGENT_FINISHED) return;
370
+ if (main->state == AGENT_BLOCKED && main->wakes_on_work) {
371
+ agent_make_ready(main);
372
+ return;
373
+ }
374
+ cluster_print_stall(self);
375
+ exit(EXIT_FAILURE);
376
+ }
377
+
378
+ /* An infinite or deadline wait on the agent's own clock adapter. */
379
+ static OseoResult agent_clock_wait(
380
+ OseoContext *context,
381
+ bool has_deadline,
382
+ uint64_t deadline
383
+ ) {
384
+ if (has_deadline) return oseo_internal_clock_wait_until(context, deadline);
385
+ OseoResult result = oseo_internal_clock_start(context);
386
+ if (result.status != OSEO_STATUS_NORMAL) return result;
387
+ if (context->clock_adapter->wait(context->clock_state, false, 0u) ==
388
+ OSEO_CLOCK_WAIT_FAILED) {
389
+ return failure(context, "OSEO2001", "The host clock wait failed.");
390
+ }
391
+ return normal(oseo_undefined());
392
+ }
393
+
394
+ /*
395
+ * Waits, with the cluster lock held on entry and on return, until this
396
+ * agent holds the turn. A blocked agent whose deadline passes first
397
+ * becomes ready by itself; `timed_out` reports that, and a blocking
398
+ * waiter still listed at that moment leaves the store.
399
+ */
400
+ static OseoResult agent_await_turn(
401
+ OseoContext *context,
402
+ Agent *self,
403
+ uint64_t deadline,
404
+ AgentWaiter *waiter,
405
+ bool *timed_out
406
+ ) {
407
+ AgentCluster *cluster = self->cluster;
408
+ OseoResult result = normal(oseo_undefined());
409
+ while (cluster->running != self) {
410
+ if (self->state == AGENT_BLOCKED && self->has_deadline) {
411
+ uint64_t now = 0u;
412
+ result = oseo_internal_clock_now(context, &now);
413
+ if (result.status != OSEO_STATUS_NORMAL) return result;
414
+ if (now >= deadline) {
415
+ if (waiter != NULL && waiter->listed) {
416
+ AgentWaiter **link = &cluster->waiters_head;
417
+ AgentWaiter *previous = NULL;
418
+ while (*link != waiter) {
419
+ previous = *link;
420
+ link = &(*link)->next;
421
+ }
422
+ *link = waiter->next;
423
+ if (cluster->waiters_tail == waiter) {
424
+ cluster->waiters_tail = previous;
425
+ }
426
+ waiter->listed = false;
427
+ }
428
+ if (timed_out != NULL) *timed_out = true;
429
+ agent_make_ready(self);
430
+ continue;
431
+ }
432
+ }
433
+ bool has_deadline =
434
+ self->state == AGENT_BLOCKED && self->has_deadline;
435
+ cluster_unlock(cluster);
436
+ result = agent_clock_wait(context, has_deadline, deadline);
437
+ cluster_lock(cluster);
438
+ if (result.status != OSEO_STATUS_NORMAL) return result;
439
+ }
440
+ return result;
441
+ }
442
+
443
+ /*
444
+ * Gives up the turn and blocks until another agent makes this one ready
445
+ * or, with `has_deadline`, until the deadline passes, then waits for the
446
+ * turn again. The cluster lock is held on entry and on return.
447
+ */
448
+ static OseoResult agent_block(
449
+ OseoContext *context,
450
+ Agent *self,
451
+ bool has_deadline,
452
+ uint64_t deadline,
453
+ bool wakes_on_work,
454
+ AgentWaiter *waiter,
455
+ bool *timed_out
456
+ ) {
457
+ AgentCluster *cluster = self->cluster;
458
+ self->state = AGENT_BLOCKED;
459
+ self->has_deadline = has_deadline;
460
+ self->wakes_on_work = wakes_on_work;
461
+ cluster->running = NULL;
462
+ cluster_dispatch(cluster);
463
+ if (!has_deadline) cluster_check_progress(cluster, self);
464
+ return agent_await_turn(context, self, deadline, waiter, timed_out);
465
+ }
466
+
467
+ /*
468
+ * The whole-millisecond deadline `milliseconds` after now. The current
469
+ * whole millisecond is counted as already started, so the wait lasts at
470
+ * least the requested time however far into it the call began, and a
471
+ * fractional request rounds up, which is a permitted additional timeout.
472
+ */
473
+ static OseoResult agent_deadline(
474
+ OseoContext *context,
475
+ double milliseconds,
476
+ uint64_t *deadline
477
+ ) {
478
+ uint64_t now = 0u;
479
+ OseoResult result = oseo_internal_clock_now(context, &now);
480
+ if (result.status != OSEO_STATUS_NORMAL) return result;
481
+ double rounded = ceil(milliseconds > 0.0 ? milliseconds : 0.0) + 1.0;
482
+ uint64_t delay = rounded >= 18446744073709549568.0
483
+ ? UINT64_MAX
484
+ : (uint64_t)rounded;
485
+ *deadline = UINT64_MAX - now < delay ? UINT64_MAX : now + delay;
486
+ return result;
487
+ }
488
+
489
+ OseoResult oseo_internal_agent_yield(OseoContext *context) {
490
+ Agent *self = agent_of(context);
491
+ if (self == NULL) return normal(oseo_undefined());
492
+ AgentCluster *cluster = self->cluster;
493
+ cluster_lock(cluster);
494
+ OseoResult result = normal(oseo_undefined());
495
+ if (cluster->ready_head != NULL) {
496
+ self->state = AGENT_READY;
497
+ ready_push(cluster, self);
498
+ cluster->running = NULL;
499
+ cluster_dispatch(cluster);
500
+ result = agent_await_turn(context, self, 0u, NULL, NULL);
501
+ }
502
+ cluster_unlock(cluster);
503
+ return result;
504
+ }
505
+
506
+ static void waiter_link(AgentCluster *cluster, AgentWaiter *waiter) {
507
+ waiter->next = NULL;
508
+ if (cluster->waiters_tail == NULL) {
509
+ cluster->waiters_head = waiter;
510
+ } else {
511
+ cluster->waiters_tail->next = waiter;
512
+ }
513
+ cluster->waiters_tail = waiter;
514
+ waiter->listed = true;
515
+ }
516
+
517
+ static void waiter_unlink(AgentCluster *cluster, AgentWaiter *waiter) {
518
+ AgentWaiter *previous = NULL;
519
+ AgentWaiter *current = cluster->waiters_head;
520
+ while (current != NULL && current != waiter) {
521
+ previous = current;
522
+ current = current->next;
523
+ }
524
+ if (current == NULL) return;
525
+ if (previous == NULL) {
526
+ cluster->waiters_head = waiter->next;
527
+ } else {
528
+ previous->next = waiter->next;
529
+ }
530
+ if (cluster->waiters_tail == waiter) cluster->waiters_tail = previous;
531
+ waiter->next = NULL;
532
+ waiter->listed = false;
533
+ }
534
+
535
+ OseoResult oseo_internal_agent_suspend(
536
+ OseoContext *context,
537
+ const OseoSharedBlock *block,
538
+ size_t byte_index,
539
+ double timeout,
540
+ bool *notified
541
+ ) {
542
+ Agent *self = agent_of(context);
543
+ AgentCluster *cluster = self->cluster;
544
+ bool finite = isfinite(timeout);
545
+ uint64_t deadline = 0u;
546
+ if (finite) {
547
+ OseoResult result = agent_deadline(context, timeout, &deadline);
548
+ if (result.status != OSEO_STATUS_NORMAL) return result;
549
+ }
550
+ AgentWaiter waiter;
551
+ waiter.next = NULL;
552
+ waiter.resolved_next = NULL;
553
+ waiter.agent = self;
554
+ waiter.block = block;
555
+ waiter.byte_index = byte_index;
556
+ waiter.waiter = oseo_undefined();
557
+ waiter.asynchronous = false;
558
+ waiter.listed = false;
559
+ waiter.notified = false;
560
+ cluster_lock(cluster);
561
+ waiter_link(cluster, &waiter);
562
+ OseoResult result = agent_block(
563
+ context,
564
+ self,
565
+ finite,
566
+ deadline,
567
+ false,
568
+ &waiter,
569
+ NULL
570
+ );
571
+ if (waiter.listed) waiter_unlink(cluster, &waiter);
572
+ *notified = waiter.notified;
573
+ cluster_unlock(cluster);
574
+ return result;
575
+ }
576
+
577
+ OseoResult oseo_internal_agent_list_waiter(
578
+ OseoContext *context,
579
+ OseoValue waiter
580
+ ) {
581
+ Agent *self = agent_of(context);
582
+ OseoAtomicsWaiter *record = atomics_waiter_object(waiter);
583
+ AgentWaiter *entry = malloc(sizeof(*entry));
584
+ if (entry == NULL) {
585
+ return failure(
586
+ context,
587
+ "OSEO2001",
588
+ "Atomics waiter allocation failed."
589
+ );
590
+ }
591
+ entry->next = NULL;
592
+ entry->resolved_next = NULL;
593
+ entry->agent = self;
594
+ entry->block = record->block;
595
+ entry->byte_index = record->byte_index;
596
+ entry->waiter = waiter;
597
+ entry->asynchronous = true;
598
+ entry->listed = false;
599
+ entry->notified = false;
600
+ record->record = entry;
601
+ cluster_lock(self->cluster);
602
+ waiter_link(self->cluster, entry);
603
+ self->listed_async += 1u;
604
+ cluster_unlock(self->cluster);
605
+ return normal(oseo_undefined());
606
+ }
607
+
608
+ bool oseo_internal_agent_unlist_waiter(OseoContext *context, OseoValue waiter) {
609
+ Agent *self = agent_of(context);
610
+ OseoAtomicsWaiter *record = atomics_waiter_object(waiter);
611
+ AgentWaiter *entry = record->record;
612
+ if (entry == NULL) return false;
613
+ cluster_lock(self->cluster);
614
+ bool listed = entry->listed;
615
+ if (listed) {
616
+ waiter_unlink(self->cluster, entry);
617
+ self->listed_async -= 1u;
618
+ }
619
+ cluster_unlock(self->cluster);
620
+ if (!listed) return false;
621
+ record->record = NULL;
622
+ free(entry);
623
+ return true;
624
+ }
625
+
626
+ bool oseo_internal_agent_notify_one(
627
+ OseoContext *context,
628
+ const OseoSharedBlock *block,
629
+ size_t byte_index,
630
+ OseoValue *own_waiter
631
+ ) {
632
+ Agent *self = agent_of(context);
633
+ AgentCluster *cluster = self->cluster;
634
+ cluster_lock(cluster);
635
+ AgentWaiter *entry = cluster->waiters_head;
636
+ while (entry != NULL &&
637
+ (entry->block != block || entry->byte_index != byte_index)) {
638
+ entry = entry->next;
639
+ }
640
+ if (entry == NULL) {
641
+ cluster_unlock(cluster);
642
+ return false;
643
+ }
644
+ waiter_unlink(cluster, entry);
645
+ entry->notified = true;
646
+ Agent *owner = entry->agent;
647
+ if (!entry->asynchronous) {
648
+ agent_make_ready(owner);
649
+ } else if (owner == self) {
650
+ owner->listed_async -= 1u;
651
+ *own_waiter = entry->waiter;
652
+ atomics_waiter_object(entry->waiter)->record = NULL;
653
+ free(entry);
654
+ } else {
655
+ /* EnqueueResolveInAgentJob: the owner resolves it as a task. */
656
+ owner->listed_async -= 1u;
657
+ entry->resolved_next = NULL;
658
+ if (owner->resolved_tail == NULL) {
659
+ owner->resolved_head = entry;
660
+ } else {
661
+ owner->resolved_tail->resolved_next = entry;
662
+ }
663
+ owner->resolved_tail = entry;
664
+ if (owner->state == AGENT_BLOCKED && owner->wakes_on_work) {
665
+ agent_make_ready(owner);
666
+ }
667
+ }
668
+ cluster_unlock(cluster);
669
+ return true;
670
+ }
671
+
672
+ /*
673
+ * Whether this realm's next broadcast can be taken: a callback is
674
+ * registered and one is waiting. The lock is held.
675
+ */
676
+ static AgentBroadcast *take_broadcast(OseoContext *context, Agent *self) {
677
+ if (tag_of(context->agent_broadcast_callback) == OSEO_TAG_UNDEFINED) {
678
+ return NULL;
679
+ }
680
+ AgentBroadcast *broadcast = self->broadcast_head;
681
+ if (broadcast == NULL) return NULL;
682
+ self->broadcast_head = broadcast->next;
683
+ if (self->broadcast_head == NULL) self->broadcast_tail = NULL;
684
+ broadcast->next = NULL;
685
+ AgentCluster *cluster = self->cluster;
686
+ if (cluster->broadcast_remaining > 0u) {
687
+ cluster->broadcast_remaining -= 1u;
688
+ if (cluster->broadcast_remaining == 0u) {
689
+ agent_make_ready(cluster->main);
690
+ }
691
+ }
692
+ return broadcast;
693
+ }
694
+
695
+ static OseoResult broadcast_id(
696
+ OseoContext *context,
697
+ const AgentBroadcast *broadcast
698
+ ) {
699
+ if (broadcast->id_kind == AGENT_ID_NUMBER) {
700
+ return normal(oseo_number(broadcast->id_number));
701
+ }
702
+ if (broadcast->id_kind == AGENT_ID_BIGINT) {
703
+ bool negative = (broadcast->id_bits >> 63u) != 0u;
704
+ return oseo_internal_bigint_from_uint64(
705
+ context,
706
+ negative ? UINT64_C(0) - broadcast->id_bits : broadcast->id_bits,
707
+ negative
708
+ );
709
+ }
710
+ return normal(oseo_undefined());
711
+ }
712
+
713
+ /*
714
+ * Turns one retrieved broadcast into a task of this agent: the callback
715
+ * runs as a due timer callback with this realm's own SharedArrayBuffer
716
+ * over the broadcast block and the id, so it follows every timer turn
717
+ * rule, including the checkpoint after it.
718
+ */
719
+ static OseoResult deliver_broadcast(
720
+ OseoContext *context,
721
+ AgentBroadcast *broadcast
722
+ ) {
723
+ OseoRootFrame frame = {NULL, NULL, 0u};
724
+ OseoResult result = oseo_roots_allocate(context, &frame, 4u);
725
+ if (result.status != OSEO_STATUS_NORMAL) {
726
+ oseo_internal_shared_block_release(broadcast->block);
727
+ free(broadcast);
728
+ return result;
729
+ }
730
+ frame.slots[0] = context->agent_broadcast_callback;
731
+ frame.slots[1] = oseo_number(0.0);
732
+ result = oseo_internal_shared_array_buffer_from_block(
733
+ context,
734
+ broadcast->block
735
+ );
736
+ frame.slots[2] = result.value;
737
+ if (result.status == OSEO_STATUS_NORMAL) {
738
+ result = broadcast_id(context, broadcast);
739
+ frame.slots[3] = result.value;
740
+ }
741
+ if (result.status == OSEO_STATUS_NORMAL) {
742
+ result = oseo_set_timeout(context, 4u, frame.slots);
743
+ }
744
+ oseo_roots_release(context, &frame);
745
+ oseo_internal_shared_block_release(broadcast->block);
746
+ free(broadcast);
747
+ return result;
748
+ }
749
+
750
+ OseoResult oseo_internal_agent_receive(OseoContext *context, bool *ran) {
751
+ *ran = false;
752
+ Agent *self = agent_of(context);
753
+ if (self == NULL) return normal(oseo_undefined());
754
+ AgentCluster *cluster = self->cluster;
755
+ OseoResult result = normal(oseo_undefined());
756
+ for (;;) {
757
+ cluster_lock(cluster);
758
+ AgentWaiter *entry = self->resolved_head;
759
+ if (entry != NULL) {
760
+ self->resolved_head = entry->resolved_next;
761
+ if (self->resolved_head == NULL) self->resolved_tail = NULL;
762
+ }
763
+ AgentBroadcast *broadcast =
764
+ entry == NULL ? take_broadcast(context, self) : NULL;
765
+ cluster_unlock(cluster);
766
+ if (entry == NULL && broadcast == NULL) break;
767
+ *ran = true;
768
+ if (entry != NULL) {
769
+ OseoValue waiter = entry->waiter;
770
+ atomics_waiter_object(waiter)->record = NULL;
771
+ free(entry);
772
+ result = oseo_internal_atomics_waiter_notified(context, waiter);
773
+ } else {
774
+ result = deliver_broadcast(context, broadcast);
775
+ }
776
+ if (result.status != OSEO_STATUS_NORMAL) break;
777
+ }
778
+ return result;
779
+ }
780
+
781
+ bool oseo_internal_agent_keeps_alive(OseoContext *context) {
782
+ Agent *self = agent_of(context);
783
+ if (self == NULL) return false;
784
+ AgentCluster *cluster = self->cluster;
785
+ cluster_lock(cluster);
786
+ bool alive;
787
+ if (agent_has_work(self, context)) {
788
+ alive = true;
789
+ } else if (!self->main) {
790
+ alive = self->listed_async > 0u ||
791
+ (tag_of(context->agent_broadcast_callback) !=
792
+ OSEO_TAG_UNDEFINED &&
793
+ !self->leaving);
794
+ } else {
795
+ alive = self->listed_async > 0u &&
796
+ cluster_other_progresses(cluster, self);
797
+ }
798
+ cluster_unlock(cluster);
799
+ return alive;
800
+ }
801
+
802
+ OseoResult oseo_internal_agent_idle(
803
+ OseoContext *context,
804
+ bool has_deadline,
805
+ uint64_t deadline
806
+ ) {
807
+ Agent *self = agent_of(context);
808
+ if (self == NULL) {
809
+ return has_deadline
810
+ ? oseo_internal_clock_wait_until(context, deadline)
811
+ : normal(oseo_undefined());
812
+ }
813
+ AgentCluster *cluster = self->cluster;
814
+ cluster_lock(cluster);
815
+ OseoResult result = normal(oseo_undefined());
816
+ if (!agent_has_work(self, context)) {
817
+ result = agent_block(
818
+ context,
819
+ self,
820
+ has_deadline,
821
+ deadline,
822
+ true,
823
+ NULL,
824
+ NULL
825
+ );
826
+ }
827
+ cluster_unlock(cluster);
828
+ return result;
829
+ }
830
+
831
+ /* Drops everything an agent that stops evaluating still holds. */
832
+ static void agent_discard_work(AgentCluster *cluster, Agent *agent) {
833
+ AgentWaiter *entry = cluster->waiters_head;
834
+ while (entry != NULL) {
835
+ AgentWaiter *next = entry->next;
836
+ if (entry->agent == agent) {
837
+ waiter_unlink(cluster, entry);
838
+ if (entry->asynchronous) free(entry);
839
+ }
840
+ entry = next;
841
+ }
842
+ while (agent->resolved_head != NULL) {
843
+ AgentWaiter *resolved = agent->resolved_head;
844
+ agent->resolved_head = resolved->resolved_next;
845
+ free(resolved);
846
+ }
847
+ agent->resolved_tail = NULL;
848
+ agent->listed_async = 0u;
849
+ while (agent->broadcast_head != NULL) {
850
+ AgentBroadcast *broadcast = agent->broadcast_head;
851
+ agent->broadcast_head = broadcast->next;
852
+ oseo_internal_shared_block_release(broadcast->block);
853
+ free(broadcast);
854
+ if (cluster->broadcast_remaining > 0u) {
855
+ cluster->broadcast_remaining -= 1u;
856
+ if (cluster->broadcast_remaining == 0u) {
857
+ agent_make_ready(cluster->main);
858
+ }
859
+ }
860
+ }
861
+ agent->broadcast_tail = NULL;
862
+ }
863
+
864
+ static void cluster_reap(AgentCluster *cluster);
865
+
866
+ static void cluster_free(AgentCluster *cluster) {
867
+ while (cluster->reports_head != NULL) {
868
+ AgentReport *report = cluster->reports_head;
869
+ cluster->reports_head = report->next;
870
+ free(report);
871
+ }
872
+ Agent *agent = cluster->agents_head;
873
+ while (agent != NULL) {
874
+ Agent *next = agent->next;
875
+ holes_free(agent->holes, agent->hole_count);
876
+ free(agent);
877
+ agent = next;
878
+ }
879
+ free(cluster->main);
880
+ agent_mutex_destroy(&cluster->lock);
881
+ free(cluster);
882
+ }
883
+
884
+ void oseo_internal_agent_context_destroy(OseoContext *context) {
885
+ Agent *self = agent_of(context);
886
+ if (self == NULL || !self->main) return;
887
+ AgentCluster *cluster = self->cluster;
888
+ cluster_lock(cluster);
889
+ /*
890
+ * The main agent keeps the turn from here on, so an agent that is
891
+ * still waiting never evaluates again while the process exits. The
892
+ * agents that finished are joined and the cluster is released only
893
+ * when all of them did; a waiting agent's thread still refers to it.
894
+ */
895
+ agent_discard_work(cluster, self);
896
+ bool finished = true;
897
+ for (Agent *agent = cluster->agents_head; agent != NULL;
898
+ agent = agent->next) {
899
+ if (agent->state != AGENT_FINISHED) finished = false;
900
+ }
901
+ cluster_unlock(cluster);
902
+ context->agent = NULL;
903
+ if (!finished) return;
904
+ cluster_reap(cluster);
905
+ cluster_free(cluster);
906
+ }
907
+
908
+ /*
909
+ * Matches a start source against one program's template: the literal
910
+ * runs must match exactly, and each hole must be a decimal integer
911
+ * literal without a leading zero, optionally followed by the BigInt
912
+ * suffix `n`. The runs never start or end with a digit or an identifier
913
+ * character, so each hole is the maximal digit run at its position and a
914
+ * following `n` can only be its suffix. `false` with `*failed` set
915
+ * reports an allocation failure rather than a mismatch.
916
+ */
917
+ static bool program_matches(
918
+ const OseoAgentProgram *program,
919
+ const OseoString *source,
920
+ AgentHole *holes,
921
+ bool *failed
922
+ ) {
923
+ size_t position = 0u;
924
+ for (size_t index = 0u; index < program->segment_count; index += 1u) {
925
+ const OseoAgentSegment *segment = &program->segments[index];
926
+ if (index > 0u) {
927
+ size_t start = position;
928
+ while (position < source->length &&
929
+ source->units[position] >= '0' &&
930
+ source->units[position] <= '9') {
931
+ position += 1u;
932
+ }
933
+ size_t length = position - start;
934
+ if (length == 0u) return false;
935
+ if (source->units[start] == '0' && length > 1u) return false;
936
+ AgentHole *hole = &holes[index - 1u];
937
+ hole->bigint = position < source->length &&
938
+ source->units[position] == 'n';
939
+ if (hole->bigint) position += 1u;
940
+ hole->digits = malloc(length + 1u);
941
+ if (hole->digits == NULL) {
942
+ *failed = true;
943
+ return false;
944
+ }
945
+ for (size_t digit = 0u; digit < length; digit += 1u) {
946
+ hole->digits[digit] = (char)source->units[start + digit];
947
+ }
948
+ hole->digits[length] = '\0';
949
+ /* One correctly rounded conversion of the exact literal text. */
950
+ hole->number = strtod(hole->digits, NULL);
951
+ }
952
+ if (source->length - position < segment->length ||
953
+ memcmp(
954
+ source->units + position,
955
+ segment->units,
956
+ segment->length * sizeof(uint16_t)
957
+ ) != 0) {
958
+ return false;
959
+ }
960
+ position += segment->length;
961
+ }
962
+ return position == source->length;
963
+ }
964
+
965
+ static OseoResult install_host(OseoContext *context, bool main);
966
+
967
+ static void agent_report_failure(OseoContext *context, OseoResult result) {
968
+ (void)fflush(stdout);
969
+ oseo_context_print_thrown(context, result.value);
970
+ (void)fflush(stderr);
971
+ exit(EXIT_FAILURE);
972
+ }
973
+
974
+ /*
975
+ * The body of one agent thread. It initializes the agent's realm, makes
976
+ * itself ready ahead of the main agent that started it, and once it holds
977
+ * the turn evaluates its program. An abrupt completion of an agent ends
978
+ * the process with the agent's error, because a test that lost an agent
979
+ * could otherwise only hang. A finished agent destroys its realm while it
980
+ * still holds the turn and then passes the turn on for good.
981
+ */
982
+ static void *agent_thread(void *argument) {
983
+ Agent *self = argument;
984
+ AgentCluster *cluster = self->cluster;
985
+ OseoContext context;
986
+ oseo_context_init(
987
+ &context,
988
+ self->program->source_id,
989
+ self->program->source_id_length
990
+ );
991
+ context.agent = self;
992
+ context.unhandled_rejection_policy = cluster->unhandled_rejection_policy;
993
+ if (!oseo_clock_open(&context)) {
994
+ (void)fflush(stdout);
995
+ (void)fwrite(
996
+ context.source_id,
997
+ 1u,
998
+ context.source_id_length,
999
+ stderr
1000
+ );
1001
+ (void)fprintf(
1002
+ stderr,
1003
+ ": error[OSEO2001]: Cross-agent wakeup is unavailable.\n"
1004
+ );
1005
+ exit(EXIT_FAILURE);
1006
+ }
1007
+ cluster_lock(cluster);
1008
+ self->context = &context;
1009
+ self->state = AGENT_READY;
1010
+ ready_push(cluster, self);
1011
+ agent_make_ready(cluster->main);
1012
+ cluster_dispatch(cluster);
1013
+ OseoResult result = agent_await_turn(&context, self, 0u, NULL, NULL);
1014
+ cluster_unlock(cluster);
1015
+ if (result.status == OSEO_STATUS_NORMAL) {
1016
+ result = install_host(&context, false);
1017
+ }
1018
+ if (result.status == OSEO_STATUS_NORMAL) {
1019
+ result = self->program->entry(&context);
1020
+ }
1021
+ if (result.status != OSEO_STATUS_NORMAL) {
1022
+ agent_report_failure(&context, result);
1023
+ }
1024
+ cluster_lock(cluster);
1025
+ agent_discard_work(cluster, self);
1026
+ cluster_unlock(cluster);
1027
+ context.agent = NULL;
1028
+ oseo_context_destroy(&context);
1029
+ cluster_lock(cluster);
1030
+ self->context = NULL;
1031
+ self->state = AGENT_FINISHED;
1032
+ cluster->running = NULL;
1033
+ cluster_dispatch(cluster);
1034
+ cluster_check_progress(cluster, self);
1035
+ cluster_unlock(cluster);
1036
+ return NULL;
1037
+ }
1038
+
1039
+ /*
1040
+ * Joins and releases every agent that has finished. An agent marks itself
1041
+ * finished in its last critical section and touches nothing shared after
1042
+ * it, so the join outside the lock only waits for its thread to return.
1043
+ * The main agent reaps before each start, so a case that starts agents one
1044
+ * after another holds at most the threads of the agents still running.
1045
+ */
1046
+ static void cluster_reap(AgentCluster *cluster) {
1047
+ Agent *finished = NULL;
1048
+ cluster_lock(cluster);
1049
+ Agent **link = &cluster->agents_head;
1050
+ Agent *previous = NULL;
1051
+ while (*link != NULL) {
1052
+ Agent *agent = *link;
1053
+ if (agent->state != AGENT_FINISHED) {
1054
+ previous = agent;
1055
+ link = &agent->next;
1056
+ continue;
1057
+ }
1058
+ *link = agent->next;
1059
+ if (cluster->agents_tail == agent) cluster->agents_tail = previous;
1060
+ agent->next = finished;
1061
+ finished = agent;
1062
+ }
1063
+ cluster_unlock(cluster);
1064
+ while (finished != NULL) {
1065
+ Agent *agent = finished;
1066
+ finished = agent->next;
1067
+ agent_thread_join(agent->thread);
1068
+ holes_free(agent->holes, agent->hole_count);
1069
+ free(agent);
1070
+ }
1071
+ }
1072
+
1073
+ static OseoResult agent_start(
1074
+ OseoContext *context,
1075
+ Agent *self,
1076
+ OseoValue source
1077
+ ) {
1078
+ AgentCluster *cluster = self->cluster;
1079
+ cluster_reap(cluster);
1080
+ if (!is_string(source)) {
1081
+ return oseo_internal_throw_error(
1082
+ context,
1083
+ OSEO_ERROR_TYPE,
1084
+ "$262.agent.start needs a source string."
1085
+ );
1086
+ }
1087
+ const OseoString *text = string_object(source);
1088
+ const OseoAgentProgram *program = NULL;
1089
+ AgentHole *holes = NULL;
1090
+ for (size_t index = 0u; index < cluster->program_count; index += 1u) {
1091
+ const OseoAgentProgram *candidate = &cluster->programs[index];
1092
+ size_t count = candidate->segment_count - 1u;
1093
+ AgentHole *values =
1094
+ count == 0u ? NULL : calloc(count, sizeof(AgentHole));
1095
+ bool failed = false;
1096
+ if (count > 0u && values == NULL) failed = true;
1097
+ if (!failed && program_matches(candidate, text, values, &failed)) {
1098
+ program = candidate;
1099
+ holes = values;
1100
+ break;
1101
+ }
1102
+ holes_free(values, count);
1103
+ if (failed) {
1104
+ return failure(context, "OSEO2001", "Agent allocation failed.");
1105
+ }
1106
+ }
1107
+ if (program == NULL) {
1108
+ return failure(
1109
+ context,
1110
+ "OSEO2001",
1111
+ "Agent source text outside the ahead-of-time agent programs "
1112
+ "is not admitted."
1113
+ );
1114
+ }
1115
+ size_t hole_count = program->segment_count - 1u;
1116
+ if (!oseo_clock_open(context)) {
1117
+ holes_free(holes, hole_count);
1118
+ return failure(
1119
+ context,
1120
+ "OSEO2001",
1121
+ "Cross-agent wakeup is unavailable."
1122
+ );
1123
+ }
1124
+ Agent *agent = calloc(1u, sizeof(*agent));
1125
+ if (agent == NULL) {
1126
+ holes_free(holes, hole_count);
1127
+ return failure(context, "OSEO2001", "Agent allocation failed.");
1128
+ }
1129
+ agent->cluster = cluster;
1130
+ agent->program = program;
1131
+ agent->holes = holes;
1132
+ agent->hole_count = hole_count;
1133
+ agent->state = AGENT_STARTING;
1134
+ cluster_lock(cluster);
1135
+ if (!agent_thread_start(&agent->thread, agent_thread, agent)) {
1136
+ cluster_unlock(cluster);
1137
+ holes_free(holes, hole_count);
1138
+ free(agent);
1139
+ return failure(context, "OSEO2001", "Agent thread creation failed.");
1140
+ }
1141
+ if (cluster->agents_tail == NULL) {
1142
+ cluster->agents_head = agent;
1143
+ } else {
1144
+ cluster->agents_tail->next = agent;
1145
+ }
1146
+ cluster->agents_tail = agent;
1147
+ /* The start blocks until the new agent is running. */
1148
+ OseoResult result = agent_block(
1149
+ context,
1150
+ self,
1151
+ false,
1152
+ 0u,
1153
+ false,
1154
+ NULL,
1155
+ NULL
1156
+ );
1157
+ cluster_unlock(cluster);
1158
+ return result.status == OSEO_STATUS_NORMAL
1159
+ ? normal(oseo_undefined())
1160
+ : result;
1161
+ }
1162
+
1163
+ /*
1164
+ * $262.agent.broadcast(sab, id). Every agent still evaluating receives
1165
+ * the block, and the main agent blocks until each of them has retrieved
1166
+ * it, which an agent does once it has registered a callback.
1167
+ */
1168
+ static OseoResult agent_broadcast(
1169
+ OseoContext *context,
1170
+ Agent *self,
1171
+ size_t argument_count,
1172
+ const OseoValue *arguments
1173
+ ) {
1174
+ OseoValue buffer = argument_count > 0u ? arguments[0] : oseo_undefined();
1175
+ OseoValue id = argument_count > 1u ? arguments[1] : oseo_undefined();
1176
+ if (!is_array_buffer(buffer) || !array_buffer_object(buffer)->shared) {
1177
+ return oseo_internal_throw_error(
1178
+ context,
1179
+ OSEO_ERROR_TYPE,
1180
+ "$262.agent.broadcast needs a SharedArrayBuffer."
1181
+ );
1182
+ }
1183
+ AgentIdKind kind = AGENT_ID_UNDEFINED;
1184
+ double number = 0.0;
1185
+ uint64_t bits = UINT64_C(0);
1186
+ if (is_number(id)) {
1187
+ kind = AGENT_ID_NUMBER;
1188
+ number = number_value(id);
1189
+ } else if (is_bigint(id)) {
1190
+ const OseoBigInt *value = bigint_object(id);
1191
+ uint64_t magnitude = UINT64_C(0);
1192
+ if (value->length > 0u) magnitude = value->limbs[0];
1193
+ if (value->length > 1u) {
1194
+ magnitude |= (uint64_t)value->limbs[1] << 32u;
1195
+ }
1196
+ if (value->length > 2u ||
1197
+ magnitude > (value->negative ? UINT64_C(0x8000000000000000)
1198
+ : UINT64_C(0x7fffffffffffffff))) {
1199
+ return oseo_internal_throw_error(
1200
+ context,
1201
+ OSEO_ERROR_RANGE,
1202
+ "$262.agent.broadcast id is outside the BigInt64 range."
1203
+ );
1204
+ }
1205
+ kind = AGENT_ID_BIGINT;
1206
+ bits = oseo_internal_bigint_to_raw_uint64(id);
1207
+ } else if (tag_of(id) != OSEO_TAG_UNDEFINED) {
1208
+ return oseo_internal_throw_error(
1209
+ context,
1210
+ OSEO_ERROR_TYPE,
1211
+ "$262.agent.broadcast id must be a Number or a BigInt."
1212
+ );
1213
+ }
1214
+ OseoSharedBlock *block = array_buffer_object(buffer)->block;
1215
+ AgentCluster *cluster = self->cluster;
1216
+ cluster_lock(cluster);
1217
+ size_t delivered = 0u;
1218
+ OseoResult result = normal(oseo_undefined());
1219
+ for (Agent *agent = cluster->agents_head; agent != NULL;
1220
+ agent = agent->next) {
1221
+ if (agent->state == AGENT_FINISHED) continue;
1222
+ AgentBroadcast *broadcast = malloc(sizeof(*broadcast));
1223
+ if (broadcast == NULL) {
1224
+ result = failure(
1225
+ context,
1226
+ "OSEO2001",
1227
+ "Agent broadcast allocation failed."
1228
+ );
1229
+ break;
1230
+ }
1231
+ oseo_internal_shared_block_retain(block);
1232
+ broadcast->next = NULL;
1233
+ broadcast->block = block;
1234
+ broadcast->id_kind = kind;
1235
+ broadcast->id_number = number;
1236
+ broadcast->id_bits = bits;
1237
+ if (agent->broadcast_tail == NULL) {
1238
+ agent->broadcast_head = broadcast;
1239
+ } else {
1240
+ agent->broadcast_tail->next = broadcast;
1241
+ }
1242
+ agent->broadcast_tail = broadcast;
1243
+ delivered += 1u;
1244
+ if (agent->state == AGENT_BLOCKED && agent->wakes_on_work) {
1245
+ agent_make_ready(agent);
1246
+ }
1247
+ }
1248
+ if (delivered > 0u) {
1249
+ cluster->broadcast_remaining += delivered;
1250
+ OseoResult blocked = agent_block(
1251
+ context,
1252
+ self,
1253
+ false,
1254
+ 0u,
1255
+ false,
1256
+ NULL,
1257
+ NULL
1258
+ );
1259
+ if (result.status == OSEO_STATUS_NORMAL) result = blocked;
1260
+ /* Reaching the turn again means every delivery was retrieved or
1261
+ * dropped by an agent that finished first. */
1262
+ }
1263
+ cluster_unlock(cluster);
1264
+ return result;
1265
+ }
1266
+
1267
+ static OseoResult agent_get_report(OseoContext *context, Agent *self) {
1268
+ OseoResult result = oseo_internal_agent_yield(context);
1269
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1270
+ AgentCluster *cluster = self->cluster;
1271
+ cluster_lock(cluster);
1272
+ AgentReport *report = cluster->reports_head;
1273
+ if (report != NULL) {
1274
+ cluster->reports_head = report->next;
1275
+ if (cluster->reports_head == NULL) cluster->reports_tail = NULL;
1276
+ }
1277
+ cluster_unlock(cluster);
1278
+ if (report == NULL) return normal(oseo_null());
1279
+ result = oseo_string_from_units(context, report->units, report->length);
1280
+ free(report);
1281
+ return result;
1282
+ }
1283
+
1284
+ static OseoResult agent_report(
1285
+ OseoContext *context,
1286
+ Agent *self,
1287
+ OseoValue value
1288
+ ) {
1289
+ OseoResult result = oseo_to_string(context, value);
1290
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1291
+ const OseoString *text = string_object(result.value);
1292
+ if (text->length > (SIZE_MAX - sizeof(AgentReport)) / sizeof(uint16_t)) {
1293
+ return failure(context, "OSEO2001", "Agent report allocation failed.");
1294
+ }
1295
+ AgentReport *report =
1296
+ malloc(sizeof(*report) + text->length * sizeof(uint16_t));
1297
+ if (report == NULL) {
1298
+ return failure(context, "OSEO2001", "Agent report allocation failed.");
1299
+ }
1300
+ report->next = NULL;
1301
+ report->length = text->length;
1302
+ if (text->length > 0u) {
1303
+ memcpy(report->units, text->units, text->length * sizeof(uint16_t));
1304
+ }
1305
+ AgentCluster *cluster = self->cluster;
1306
+ cluster_lock(cluster);
1307
+ if (cluster->reports_tail == NULL) {
1308
+ cluster->reports_head = report;
1309
+ } else {
1310
+ cluster->reports_tail->next = report;
1311
+ }
1312
+ cluster->reports_tail = report;
1313
+ cluster_unlock(cluster);
1314
+ return normal(oseo_undefined());
1315
+ }
1316
+
1317
+ static OseoResult agent_sleep(
1318
+ OseoContext *context,
1319
+ Agent *self,
1320
+ OseoValue value
1321
+ ) {
1322
+ OseoResult result = oseo_internal_to_number(context, value);
1323
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1324
+ double milliseconds = number_value(result.value);
1325
+ if (isnan(milliseconds)) milliseconds = 0.0;
1326
+ if (milliseconds == INFINITY) {
1327
+ return oseo_internal_throw_error(
1328
+ context,
1329
+ OSEO_ERROR_RANGE,
1330
+ "$262.agent.sleep needs a finite time."
1331
+ );
1332
+ }
1333
+ uint64_t deadline = 0u;
1334
+ result = agent_deadline(context, milliseconds, &deadline);
1335
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1336
+ AgentCluster *cluster = self->cluster;
1337
+ cluster_lock(cluster);
1338
+ result = agent_block(context, self, true, deadline, false, NULL, NULL);
1339
+ cluster_unlock(cluster);
1340
+ return result.status == OSEO_STATUS_NORMAL
1341
+ ? normal(oseo_undefined())
1342
+ : result;
1343
+ }
1344
+
1345
+ static OseoResult agent_monotonic_now(OseoContext *context, Agent *self) {
1346
+ OseoResult result = oseo_internal_clock_start(context);
1347
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1348
+ uint64_t now = 0u;
1349
+ if (!context->clock_adapter->monotonic(context->clock_state, &now)) {
1350
+ return failure(
1351
+ context,
1352
+ "OSEO2001",
1353
+ "The host monotonic clock is unavailable."
1354
+ );
1355
+ }
1356
+ uint64_t origin = self->cluster->origin;
1357
+ double elapsed = now > origin ? (double)(now - origin) : 0.0;
1358
+ return normal(oseo_number(elapsed / AGENT_NANOSECONDS_PER_MILLISECOND));
1359
+ }
1360
+
1361
+ OseoResult oseo_internal_agent_builtin_dispatch(
1362
+ OseoContext *context,
1363
+ size_t code_id,
1364
+ OseoValue callee,
1365
+ OseoValue receiver,
1366
+ size_t argument_count,
1367
+ const OseoValue *arguments,
1368
+ OseoValue new_target
1369
+ ) {
1370
+ (void)callee;
1371
+ (void)receiver;
1372
+ if (tag_of(new_target) != OSEO_TAG_UNDEFINED) {
1373
+ return oseo_internal_throw_error(
1374
+ context,
1375
+ OSEO_ERROR_TYPE,
1376
+ "$262.agent function is not a constructor."
1377
+ );
1378
+ }
1379
+ Agent *self = agent_of(context);
1380
+ if (self == NULL) {
1381
+ return failure(
1382
+ context,
1383
+ "OSEO2001",
1384
+ "The test262 agent host is not installed."
1385
+ );
1386
+ }
1387
+ OseoValue first = argument_count > 0u ? arguments[0] : oseo_undefined();
1388
+ switch (code_id) {
1389
+ case OSEO_AGENT_START_CODE_ID:
1390
+ return agent_start(context, self, first);
1391
+ case OSEO_AGENT_BROADCAST_CODE_ID:
1392
+ return agent_broadcast(context, self, argument_count, arguments);
1393
+ case OSEO_AGENT_GET_REPORT_CODE_ID:
1394
+ return agent_get_report(context, self);
1395
+ case OSEO_AGENT_SLEEP_CODE_ID:
1396
+ return agent_sleep(context, self, first);
1397
+ case OSEO_AGENT_MONOTONIC_NOW_CODE_ID:
1398
+ return agent_monotonic_now(context, self);
1399
+ case OSEO_AGENT_RECEIVE_BROADCAST_CODE_ID:
1400
+ if (!is_callable(first)) {
1401
+ return oseo_internal_throw_error(
1402
+ context,
1403
+ OSEO_ERROR_TYPE,
1404
+ "$262.agent.receiveBroadcast needs a function."
1405
+ );
1406
+ }
1407
+ context->agent_broadcast_callback = first;
1408
+ return normal(oseo_undefined());
1409
+ case OSEO_AGENT_REPORT_CODE_ID:
1410
+ return agent_report(context, self, first);
1411
+ case OSEO_AGENT_LEAVING_CODE_ID:
1412
+ self->leaving = true;
1413
+ return normal(oseo_undefined());
1414
+ default:
1415
+ return oseo_unknown_function(context, code_id);
1416
+ }
1417
+ }
1418
+
1419
+
1420
+ typedef struct {
1421
+ const char *name;
1422
+ size_t code_id;
1423
+ size_t length;
1424
+ } AgentFunction;
1425
+
1426
+ static const AgentFunction main_functions[] = {
1427
+ {"start", OSEO_AGENT_START_CODE_ID, 1u},
1428
+ {"broadcast", OSEO_AGENT_BROADCAST_CODE_ID, 2u},
1429
+ {"getReport", OSEO_AGENT_GET_REPORT_CODE_ID, 0u},
1430
+ {"sleep", OSEO_AGENT_SLEEP_CODE_ID, 1u},
1431
+ {"monotonicNow", OSEO_AGENT_MONOTONIC_NOW_CODE_ID, 0u},
1432
+ };
1433
+
1434
+ static const AgentFunction agent_functions[] = {
1435
+ {"receiveBroadcast", OSEO_AGENT_RECEIVE_BROADCAST_CODE_ID, 1u},
1436
+ {"report", OSEO_AGENT_REPORT_CODE_ID, 1u},
1437
+ {"leaving", OSEO_AGENT_LEAVING_CODE_ID, 0u},
1438
+ {"sleep", OSEO_AGENT_SLEEP_CODE_ID, 1u},
1439
+ {"monotonicNow", OSEO_AGENT_MONOTONIC_NOW_CODE_ID, 0u},
1440
+ };
1441
+
1442
+ static OseoResult define_host_property(
1443
+ OseoContext *context,
1444
+ OseoValue object,
1445
+ const char *name,
1446
+ OseoValue value
1447
+ ) {
1448
+ OseoValue slots[3] = {object, value, oseo_undefined()};
1449
+ OseoRootFrame frame = {NULL, slots, 3u};
1450
+ oseo_roots_push(context, &frame);
1451
+ OseoResult result = oseo_internal_ascii_string(context, name);
1452
+ slots[2] = result.value;
1453
+ if (result.status == OSEO_STATUS_NORMAL) {
1454
+ result = oseo_object_define(
1455
+ context,
1456
+ slots[0],
1457
+ slots[2],
1458
+ slots[1],
1459
+ (OseoPropertyAttributes){true, false, true, false}
1460
+ );
1461
+ }
1462
+ oseo_roots_pop(context, &frame);
1463
+ return result;
1464
+ }
1465
+
1466
+ static OseoResult create_host_function(
1467
+ OseoContext *context,
1468
+ const AgentFunction *entry
1469
+ ) {
1470
+ size_t name_length = strlen(entry->name);
1471
+ uint16_t units[24];
1472
+ if (name_length > sizeof(units) / sizeof(*units)) {
1473
+ return failure(context, "OSEO2001", "Built-in name is too long.");
1474
+ }
1475
+ for (size_t index = 0u; index < name_length; index += 1u) {
1476
+ units[index] = (uint16_t)(unsigned char)entry->name[index];
1477
+ }
1478
+ OseoValue environment = oseo_undefined();
1479
+ OseoRootFrame frame = {NULL, &environment, 1u};
1480
+ oseo_roots_push(context, &frame);
1481
+ OseoResult result = oseo_environment_create(context, 0u);
1482
+ environment = result.value;
1483
+ if (result.status == OSEO_STATUS_NORMAL) {
1484
+ result = oseo_function_create(
1485
+ context,
1486
+ entry->code_id,
1487
+ environment,
1488
+ units,
1489
+ name_length,
1490
+ entry->length,
1491
+ OSEO_FUNCTION_INTERNAL,
1492
+ oseo_undefined(),
1493
+ oseo_undefined(),
1494
+ OSEO_FUNCTION_NAME_PREFIX_NONE
1495
+ );
1496
+ }
1497
+ oseo_roots_pop(context, &frame);
1498
+ return result;
1499
+ }
1500
+
1501
+ /*
1502
+ * Installs `$262` on this realm's global object: an ordinary object whose
1503
+ * `agent` object holds the main or the agent function set, and whose
1504
+ * `createRealm` and `global` members come from the realm component. All
1505
+ * are writable and configurable, so a harness include can replace a
1506
+ * member as the upstream atomicsHelper.js replaces `getReport`.
1507
+ */
1508
+ static OseoResult install_host(OseoContext *context, bool main) {
1509
+ OseoRootFrame frame = {NULL, NULL, 0u};
1510
+ OseoResult result = oseo_roots_allocate(context, &frame, 4u);
1511
+ if (result.status != OSEO_STATUS_NORMAL) return result;
1512
+ result = oseo_this_value(context, oseo_undefined());
1513
+ frame.slots[0] = result.value;
1514
+ if (result.status == OSEO_STATUS_NORMAL) {
1515
+ result = oseo_internal_intrinsic(
1516
+ context,
1517
+ OSEO_INTRINSIC_OBJECT_PROTOTYPE
1518
+ );
1519
+ frame.slots[1] = result.value;
1520
+ }
1521
+ if (result.status == OSEO_STATUS_NORMAL) {
1522
+ result = oseo_object_create(context, frame.slots[1]);
1523
+ frame.slots[2] = result.value;
1524
+ }
1525
+ if (result.status == OSEO_STATUS_NORMAL) {
1526
+ result = oseo_object_create(context, frame.slots[1]);
1527
+ frame.slots[1] = result.value;
1528
+ }
1529
+ const AgentFunction *functions = main ? main_functions : agent_functions;
1530
+ size_t count = main
1531
+ ? sizeof(main_functions) / sizeof(*main_functions)
1532
+ : sizeof(agent_functions) / sizeof(*agent_functions);
1533
+ for (size_t index = 0u;
1534
+ result.status == OSEO_STATUS_NORMAL && index < count;
1535
+ index += 1u) {
1536
+ result = create_host_function(context, &functions[index]);
1537
+ frame.slots[3] = result.value;
1538
+ if (result.status == OSEO_STATUS_NORMAL) {
1539
+ result = define_host_property(
1540
+ context,
1541
+ frame.slots[1],
1542
+ functions[index].name,
1543
+ frame.slots[3]
1544
+ );
1545
+ }
1546
+ }
1547
+ if (result.status == OSEO_STATUS_NORMAL) {
1548
+ result = define_host_property(
1549
+ context,
1550
+ frame.slots[2],
1551
+ "agent",
1552
+ frame.slots[1]
1553
+ );
1554
+ }
1555
+ if (result.status == OSEO_STATUS_NORMAL) {
1556
+ result = oseo_internal_realm_host_install(context, frame.slots[2]);
1557
+ }
1558
+ if (result.status == OSEO_STATUS_NORMAL) {
1559
+ result = define_host_property(
1560
+ context,
1561
+ frame.slots[0],
1562
+ "$262",
1563
+ frame.slots[2]
1564
+ );
1565
+ }
1566
+ oseo_roots_release(context, &frame);
1567
+ return result;
1568
+ }
1569
+
1570
+ OseoResult oseo_test262_host_install(
1571
+ OseoContext *context,
1572
+ const OseoAgentProgram *programs,
1573
+ size_t program_count
1574
+ ) {
1575
+ if (context->agent != NULL) {
1576
+ return failure(
1577
+ context,
1578
+ "OSEO2001",
1579
+ "The test262 agent host is already installed."
1580
+ );
1581
+ }
1582
+ AgentCluster *cluster = calloc(1u, sizeof(*cluster));
1583
+ Agent *main = calloc(1u, sizeof(*main));
1584
+ if (cluster == NULL || main == NULL ||
1585
+ !agent_mutex_init(&cluster->lock)) {
1586
+ free(cluster);
1587
+ free(main);
1588
+ return failure(context, "OSEO2001", "Agent cluster allocation failed.");
1589
+ }
1590
+ OseoResult result = oseo_internal_clock_start(context);
1591
+ uint64_t origin = 0u;
1592
+ if (result.status == OSEO_STATUS_NORMAL &&
1593
+ !context->clock_adapter->monotonic(context->clock_state, &origin)) {
1594
+ result = failure(
1595
+ context,
1596
+ "OSEO2001",
1597
+ "The host monotonic clock is unavailable."
1598
+ );
1599
+ }
1600
+ if (result.status != OSEO_STATUS_NORMAL) {
1601
+ agent_mutex_destroy(&cluster->lock);
1602
+ free(cluster);
1603
+ free(main);
1604
+ return result;
1605
+ }
1606
+ cluster->origin = origin;
1607
+ cluster->unhandled_rejection_policy = context->unhandled_rejection_policy;
1608
+ cluster->programs = programs;
1609
+ cluster->program_count = program_count;
1610
+ cluster->main = main;
1611
+ cluster->running = main;
1612
+ main->cluster = cluster;
1613
+ main->context = context;
1614
+ main->state = AGENT_RUNNING;
1615
+ main->main = true;
1616
+ context->agent = main;
1617
+ return install_host(context, true);
1618
+ }
1619
+
1620
+ OseoResult oseo_agent_hole(OseoContext *context, size_t index) {
1621
+ const Agent *self = agent_of(context);
1622
+ if (self == NULL || index >= self->hole_count) {
1623
+ return failure(
1624
+ context,
1625
+ "OSEO2001",
1626
+ "The agent program has no such source hole."
1627
+ );
1628
+ }
1629
+ const AgentHole *hole = &self->holes[index];
1630
+ if (hole->bigint) return oseo_bigint_literal(context, hole->digits, 10u);
1631
+ return normal(oseo_number(hole->number));
1632
+ }
1633
+
1634
+ OseoResult oseo_agent_function_set_source(
1635
+ OseoContext *context,
1636
+ OseoValue function_value,
1637
+ const OseoAgentSegment *runs,
1638
+ size_t run_count,
1639
+ const size_t *holes
1640
+ ) {
1641
+ const Agent *self = agent_of(context);
1642
+ size_t length = 0u;
1643
+ for (size_t index = 0u; index < run_count; index += 1u) {
1644
+ length += runs[index].length;
1645
+ if (index + 1u == run_count) break;
1646
+ if (self == NULL || holes[index] >= self->hole_count) {
1647
+ return failure(
1648
+ context,
1649
+ "OSEO2001",
1650
+ "The agent program has no such source hole."
1651
+ );
1652
+ }
1653
+ const AgentHole *hole = &self->holes[holes[index]];
1654
+ length += strlen(hole->digits) + (hole->bigint ? 1u : 0u);
1655
+ }
1656
+ uint16_t *units = malloc((length == 0u ? 1u : length) * sizeof(uint16_t));
1657
+ if (units == NULL) {
1658
+ return failure(
1659
+ context,
1660
+ "OSEO2001",
1661
+ "Function source allocation failed."
1662
+ );
1663
+ }
1664
+ size_t position = 0u;
1665
+ for (size_t index = 0u; index < run_count; index += 1u) {
1666
+ if (runs[index].length > 0u) {
1667
+ memcpy(
1668
+ units + position,
1669
+ runs[index].units,
1670
+ runs[index].length * sizeof(uint16_t)
1671
+ );
1672
+ position += runs[index].length;
1673
+ }
1674
+ if (index + 1u == run_count) break;
1675
+ const AgentHole *hole = &self->holes[holes[index]];
1676
+ for (const char *digit = hole->digits; *digit != '\0'; digit += 1) {
1677
+ units[position] = (uint16_t)(unsigned char)*digit;
1678
+ position += 1u;
1679
+ }
1680
+ if (hole->bigint) {
1681
+ units[position] = (uint16_t)'n';
1682
+ position += 1u;
1683
+ }
1684
+ }
1685
+ OseoResult result = oseo_function_set_source(
1686
+ context,
1687
+ function_value,
1688
+ units,
1689
+ length
1690
+ );
1691
+ free(units);
1692
+ return result;
1693
+ }