Repository navigation
Expand file tree
/
Copy pathruntime.zig
More file actions
1423 lines (1313 loc) · 64 KB
/
Copy pathruntime.zig
File metadata and controls
1423 lines (1313 loc) · 64 KB
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
//! The Luau state that mod scripts run in
//! ([#498](https://github.com/OpenReliant/openreliant/issues/498)): the sandbox, the time and
//! memory limits, loading each mod's scripts, and `require`.
//!
//! A mod's scripts are compiled once, the first time the mod is opened, and kept as bytecode
//! (`Code`). Each opening of the mod (`Context`), such as the one for each object a mod's object
//! scripts run on, loads its own copy of a script as it requires it, with its own global table. So
//! scripts can't see each other's globals, and an object's scripts can't see another object's.
//! `require` runs a script once for its context and returns its result. It accepts another script
//! from the same mod, by file name with or without the extension and in any case, or an
//! OpenReliant package (`script.Package`). Compile errors are logged when the mod is first opened,
//! and raised again when the script is required.
const std = @import("std");
const Allocator = std.mem.Allocator;
const Io = std.Io;
const log = std.log.scoped(.scripts);
const openreliant = @import("openreliant");
const mods = openreliant.engine.game.bigfile.mods;
const Mod = mods.Mod;
const Objects = openreliant.engine.game.create.Objects;
const gameobj = openreliant.engine.game.gameobj;
const aigeneric = openreliant.engine.game.aigeneric;
const luau = @import("luau.zig");
const State = luau.State;
const script = @import("script.zig");
const values = @import("values.zig");
const objects = @import("objects.zig");
const missiles = @import("missiles.zig");
const turrets = @import("turrets.zig");
const game_module = @import("game.zig");
const presentation_module = @import("presentation.zig");
const storage_module = @import("storage.zig");
const options_module = @import("options.zig");
const running_module = @import("running.zig");
const stored = @import("stored.zig");
const bigfile = openreliant.engine.game.bigfile;
/// The userdata tags, one per kind of userdata, each with its own metatable.
pub const Tag = enum(luau.Tag) {
/// A record, or a struct or array inside one (`records.Values`).
record_value = 1,
/// A table of records, such as the ships (`records.Set`).
record_set = 2,
/// An object's handle (`objects.Handle`).
object = 3,
/// What a hook's handler sees as `e` (`hooks.Event`).
hook_event = 4,
/// What `hooks.add` returns (`hooks.Handle`).
hook_handle = 5,
/// The package `openreliant.interfaces` (`interfaces.Interfaces`).
interfaces = 6,
/// A section of a mod's storage (`storage.zig`).
section = 7,
/// A missile's handle (`missiles.Handle`).
missile = 8,
/// A turret's handle (`turrets.Handle`).
turret = 9,
/// The campaign's missions (`records.missions`), and one of them.
campaign_missions = 10,
campaign_mission = 11,
/// The KILLBOARD's pilots (`records.killboard`), and one of them.
killboard = 12,
killboard_pilot = 13,
/// The combat maneuvers (`records.maneuvers`), and one of them.
maneuvers = 14,
maneuver = 15,
/// The planets (`records.planets`), and one of them.
planets = 16,
planet = 17,
/// The CD player's tracks (`records.cd_player`), and one of them.
cd_player = 18,
cd_player_track = 19,
/// The rooms' views (`records.room_views`), and one of them.
room_views = 20,
room_view = 21,
/// The game's variables (`records.game_variables`), and one of them.
game_variables = 22,
game_variable = 23,
};
/// What an object script's context runs on: an object of the mission, a missile in flight, or a
/// turret.
pub const RunsOn = union(enum) {
object: objects.Handle,
missile: missiles.Handle,
turret: turrets.Handle,
/// Whether it's still in the mission.
pub fn valid(runs_on: RunsOn, all: *const Objects) bool {
return switch (runs_on) {
inline else => |handle| handle.valid(all),
};
}
/// Where it is, while it's valid.
pub fn position(runs_on: RunsOn, all: *const Objects) @Vector(3, f32) {
return switch (runs_on) {
.object => |handle| all.slots[handle.slot].object.position(),
.missile => |handle| all.missiles.records[handle.record].?.slot.object.position(),
.turret => |handle| if (all.slots[handle.object.slot].guns[handle.gun].turret.base()) |base|
base.part().drawn().position
else
all.slots[handle.object.slot].object.position(),
};
}
/// Whether `runs_on` and `other` hold the same object or missile.
pub fn eql(runs_on: RunsOn, other: RunsOn) bool {
return std.meta.eql(runs_on, other);
}
};
/// Which part of the game a state runs scripts for.
pub const Side = enum {
/// Load, global and object scripts, which affect what happens in the game. They have no `os`
/// library, and `math.random` uses a seeded generator so every machine gets the same numbers.
game,
/// Player and menu scripts, which affect what each player sees and hears.
presentation,
};
/// Resource limits for scripts.
pub const Limits = struct {
/// How long a single call into a script may run.
time: Io.Duration,
/// How much memory one mod's scripts may use.
memory: usize,
};
/// How much memory one mod's scripts may use, on every side (`game.limits`,
/// `presentation.limits`, `load.limits`).
pub const memory_per_mod = std.fmt.parseIntSizeSuffix("64MiB", 10) catch unreachable;
pub const Options = struct {
side: Side,
limits: Limits,
/// The seed for `math.random` on the game side.
seed: u64,
/// OpenReliant's version, such as `0.7.0` (`core.package.version`).
version: []const u8,
shared: Shared = .{},
};
/// Runtimes for tests.
pub const testing = struct {
/// One second per call and 1 MiB per mod, plenty for the tests' scripts.
pub const limits: Limits = .{ .time = .fromSeconds(1), .memory = std.fmt.parseIntSizeSuffix("1MiB", 10) catch unreachable };
/// A game-side runtime with `limits`.
pub const options: Options = .{ .side = .game, .limits = limits, .seed = 1, .version = "0.7.0" };
};
/// What every state shares.
pub const Shared = struct {
/// The mods' storage (`storage.zig`); null if it isn't kept.
storage: ?*storage_module.Storage = null,
/// The game's resource archive, with the mods' files taking priority (`vfs.zig`); null if there
/// is none.
files: ?bigfile.Hog = null,
/// The game's folder, where its loose files are read from (`vfs.zig`); null if there is none.
game: ?storage_module.Storage.Folder = null,
/// The original and mod bindings' settings file, shared with the controls screen.
bindings_file: ?*@import("openreliant").engine.profile.File = null,
/// The pages of options the mods offer (`options.zig`); null if there are none.
option_pages: ?*options_module.Registry = null,
/// The game modes the mods register (`game_modes.zig`); null if they aren't kept.
modes: ?*@import("game_modes.zig").Registry = null,
};
/// The interrupt callback reads the clock on every this many calls, since reading it on every call
/// would be slow.
const interrupt_stride = 64;
/// Luau supports 256 memory categories: 0 for the engine and one per mod. Mods past the 255th
/// share the last one.
const max_category = 255;
/// The longest module name and chunk name.
const max_module_name = 255;
const max_chunk_name = 255;
/// The message for an error from `Context.readModFile`; null for any other error.
pub fn fileProblem(err: anyerror) ?[]const u8 {
return switch (err) {
error.InvalidFileName => "a file name must be printable ASCII, with no folder",
error.FileNotFound => "the mod has no file with that name",
else => null,
};
}
/// Marks a module as currently loading in `Context.loaded`, to detect circular requires.
var loading: u8 = 0;
pub const Runtime = struct {
gpa: Allocator,
io: Io,
state: *State,
options: Options,
/// The mods, in load order.
mods: []const Mod,
/// The value `require` returns for each package, if set (`setPackage`).
packages: std.EnumArray(script.Package, ?luau.Ref) = .initFill(null),
/// The opened mods (`open`).
contexts: std.ArrayList(*Context) = .empty,
/// Each mod's scripts compiled, by the mod's index in `mods`, once it has been opened.
code: std.AutoHashMapUnmanaged(u16, Code) = .empty,
random: std.Random.DefaultPrng,
/// The call in progress, if any (`begin`).
running: ?Running = null,
/// How many calls are in progress, each inside the last.
calls: u32 = 0,
/// The contexts closed while calls ran, whose references wait until no call runs (`close`),
/// linked through `Context.next_closing`.
closing: ?*Context = null,
/// Interrupt calls since the clock was last read.
interrupts: u32 = 0,
/// The error handler every call into a script runs with (`luau.State.traceback`), made once so
/// that a call takes no memory before it is protected.
traceback: luau.Ref = undefined,
/// The objects that handles stand for, while a game runs (`objects.zig`).
objects: ?*Objects = null,
/// The game the scripts run in, while one runs, for the game side.
game: ?*game_module.Game = null,
/// The presentation side, for its own state.
presentation: ?*presentation_module.Presentation = null,
/// What orders run against, while a mission runs.
orders: ?aigeneric.Context = null,
/// The scripts that run in the state, with their events, interfaces and timers.
runner: ?*running_module.Runner = null,
/// The handles made, by slot (`objects.zig`).
handles: ?luau.Ref = null,
/// The missiles' handles made, by record (`missiles.zig`).
missile_handles: ?luau.Ref = null,
/// The turrets' handles made, by object and gun (`turrets.zig`).
turret_handles: ?luau.Ref = null,
/// The handle every player script's `self` is, made the first time one asks, which follows the
/// player's ship from mission to mission (`followPlayer`).
player_self: ?luau.Ref = null,
custom_orders: @import("orders.zig").Registry = .{},
input_actions: @import("openreliant").engine.input.actions.Registry = .{},
registries: @import("registries.zig").Registry = .{},
/// The mods' post effects (`postprocessing.zig`).
post_effects: @import("postprocessing.zig").Registry = .{},
/// The mods' surface and lighting functions (`shaders.zig`).
mod_shaders: @import("shaders.zig").Registry = .{},
const Running = struct {
/// The memory category of the running mod.
category: u8,
/// When the call began, moved on by the time the calls inside it took, which the time limit
/// counts from.
started: Io.Clock.Timestamp,
/// Whether the call ran out of time (`interrupt`).
timed_out: bool = false,
/// The call as it goes on after a call inside it that took `took`: its clock moves on by as
/// much, so that the time limit counts only its own time.
fn after(running: Running, took: Io.Clock.Duration) Running {
var resumed = running;
resumed.started = running.started.addDuration(took);
return resumed;
}
};
/// A call begun (`begin`): the call it interrupts, if any, and when it began.
const Begun = struct {
outer: ?Running,
began: Io.Clock.Timestamp,
};
/// Luau's functions that scripts don't get, on either side: a function's environment is the
/// globals of the script that made it, so with them a mod could read and change another mod's
/// globals through any function an interface hands it.
const withheld = [_][:0]const u8{ "getfenv", "setfenv" };
/// Creates a sandboxed state with Luau's standard libraries, less `withheld`, and OpenReliant's
/// `require` and `print`.
pub fn create(gpa: Allocator, io: Io, opened: []const Mod, options: Options) Allocator.Error!*Runtime {
const runtime = try gpa.create(Runtime);
errdefer gpa.destroy(runtime);
runtime.* = .{ .gpa = gpa, .io = io, .state = undefined, .options = options, .mods = opened, .random = .init(options.seed) };
runtime.state = State.create(allocate, runtime) orelse return error.OutOfMemory;
const state = runtime.state;
state.setCallbackData(runtime);
state.setInterrupt(interrupt);
state.setPanic(panic);
state.inheritThreadData();
state.openLibraries();
state.pushFunction(State.traceback, "traceback");
runtime.traceback = state.ref(-1);
state.pop(1);
state.pushFunction(luau.wrap(require), "require");
state.setGlobal("require");
state.pushFunction(luau.wrap(print), "print");
state.setGlobal("print");
for (withheld) |name| {
state.pushNil();
state.setGlobal(name);
}
storage_module.Storage.register(state);
if (options.side == .game) {
state.pushNil();
state.setGlobal("os");
_ = state.getGlobal("math");
state.pushFunction(luau.wrap(random), "random");
state.rawSetField(-2, "random");
state.pushNil();
state.rawSetField(-2, "randomseed");
state.pop(1);
}
state.sandbox();
return runtime;
}
pub fn destroy(runtime: *Runtime) void {
runtime.registries.deinit(runtime);
runtime.post_effects.deinit(runtime.gpa);
runtime.mod_shaders.deinit(runtime.gpa);
runtime.custom_orders.deinit(runtime);
runtime.state.close();
for (runtime.contexts.items) |context| runtime.gpa.destroy(context);
runtime.contexts.deinit(runtime.gpa);
var code = runtime.code.valueIterator();
while (code.next()) |held| held.deinit(runtime.gpa);
runtime.code.deinit(runtime.gpa);
runtime.gpa.destroy(runtime);
}
/// Points the player scripts' `self` at the player's ship as it is now, as a mission starts. A
/// player script runs until the game ends, while each mission fills the ship's slot anew.
pub fn followPlayer(runtime: *Runtime) void {
const all = runtime.objects orelse return;
const kept = runtime.player_self orelse return;
_ = runtime.state.pushRef(kept);
objects.follow(runtime.state, -1, all);
runtime.state.pop(1);
}
/// Lets the player scripts' `self` go, as the player scripts stop.
pub fn dropPlayerSelf(runtime: *Runtime) void {
if (runtime.player_self) |kept| runtime.release(kept);
runtime.player_self = null;
}
/// Releases a reference so its value can be collected.
pub fn release(runtime: *Runtime, kept: luau.Ref) void {
runtime.state.unref(kept);
}
/// Pops a value and makes it what `require` returns for `package`.
pub fn setPackage(runtime: *Runtime, package: script.Package) void {
runtime.packages.set(package, runtime.state.ref(-1));
runtime.state.pop(1);
}
/// Opens a mod for scripts of `family`, so that they can be required. `mod` is the mod's index
/// in `mods`. An object script's context names its object (`object`). The mod's scripts are
/// compiled the first time it's opened (`compiled`). Its thread and its table of modules are
/// made in protected mode as the engine's (`protect`), as a script can open one, such as with
/// `object:add_script`, where running out of memory would otherwise skip what frees the context.
pub fn open(runtime: *Runtime, mod: u16, family: script.Family, runs_on: ?RunsOn) Allocator.Error!*Context {
_ = try runtime.compiled(mod);
const context = try runtime.gpa.create(Context);
errdefer runtime.gpa.destroy(context);
try runtime.contexts.ensureUnusedCapacity(runtime.gpa, 1);
var made: Opened = .{};
if (!runtime.protect(luau.wrap(makeContext), &made)) {
if (made.thread_ref) |kept| runtime.release(kept);
return error.OutOfMemory;
}
const thread = made.thread.?;
context.* = .{ .runtime = runtime, .mod = mod, .family = family, .runs_on = runs_on, .thread = thread, .thread_ref = made.thread_ref.?, .loaded = made.loaded.? };
thread.setThreadData(context);
thread.setMemoryCategory(context.category());
runtime.contexts.appendAssumeCapacity(context);
return context;
}
/// The scripts of mod `mod` compiled, compiling them the first time. A script that doesn't
/// compile is logged, and kept, so that requiring it raises its error.
fn compiled(runtime: *Runtime, mod: u16) Allocator.Error!*const Code {
const entry = try runtime.code.getOrPut(runtime.gpa, mod);
if (entry.found_existing) return entry.value_ptr;
entry.value_ptr.* = runtime.compile(mod) catch |err| {
runtime.code.removeByPtr(entry.key_ptr);
return err;
};
return entry.value_ptr;
}
/// Reads and compiles the scripts of the folder mods compiled so far again, as they're
/// reloaded: the scripts that start from then on, and the modules `require` runs, take the
/// new code. A mod's archive doesn't change while OpenReliant runs.
pub fn recompileFolders(runtime: *Runtime) Allocator.Error!void {
var entries = runtime.code.iterator();
while (entries.next()) |entry| {
if (runtime.mods[entry.key_ptr.*].source != .folder) continue;
const code = try runtime.compile(entry.key_ptr.*);
entry.value_ptr.deinit(runtime.gpa);
entry.value_ptr.* = code;
}
}
/// Reads and compiles the scripts of `mod`.
fn compile(runtime: *Runtime, mod: u16) Allocator.Error!Code {
var code: Code = .{};
errdefer code.deinit(runtime.gpa);
const opened = &runtime.mods[mod];
var names = opened.scripts();
while (names.next()) |name| {
var module_buffer: [max_module_name:0]u8 = undefined;
const module = moduleName(&module_buffer, name) orelse {
log.warn("{s}: skipping {s}: the name is too long", .{ opened.name, name });
continue;
};
const source = opened.readFile(runtime.gpa, name) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
else => {
log.warn("{s}: skipping {s}: {s}", .{ opened.name, name, @errorName(err) });
continue;
},
} orelse continue;
defer runtime.gpa.free(source);
const bytecode = luau.compile(source) orelse return error.OutOfMemory;
errdefer bytecode.free();
var chunk_buffer: [max_chunk_name:0]u8 = undefined;
const chunk = std.mem.printSentinel(&chunk_buffer, "={s}/{s}", .{ opened.name, name }, 0) catch "=script";
try code.add(runtime.gpa, module, chunk, bytecode);
runtime.check(chunk, bytecode.bytes);
}
return code;
}
/// Loads `bytecode` once to log its compile error, if it has one.
fn check(runtime: *Runtime, chunk: [:0]const u8, bytecode: []const u8) void {
const state = runtime.state;
var request: LoadRequest = .{ .chunk = chunk, .bytecode = bytecode };
if (state.protectedCallC(luau.wrap(checkChunk), &request) != .ok) {
log.warn("{s}: out of memory checking the script", .{chunk[1..]});
state.pop(1);
}
}
/// Closes a mod opened for scripts that stop before the others, such as a mission's: its
/// scripts can be collected, and it can't be called again. The context itself stays until the
/// runtime is destroyed, since coroutines its scripts made may still point to it.
///
/// A script can stop its own scripts while it runs, such as a missile's script that sets off
/// its missile, which stops the missile's scripts. Its thread then runs on, so a context closed
/// while calls run keeps its references until no call runs (`letGoClosing`): Luau can't then
/// collect a thread in the middle of a call.
pub fn close(runtime: *Runtime, context: *Context) void {
if (context.closed) return;
runtime.custom_orders.removeContext(runtime, context);
runtime.input_actions.removeOwner(context);
runtime.registries.removeSince(runtime, context, 0);
runtime.post_effects.removeContext(context);
runtime.mod_shaders.removeContext(runtime.gpa, context);
context.closed = true;
if (runtime.calls == 0) return runtime.letGo(context);
context.next_closing = runtime.closing;
runtime.closing = context;
}
/// Lets go of what a closed context holds in the state: its thread and its tables can then be
/// collected.
fn letGo(runtime: *Runtime, context: *Context) void {
const state = runtime.state;
state.unref(context.loaded);
state.unref(context.thread_ref);
if (context.callbacks) |callbacks| state.unref(callbacks);
context.callbacks = null;
if (context.console) |console| state.unref(console);
context.console = null;
}
/// Lets go of the contexts closed while calls ran (`close`), once none runs.
fn letGoClosing(runtime: *Runtime) void {
while (runtime.closing) |context| {
runtime.closing = context.next_closing;
context.next_closing = null;
runtime.letGo(context);
}
}
/// Makes a value in protected mode, with `build` and its `arguments` pushing it, and returns a
/// reference to it, or null if memory runs out. The value is the engine's, so it counts
/// against no mod's memory.
pub fn make(runtime: *Runtime, comptime build: anytype, arguments: anytype) ?luau.Ref {
const Request = struct {
arguments: @TypeOf(arguments),
made: ?luau.Ref = null,
fn run(state: *State) i32 {
const request = state.toLightUserdata(@This(), 1).?;
@call(.auto, build, .{state} ++ request.arguments);
request.made = state.ref(-1);
state.pop(1);
return 0;
}
};
var request: Request = .{ .arguments = arguments };
if (!runtime.protect(luau.wrap(Request.run), &request)) return null;
return request.made;
}
/// Calls `function` with `data` in protected mode on the state's main thread, as the engine's
/// own work, which counts against no mod's memory. Where memory runs out, its error is popped
/// and the result is false.
fn protect(runtime: *Runtime, function: luau.Function, data: *anyopaque) bool {
const outer = runtime.running;
runtime.running = null;
defer runtime.running = outer;
if (runtime.state.protectedCallC(function, data) == .ok) return true;
runtime.state.pop(1);
return false;
}
/// Starts `math.random` on the game side again from `seed`.
pub fn reseed(runtime: *Runtime, seed: u64) void {
runtime.random = .init(seed);
}
/// Runs the script `name` like `require` does, and returns a reference to its result. Returns
/// null if the script fails; the error is logged.
pub fn run(runtime: *Runtime, context: *Context, name: []const u8) ?luau.Ref {
if (context.closed) return null;
const registrations = runtime.custom_orders.entries.items.len;
const actions_generation = runtime.input_actions.generation;
const registrations_presentation = runtime.registries.entries.items.len;
const effects_before = runtime.post_effects.entries.items.len;
const shaders_before = runtime.mod_shaders.entries.items.len;
const thread = context.thread;
_ = thread.getGlobal("require");
thread.pushString(name);
if (runtime.protectedRun(context, 1, 1).status != .ok) {
runtime.custom_orders.removeSince(runtime, context, registrations);
runtime.input_actions.removeSince(context, actions_generation);
runtime.registries.removeSince(runtime, context, registrations_presentation);
runtime.post_effects.removeSince(context, effects_before);
runtime.mod_shaders.removeSince(runtime.gpa, context, shaders_before);
runtime.recover(context, thread);
return null;
}
defer thread.pop(1);
return thread.ref(-1);
}
/// Calls the referenced function as the context's mod, with `arguments`: each a reference, a
/// number or a boolean, none of which takes memory to push (`make` makes the rest). Returns
/// what the function returned, or `failed` if it raised an error, which is logged.
pub fn call(runtime: *Runtime, context: *Context, function: luau.Ref, arguments: anytype) Called {
if (context.closed) return .failed;
const thread = context.thread;
if (!thread.checkStack(arguments.len + 3)) return .failed;
_ = thread.pushRef(function);
return runtime.callPushed(context, arguments);
}
/// Calls the referenced function with no arguments as the context's mod, and returns a copy of
/// what it returned as plain data (`stored.capture`), made in `gpa`: nil for nothing, and null
/// where it failed or returned what isn't plain data, which is logged.
pub fn callKeeping(runtime: *Runtime, context: *Context, function: luau.Ref, gpa: Allocator) ?stored.Value {
if (context.closed) return null;
const thread = context.thread;
if (!thread.checkStack(3)) return null;
_ = thread.pushRef(function);
if (runtime.protectedRun(context, 0, 1).status != .ok) {
runtime.recover(context, thread);
return null;
}
const returned = thread.ref(-1);
thread.pop(1);
defer runtime.release(returned);
return runtime.keep(context, returned, gpa, "on_save");
}
/// Calls a registered function and validates its returned value inside a protected boundary.
/// The value is kept for the check once the call has ended, so that keeping it can't take the
/// mod past its memory limit outside a protected call.
pub fn callResult(runtime: *Runtime, context: *Context, table: luau.Ref, key: [:0]const u8, comptime T: type, arguments: anytype) ?T {
if (context.closed) return null;
const thread = context.thread;
if (!thread.checkStack(arguments.len + 4)) return null;
_ = thread.pushRef(table);
if (thread.rawGetField(-1, key) != .function) {
thread.pop(2);
return null;
}
thread.remove(-2);
inline for (arguments) |argument| pushArgument(thread, argument);
if (runtime.protectedRun(context, arguments.len, 1).status != .ok) {
runtime.recover(context, thread);
return null;
}
defer thread.pop(1);
const ref = thread.ref(-1);
defer runtime.release(ref);
const Request = struct {
ref: luau.Ref,
result: ?T = null,
fn read(state: *State) i32 {
const request = state.toLightUserdata(@This(), 1).?;
_ = state.pushRef(request.ref);
request.result = values.read(state, T, -1, "callback result");
state.pop(1);
return 0;
}
};
var request: Request = .{ .ref = ref };
if (thread.protectedCallC(luau.wrap(Request.read), &request) != .ok) {
runtime.recover(context, thread);
return null;
}
return request.result;
}
/// A copy of the referenced value as plain data (`stored.capture`), made in `gpa`; null where
/// it isn't plain data, which is logged as the context's error, naming `label`.
pub fn keep(runtime: *Runtime, context: *Context, value: luau.Ref, gpa: Allocator, label: []const u8) ?stored.Value {
const thread = context.thread;
if (!thread.checkStack(2)) return null;
var request: KeepRequest = .{ .value = value, .gpa = gpa, .label = label };
if (thread.protectedCallC(luau.wrap(keepValue), &request) != .ok) {
runtime.recover(context, thread);
return null;
}
return request.kept;
}
/// Runs `source`, a line of Luau typed into the console, as the context's mod: as an expression,
/// whose values are written to `w` separated by tabs, or else as statements. Its global
/// variables are kept for the next line, apart from the scripts' (`Context.console`). Returns
/// false where it doesn't compile or fails, which is logged as the scripts' errors are.
pub fn evaluate(runtime: *Runtime, context: *Context, source: []const u8, w: *Io.Writer) Allocator.Error!bool {
if (context.closed) return false;
const expression = try std.mem.concat(runtime.gpa, u8, &.{ "return ", source });
defer runtime.gpa.free(expression);
const as_expression = luau.compile(expression) orelse return error.OutOfMemory;
defer as_expression.free();
const as_statements = luau.compile(source) orelse return error.OutOfMemory;
defer as_statements.free();
const thread = context.thread;
if (!thread.checkStack(console_stack)) return error.OutOfMemory;
var request: EvaluateRequest = .{ .context = context, .tried = .{ as_expression.bytes, as_statements.bytes } };
if (thread.protectedCallC(luau.wrap(loadConsoleLine), &request) != .ok) {
runtime.recover(context, thread);
return false;
}
const base = thread.top();
defer thread.setTop(base);
_ = thread.pushRef(request.function.?);
runtime.release(request.function.?);
const begun = runtime.begin(context);
defer _ = runtime.end(begun);
if (thread.protectedCallWith(0, luau.all_results, runtime.traceback) != .ok) {
runtime.recover(context, thread);
return false;
}
// Each value is written as `tostring` gives it, called in protected mode, since a
// metatable's `__tostring` can fail.
const results = thread.top();
var at = base + 1;
while (at <= results) : (at += 1) {
if (!thread.checkStack(console_stack)) return error.OutOfMemory;
if (at > base + 1) w.writeByte('\t') catch {};
_ = thread.getGlobal("tostring");
thread.pushCopy(at);
if (thread.protectedCallWith(1, 1, runtime.traceback) != .ok) {
runtime.recover(context, thread);
return false;
}
w.writeAll(thread.toString(-1) orelse "") catch {};
thread.pop(1);
}
return true;
}
/// `call`, for the function at `key` of the referenced table, such as an event's handler.
/// Returns null if the table has no function there.
pub fn callIn(runtime: *Runtime, context: *Context, table: luau.Ref, key: [:0]const u8, arguments: anytype) ?Called {
if (context.closed) return .failed;
const thread = context.thread;
if (!thread.checkStack(arguments.len + 4)) return .failed;
_ = thread.pushRef(table);
const found = thread.rawGetField(-1, key);
thread.remove(-2);
if (found != .function) {
thread.pop(1);
return null;
}
return runtime.callPushed(context, arguments);
}
/// Calls the function on top of the context's thread with `arguments` (`call`).
fn callPushed(runtime: *Runtime, context: *Context, arguments: anytype) Called {
const thread = context.thread;
inline for (arguments) |argument| pushArgument(thread, argument);
const ran = runtime.protectedRun(context, arguments.len, 1);
if (ran.status != .ok) {
runtime.recover(context, thread);
return if (ran.timed_out) .timed_out else .failed;
}
defer thread.pop(1);
return switch (thread.typeOf(-1)) {
.nil => .returned_nil,
.boolean => if (thread.toBoolean(-1)) .returned else .returned_false,
else => .returned,
};
}
/// How a call into a script went (`protectedRun`): its status, and whether it ran out of time.
const Ran = struct { status: luau.Status, timed_out: bool };
/// Calls the function below the top `arguments` of the context's thread as the context's mod
/// (`begin`, `end`), in protected mode, leaving `results` results as `State.protectedCall`
/// does.
fn protectedRun(runtime: *Runtime, context: *const Context, arguments: i32, results: i32) Ran {
const begun = runtime.begin(context);
const status = context.thread.protectedCallWith(arguments, results, runtime.traceback);
return .{ .status = status, .timed_out = runtime.end(begun) };
}
/// After a failed call: logs the error, and runs a full garbage collection so that a script
/// that hit the memory limit doesn't leave its garbage for the mod's next script.
fn recover(runtime: *Runtime, context: *const Context, thread: *State) void {
context.report(thread);
runtime.state.collectGarbage();
}
/// Starts a call into a mod's scripts: its allocations count against the mod's memory, and the
/// time limit starts. Returns the call it interrupts, if any, which `end` resumes: a hook's
/// handler can run the game's function, whose own hooks call other handlers. A call that
/// begins while no other runs first lets go of the contexts closed meanwhile (`close`).
fn begin(runtime: *Runtime, context: *const Context) Begun {
if (runtime.calls == 0) runtime.letGoClosing();
runtime.calls += 1;
const now: Io.Clock.Timestamp = .now(runtime.io, .awake);
const begun: Begun = .{ .outer = runtime.running, .began = now };
runtime.running = .{ .category = context.category(), .started = now };
runtime.interrupts = 0;
return begun;
}
/// Ends the call `begun` started, and goes on with the call it interrupted, whose clock stood
/// still meanwhile: time spent in the handlers it ran, other mods' included, doesn't count
/// against it. Returns whether the call ran out of time.
fn end(runtime: *Runtime, begun: Begun) bool {
const timed_out = if (runtime.running) |running| running.timed_out else false;
runtime.calls -= 1;
runtime.running = if (begun.outer) |outer| outer.after(begun.began.untilNow(runtime.io)) else null;
return timed_out;
}
/// Luau's allocator, using C's allocator. Refuses allocations that would take the running mod
/// over its memory limit (`Limits.memory`).
fn allocate(data: ?*anyopaque, ptr: ?*anyopaque, old: usize, new: usize) callconv(.c) ?*anyopaque {
const runtime: *Runtime = @ptrCast(@alignCast(data.?));
if (new == 0) {
std.c.free(ptr);
return null;
}
const held = if (ptr == null) 0 else old;
if (runtime.running) |running| if (new > held) {
if (runtime.state.totalBytes(running.category) + (new - held) > runtime.options.limits.memory) return null;
};
return std.c.realloc(ptr, new);
}
/// Stops a call that runs over its time limit (`Limits.time`).
fn interrupt(state: *State, collecting: bool) void {
if (collecting) return;
const runtime = state.callbackData(Runtime).?;
const running = if (runtime.running) |*held| held else return;
runtime.interrupts +%= 1;
if (runtime.interrupts % interrupt_stride != 0) return;
if (running.started.untilNow(runtime.io).raw.nanoseconds < runtime.options.limits.time.nanoseconds) return;
running.timed_out = true;
state.raise("script timed out after {f}", .{runtime.options.limits.time});
}
/// Logs an error that no protected call caught, as Luau aborts the process after it. Every
/// call into a script is protected, so it's a bug of OpenReliant's, and the log keeps its
/// message.
fn panic(state: *State, status: luau.Status) void {
const message = if (state.typeOf(-1) == .string) state.toString(-1).? else switch (status) {
.memory_error => "out of memory",
.handler_error => "an error in the error handler",
else => "an error that isn't a string",
};
log.err("a script's error was raised outside every protected call, and OpenReliant stops: {s}", .{message});
}
/// How much memory the scripts of `context`'s mod have left (`Limits.memory`).
pub fn memoryLeft(runtime: *const Runtime, context: *const Context) usize {
return runtime.options.limits.memory -| runtime.state.totalBytes(context.category());
}
};
/// What a call returned (`Runtime.call`).
pub const Called = enum {
/// It raised an error, which is logged.
failed,
/// It ran out of time (`Limits.time`), which is logged as an error is. A call can be slow once
/// for reasons that aren't its own, such as the system or a collection, so a handler that runs
/// out of time is removed only once it does `max_timeouts` times in a row (`Timeouts`).
timed_out,
/// It returned a value other than nil and `false`.
returned,
/// It returned nil, or nothing.
returned_nil,
/// It returned `false`, which stops a hook's later handlers.
returned_false,
/// Whether it raised an error, running out of time included.
pub fn raised(called: Called) bool {
return called == .failed or called == .timed_out;
}
};
/// How many calls in a row a handler may run out of time before it's removed (`Called.timed_out`).
/// Many handlers that each keep to the limit can still hold up a frame; a budget across all of
/// them isn't kept yet ([#1077](https://github.com/OpenReliant/openreliant/issues/1077)).
pub const max_timeouts: u8 = 3;
/// How many calls in a row of one of a mod's functions ran out of time, such as a hook's handler or
/// an engine handler, which keeps a function that is slow once: it's let go of where a call fails,
/// or where `max_timeouts` calls in a row run out of time.
pub const Timeouts = struct {
in_a_row: u8 = 0,
/// Counts a call, which went as `called` says, and returns whether the function is to be let go
/// of.
pub fn removes(timeouts: *Timeouts, called: Called) bool {
switch (called) {
.failed => return true,
.timed_out => {
timeouts.in_a_row +|= 1;
return timeouts.in_a_row >= max_timeouts;
},
.returned, .returned_nil, .returned_false => {
timeouts.in_a_row = 0;
return false;
},
}
}
/// Why a function goes after `called` (`removes`), as the log says it.
pub fn why(called: Called) []const u8 {
return if (called == .timed_out) timed_out_in_a_row else "failed";
}
const timed_out_in_a_row = std.fmt.comptimePrint("ran out of time {d} times in a row", .{max_timeouts});
};
/// Pushes an argument of `Runtime.call`.
fn pushArgument(state: *State, argument: anytype) void {
const T = @TypeOf(argument);
switch (@typeInfo(T)) {
.float, .int, .comptime_float, .comptime_int => state.pushNumber(argument),
.bool => state.pushBoolean(argument),
.optional => if (argument) |held| pushArgument(state, held) else state.pushNil(),
else => if (T == luau.Ref) {
_ = state.pushRef(argument);
} else @compileError("make a reference to pass a " ++ @typeName(T)),
}
}
/// The engine handlers a script returned, as references.
pub const Handlers = std.EnumArray(script.Handler, ?luau.Ref);
/// The longest name of an interface or of an event.
pub const max_name = 64;
/// A name of up to `max_name` bytes, kept in place, with a zero after it for Luau.
pub const Name = struct {
bytes: [max_name:0]u8 = @splat(0),
len: u8 = 0,
/// `text` as a name, or null if it's too long.
pub fn of(text: []const u8) ?Name {
if (text.len > max_name) return null;
var name: Name = .{ .len = @intCast(text.len) };
@memcpy(name.bytes[0..text.len], text);
return name;
}
pub fn slice(name: *const Name) [:0]const u8 {
return name.bytes[0..name.len :0];
}
};
/// What a script offers in the table it returns (`Context.offerOf`), as references.
pub const Offered = struct {
handlers: Handlers = .initFill(null),
/// A copy of its `event_handlers`: functions by event name.
event_handlers: ?luau.Ref = null,
/// Its `interface`, and the `interface_name` it goes by.
interface: ?Interface = null,
pub const Interface = struct {
name: Name,
table: luau.Ref,
};
/// Lets go of what it holds.
pub fn release(offered: *Offered, runtime: *Runtime) void {
for (std.enums.values(script.Handler)) |handler| {
if (offered.handlers.get(handler)) |function| runtime.release(function);
}
if (offered.event_handlers) |table| runtime.release(table);
if (offered.interface) |interface| runtime.release(interface.table);
offered.* = .{};
}
};
/// What's wrong with the table a script returned.
const Failure = union(enum) {
returns: []const u8,
key: []const u8,
offer: []const u8,
table: struct { offer: script.Offer, type_name: []const u8 },
handler: []const u8,
function: []const u8,
event: []const u8,
interface_name: []const u8,
half_interface,
};
/// A mod opened for one script family (`Runtime.open`), or for its scripts on one object.
pub const Context = struct {
runtime: *Runtime,
/// The mod's index in `Runtime.mods`.
mod: u16,
family: script.Family,
/// What an object script's context runs on: an object, a missile for a missile script, or a
/// turret for a turret script; null for the other families.
runs_on: ?RunsOn = null,
/// The thread the mod's calls run on. Its allocations count against the mod.
thread: *State,
thread_ref: luau.Ref,
/// The modules `require` has run, with their results.
loaded: luau.Ref = undefined,
/// The functions its scripts registered for timers, by name (`async.zig`); null until the
/// first.
callbacks: ?luau.Ref = null,
/// The thread whose globals keep the variables of the Luau typed into the console in this
/// context (`Runtime.evaluate`); null until the first line.
console: ?luau.Ref = null,
/// Whether it has been closed (`Runtime.close`).
closed: bool = false,
/// The next context closed while calls ran (`Runtime.closing`).
next_closing: ?*Context = null,
pub fn modOf(context: *const Context) *const Mod {
return &context.runtime.mods[context.mod];
}
/// Reads the file `name` of the context's mod into `gpa`. Fails with `error.InvalidFileName`
/// if `name` isn't a plain file name, and with `error.FileNotFound` if the mod has no such
/// file (`fileProblem`).
pub fn readModFile(context: *const Context, gpa: Allocator, name: []const u8) ![]u8 {
if (!openreliant.hog.validName(name)) return error.InvalidFileName;
return (try context.modOf().readFile(gpa, name)) orelse error.FileNotFound;
}
/// The mod's memory category.
fn category(context: *const Context) u8 {
return @intCast(@min(@as(usize, context.mod) + 1, max_category));
}
/// Checks the table a script returned, and returns references to what it offers. Returns null
/// if the table has something a script of this family may not return, or out of memory; the
/// problem is logged.
pub fn offerOf(context: *Context, name: []const u8, returned: luau.Ref) ?Offered {
const state = context.thread;
const mod = context.modOf();
var offered: Offered = .{};
const base = state.top();
defer state.setTop(base);
if (!state.checkStack(offer_stack)) {
log.warn("{s}: {s}: out of memory", .{ mod.name, name });
return null;
}
var interface_name: ?Name = null;
const failure: Failure = check: {
switch (state.pushRef(returned)) {
.nil => return offered,
.table => {},
// What `require` returns for a script that returns nothing.
.boolean => if (state.toBoolean(-1)) return offered else break :check .{ .returns = state.typeName(-1) },
else => break :check .{ .returns = state.typeName(-1) },
}
state.pushNil();
while (state.next(base + 1)) {
const key = state.toString(-2) orelse break :check .{ .key = state.typeName(-2) };
const offer = std.meta.stringToEnum(script.Offer, key) orelse break :check .{ .offer = key };
if (!offer.offeredBy(context.family)) break :check .{ .offer = key };