forked from roc-lang/roc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.zig
More file actions
2070 lines (1784 loc) · 78.7 KB
/
main.zig
File metadata and controls
2070 lines (1784 loc) · 78.7 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
//! Roc command line interface for the new compiler. Entrypoint of the Roc binary.
//! Build with `zig build -Dllvm -Dfuzz -Dsystem-afl=false`.
//! Result is at `./zig-out/bin/roc`
const std = @import("std");
const build_options = @import("build_options");
const builtin = @import("builtin");
const base = @import("base");
const collections = @import("collections");
const reporting = @import("reporting");
const parse = @import("parse");
const tracy = @import("tracy");
const fs_mod = @import("fs");
const compile = @import("compile");
const can = @import("can");
const check = @import("check");
const bundle = @import("bundle");
const unbundle = @import("unbundle");
const ipc = @import("ipc");
const fmt = @import("fmt");
const eval = @import("eval");
const layout = @import("layout");
const builtins = @import("builtins");
const cli_args = @import("cli_args.zig");
const bench = @import("bench.zig");
const linker = @import("linker.zig");
const Can = can.Can;
const Check = check.Check;
const SharedMemoryAllocator = ipc.SharedMemoryAllocator;
const Filesystem = fs_mod.Filesystem;
const ModuleEnv = can.ModuleEnv;
const BuildEnv = compile.BuildEnv;
const TimingInfo = compile.package.TimingInfo;
const CacheManager = compile.CacheManager;
const CacheConfig = compile.CacheConfig;
const tokenize = parse.tokenize;
const Interpreter = eval.Interpreter;
const LayoutStore = layout.Store;
const RocOps = builtins.host_abi.RocOps;
const RocAlloc = builtins.host_abi.RocAlloc;
const RocDealloc = builtins.host_abi.RocDealloc;
const RocRealloc = builtins.host_abi.RocRealloc;
const RocDbg = builtins.host_abi.RocDbg;
const RocExpectFailed = builtins.host_abi.RocExpectFailed;
const RocCrashed = builtins.host_abi.RocCrashed;
const roc_shim_lib = if (builtin.is_test) &[_]u8{} else if (builtin.target.os.tag == .windows) @embedFile("roc_shim.lib") else @embedFile("libroc_shim.a");
test {
_ = @import("test_bundle_logic.zig");
}
// Workaround for Zig standard library compilation issue on macOS ARM64.
//
// The Problem:
// When importing std.c directly, Zig attempts to compile ALL C function declarations,
// including mremap which has this signature in std/c.zig:9562:
// pub extern "c" fn mremap(addr: ?*align(page_size) const anyopaque, old_len: usize,
// new_len: usize, flags: MREMAP, ...) *anyopaque;
//
// The variadic arguments (...) at the end trigger this compiler error on macOS ARM64:
// "parameter of type 'void' not allowed in function with calling convention 'aarch64_aapcs_darwin'"
//
// This is because:
// 1. mremap is a Linux-specific syscall that doesn't exist on macOS
// 2. The variadic declaration is incompatible with ARM64 macOS calling conventions
// 3. Even though we never call mremap, just importing std.c triggers its compilation
//
// Related issues:
// - https://github.com/ziglang/zig/issues/6321 - Discussion about mremap platform support
// - mremap is only available on Linux/FreeBSD, not macOS/Darwin
//
// Solution:
// Instead of importing all of std.c, we create a minimal wrapper that only exposes
// the specific types and functions we actually need. This avoids triggering the
// compilation of the broken mremap declaration.
//
// TODO: This workaround can be removed once the upstream Zig issue is fixed.
/// Minimal wrapper around std.c types and functions to avoid mremap compilation issues.
/// Contains only the C types and functions we actually need.
pub const c = struct {
pub const mode_t = std.c.mode_t;
pub const off_t = std.c.off_t;
pub const close = std.c.close;
pub const link = std.c.link;
pub const ftruncate = std.c.ftruncate;
pub const _errno = std.c._errno;
};
// Platform-specific shared memory implementation
const is_windows = builtin.target.os.tag == .windows;
// POSIX shared memory functions
const posix = if (!is_windows) struct {
extern "c" fn shm_open(name: [*:0]const u8, oflag: c_int, mode: std.c.mode_t) c_int;
extern "c" fn shm_unlink(name: [*:0]const u8) c_int;
extern "c" fn mmap(addr: ?*anyopaque, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: std.c.off_t) ?*anyopaque;
extern "c" fn munmap(addr: *anyopaque, len: usize) c_int;
extern "c" fn fcntl(fd: c_int, cmd: c_int, arg: c_int) c_int;
// fcntl constants
const F_GETFD = 1;
const F_SETFD = 2;
const FD_CLOEXEC = 1;
} else struct {};
// Windows shared memory functions
const windows = if (is_windows) struct {
const HANDLE = *anyopaque;
const DWORD = u32;
const BOOL = c_int;
const LPVOID = ?*anyopaque;
const LPCWSTR = [*:0]const u16;
const SIZE_T = usize;
const STARTUPINFOW = extern struct {
cb: DWORD,
lpReserved: ?LPCWSTR,
lpDesktop: ?LPCWSTR,
lpTitle: ?LPCWSTR,
dwX: DWORD,
dwY: DWORD,
dwXSize: DWORD,
dwYSize: DWORD,
dwXCountChars: DWORD,
dwYCountChars: DWORD,
dwFillAttribute: DWORD,
dwFlags: DWORD,
wShowWindow: u16,
cbReserved2: u16,
lpReserved2: ?*u8,
hStdInput: ?HANDLE,
hStdOutput: ?HANDLE,
hStdError: ?HANDLE,
};
const PROCESS_INFORMATION = extern struct {
hProcess: HANDLE,
hThread: HANDLE,
dwProcessId: DWORD,
dwThreadId: DWORD,
};
extern "kernel32" fn SetHandleInformation(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD) BOOL;
extern "kernel32" fn CreateProcessW(
lpApplicationName: ?LPCWSTR,
lpCommandLine: ?[*:0]u16,
lpProcessAttributes: ?*anyopaque,
lpThreadAttributes: ?*anyopaque,
bInheritHandles: BOOL,
dwCreationFlags: DWORD,
lpEnvironment: ?*anyopaque,
lpCurrentDirectory: ?LPCWSTR,
lpStartupInfo: *STARTUPINFOW,
lpProcessInformation: *PROCESS_INFORMATION,
) BOOL;
extern "kernel32" fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) DWORD;
const HANDLE_FLAG_INHERIT = 0x00000001;
const INFINITE = 0xFFFFFFFF;
} else struct {};
const benchTokenizer = bench.benchTokenizer;
const benchParse = bench.benchParse;
const Allocator = std.mem.Allocator;
const ColorPalette = reporting.ColorPalette;
const legalDetailsFileContent = @embedFile("legal_details");
/// Size for shared memory allocator (just virtual address space to reserve)
///
/// We pick a large number because we can't resize this without messing up the
/// child process. It's just virtual address space though, not physical memory.
/// On 32-bit targets, we use 512MB since 2TB won't fit in the address space.
const SHARED_MEMORY_SIZE: usize = if (@sizeOf(usize) >= 8)
512 * 1024 * 1024 // 512MB for 64-bit targets (reduced from 2TB for Windows compatibility)
else
256 * 1024 * 1024; // 256MB for 32-bit targets
/// Cross-platform hardlink creation
fn createHardlink(allocator: Allocator, source: []const u8, dest: []const u8) !void {
if (comptime builtin.target.os.tag == .windows) {
// On Windows, use CreateHardLinkW
const source_w = try std.unicode.utf8ToUtf16LeAllocZ(allocator, source);
defer allocator.free(source_w);
const dest_w = try std.unicode.utf8ToUtf16LeAllocZ(allocator, dest);
defer allocator.free(dest_w);
// Declare CreateHardLinkW since it's not in all versions of std
const kernel32 = struct {
extern "kernel32" fn CreateHardLinkW(
lpFileName: [*:0]const u16,
lpExistingFileName: [*:0]const u16,
lpSecurityAttributes: ?*anyopaque,
) callconv(std.os.windows.WINAPI) std.os.windows.BOOL;
};
if (kernel32.CreateHardLinkW(dest_w, source_w, null) == 0) {
const err = std.os.windows.kernel32.GetLastError();
switch (err) {
.ALREADY_EXISTS => return error.PathAlreadyExists,
else => return error.Unexpected,
}
}
} else {
// On POSIX systems, use the link system call
const source_c = try allocator.dupeZ(u8, source);
defer allocator.free(source_c);
const dest_c = try allocator.dupeZ(u8, dest);
defer allocator.free(dest_c);
const result = c.link(source_c, dest_c);
if (result != 0) {
const errno = c._errno().*;
switch (errno) {
17 => return error.PathAlreadyExists, // EEXIST
else => return error.Unexpected,
}
}
}
}
/// Generate a cryptographically secure random ASCII string for directory names
fn generateRandomSuffix(allocator: Allocator) ![]u8 {
// TODO: Consider switching to a library like https://github.com/abhinav/temp.zig
// for more robust temporary file/directory handling
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const suffix = try allocator.alloc(u8, 32);
// Fill with cryptographically secure random bytes
std.crypto.random.bytes(suffix);
// Convert to ASCII characters from our charset
for (suffix) |*byte| {
byte.* = charset[byte.* % charset.len];
}
return suffix;
}
/// Create the temporary directory structure for fd communication.
/// Returns the path to the executable in the temp directory (caller must free).
/// If a cache directory is provided, it will be used for temporary files; otherwise
/// falls back to the system temp directory.
pub fn createTempDirStructure(allocator: Allocator, exe_path: []const u8, shm_handle: SharedMemoryHandle, cache_dir: ?[]const u8) ![]const u8 {
// Use provided cache dir or fall back to system temp directory
const temp_dir = if (cache_dir) |dir|
try allocator.dupe(u8, dir)
else if (comptime is_windows)
std.process.getEnvVarOwned(allocator, "TEMP") catch
std.process.getEnvVarOwned(allocator, "TMP") catch try allocator.dupe(u8, "C:\\Windows\\Temp")
else
std.process.getEnvVarOwned(allocator, "TMPDIR") catch try allocator.dupe(u8, "/tmp");
defer allocator.free(temp_dir);
// Try up to 10 times to create a unique directory
var attempt: u8 = 0;
while (attempt < 10) : (attempt += 1) {
const random_suffix = try generateRandomSuffix(allocator);
errdefer allocator.free(random_suffix);
// Create the full path with .txt suffix first
const normalized_temp_dir = if (comptime is_windows)
std.mem.trimRight(u8, temp_dir, "/\\")
else
std.mem.trimRight(u8, temp_dir, "/");
const dir_name_with_txt = if (comptime is_windows)
try std.fmt.allocPrint(allocator, "{s}\\roc-tmp-{s}.txt", .{ normalized_temp_dir, random_suffix })
else
try std.fmt.allocPrint(allocator, "{s}/roc-tmp-{s}.txt", .{ normalized_temp_dir, random_suffix });
errdefer allocator.free(dir_name_with_txt);
// Get the directory path by slicing off the .txt suffix
const dir_path_len = dir_name_with_txt.len - 4; // Remove ".txt"
const temp_dir_path = dir_name_with_txt[0..dir_path_len];
// Try to create the directory
std.fs.cwd().makeDir(temp_dir_path) catch |err| switch (err) {
error.PathAlreadyExists => {
// Directory already exists, try again with a new random suffix
allocator.free(random_suffix);
allocator.free(dir_name_with_txt);
continue;
},
else => {
allocator.free(random_suffix);
allocator.free(dir_name_with_txt);
return err;
},
};
// Try to create the fd file
const fd_file = std.fs.cwd().createFile(dir_name_with_txt, .{ .exclusive = true }) catch |err| switch (err) {
error.PathAlreadyExists => {
// File already exists, remove the directory and try again
std.fs.cwd().deleteDir(temp_dir_path) catch {};
allocator.free(random_suffix);
allocator.free(dir_name_with_txt);
continue;
},
else => {
// Clean up directory on other errors
std.fs.cwd().deleteDir(temp_dir_path) catch {};
allocator.free(random_suffix);
allocator.free(dir_name_with_txt);
return err;
},
};
// Note: We'll close this explicitly later, before spawning the child
// Write shared memory info to file (POSIX only - Windows uses command line args)
const fd_str = try std.fmt.allocPrint(allocator, "{}\n{}", .{ shm_handle.fd, shm_handle.size });
defer allocator.free(fd_str);
try fd_file.writeAll(fd_str);
// IMPORTANT: Flush and close the file explicitly before spawning child process
// On Windows, having the file open can prevent child process access
try fd_file.sync(); // Ensure data is written to disk
fd_file.close();
// Create hardlink to executable in temp directory
const exe_basename = std.fs.path.basename(exe_path);
const temp_exe_path = try std.fs.path.join(allocator, &.{ temp_dir_path, exe_basename });
defer allocator.free(temp_exe_path);
// Try to create a hardlink first (more efficient than copying)
createHardlink(allocator, exe_path, temp_exe_path) catch {
// If hardlinking fails for any reason, fall back to copying
// Common reasons: cross-device link, permissions, file already exists
try std.fs.cwd().copyFile(exe_path, std.fs.cwd(), temp_exe_path, .{});
};
// Allocate and return just the executable path
const final_exe_path = try allocator.dupe(u8, temp_exe_path);
// Free all temporary allocations
allocator.free(dir_name_with_txt);
allocator.free(random_suffix);
return final_exe_path;
}
// Failed after 10 attempts
return error.FailedToCreateUniqueTempDir;
}
/// The CLI entrypoint for the Roc compiler.
pub fn main() !void {
var gpa_tracy: tracy.TracyAllocator(null) = undefined;
var gpa = std.heap.c_allocator;
if (tracy.enable_allocation) {
gpa_tracy = tracy.tracyAllocator(gpa);
gpa = gpa_tracy.allocator();
}
var arena_impl = std.heap.ArenaAllocator.init(gpa);
defer arena_impl.deinit();
const arena = arena_impl.allocator();
const args = try std.process.argsAlloc(arena);
const result = mainArgs(gpa, arena, args);
if (tracy.enable) {
try tracy.waitForShutdown();
}
return result;
}
fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
const trace = tracy.trace(@src());
defer trace.end();
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
const parsed_args = try cli_args.parse(gpa, args[1..]);
defer parsed_args.deinit(gpa);
try switch (parsed_args) {
.run => |run_args| rocRun(gpa, run_args),
.check => |check_args| rocCheck(gpa, check_args),
.build => |build_args| rocBuild(gpa, build_args),
.bundle => |bundle_args| rocBundle(gpa, bundle_args),
.unbundle => |unbundle_args| rocUnbundle(gpa, unbundle_args),
.format => |format_args| rocFormat(gpa, arena, format_args),
.test_cmd => |test_args| rocTest(gpa, test_args),
.repl => rocRepl(gpa),
.version => stdout.print("Roc compiler version {s}\n", .{build_options.compiler_version}),
.docs => |docs_args| rocDocs(gpa, docs_args),
.help => |help_message| stdout.writeAll(help_message),
.licenses => stdout.writeAll(legalDetailsFileContent),
.problem => |problem| {
try switch (problem) {
.missing_flag_value => |details| stderr.print("Error: no value was supplied for {s}\n", .{details.flag}),
.unexpected_argument => |details| stderr.print("Error: roc {s} received an unexpected argument: `{s}`\n", .{ details.cmd, details.arg }),
.invalid_flag_value => |details| stderr.print("Error: `{s}` is not a valid value for {s}. The valid options are {s}\n", .{ details.value, details.flag, details.valid_options }),
};
std.process.exit(1);
},
};
}
fn rocRun(gpa: Allocator, args: cli_args.RunArgs) void {
const trace = tracy.trace(@src());
defer trace.end();
// Initialize cache - used to store our shim, and linked interpreter executables in cache
const cache_config = CacheConfig{
.enabled = !args.no_cache,
.verbose = false,
};
var cache_manager = CacheManager.init(gpa, cache_config, Filesystem.default());
// Create cache directory for linked interpreter executables
const cache_dir = cache_manager.config.getCacheEntriesDir(gpa) catch |err| {
std.log.err("Failed to get cache directory: {}\n", .{err});
std.process.exit(1);
};
defer gpa.free(cache_dir);
const exe_cache_dir = std.fs.path.join(gpa, &.{ cache_dir, "executables" }) catch |err| {
std.log.err("Failed to create executable cache path: {}\n", .{err});
std.process.exit(1);
};
defer gpa.free(exe_cache_dir);
std.fs.cwd().makePath(exe_cache_dir) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => {
std.log.err("Failed to create cache directory: {}\n", .{err});
std.process.exit(1);
},
};
// Generate executable name based on the roc file path
// TODO use something more interesting like a hash from the platform.main or platform/host.a etc
const exe_name = std.fmt.allocPrint(gpa, "roc_run_{}", .{std.hash.crc.Crc32.hash(args.path)}) catch |err| {
std.log.err("Failed to generate executable name: {}\n", .{err});
std.process.exit(1);
};
defer gpa.free(exe_name);
const exe_path = std.fs.path.join(gpa, &.{ exe_cache_dir, exe_name }) catch |err| {
std.log.err("Failed to create executable path: {}\n", .{err});
std.process.exit(1);
};
defer gpa.free(exe_path);
// Check if the interpreter executable already exists (cached)
const exe_exists = if (args.no_cache) false else blk: {
std.fs.accessAbsolute(exe_path, .{}) catch {
break :blk false;
};
break :blk true;
};
if (!exe_exists) {
// Resolve platform from app header
const host_path = resolvePlatformHost(gpa, args.path) catch |err| {
std.log.err("Failed to resolve platform: {}\n", .{err});
std.process.exit(1);
};
defer gpa.free(host_path);
// Check for cached shim library, extract if not present
const shim_filename = if (builtin.target.os.tag == .windows) "roc_shim.lib" else "libroc_shim.a";
const shim_path = std.fs.path.join(gpa, &.{ exe_cache_dir, shim_filename }) catch |err| {
std.log.err("Failed to create shim library path: {}\n", .{err});
std.process.exit(1);
};
defer gpa.free(shim_path);
// Extract shim if not cached or if --no-cache is used
const shim_exists = if (args.no_cache) false else blk: {
std.fs.cwd().access(shim_path, .{}) catch {
break :blk false;
};
break :blk true;
};
if (!shim_exists) {
// Shim not found in cache or cache disabled, extract it
extractReadRocFilePathShimLibrary(gpa, shim_path) catch |err| {
std.log.err("Failed to extract read roc file path shim library: {}\n", .{err});
std.process.exit(1);
};
}
// Link the host.a with our shim to create the interpreter executable using our linker
// Try LLD first, fallback to clang if LLVM is not available
var extra_args = std.ArrayList([]const u8).init(gpa);
defer extra_args.deinit();
// Add system libraries for macOS
if (builtin.target.os.tag == .macos) {
extra_args.append("-lSystem") catch {
std.log.err("Failed to allocate memory for linker args\n", .{});
std.process.exit(1);
};
}
const link_config = linker.LinkConfig{
.output_path = exe_path,
.object_files = &.{ host_path, shim_path },
.extra_args = extra_args.items,
.can_exit_early = false,
.disable_output = false,
};
linker.link(gpa, link_config) catch |err| switch (err) {
linker.LinkError.LLVMNotAvailable => {
// Fallback to clang when LLVM is not available
const link_result = std.process.Child.run(.{
.allocator = gpa,
.argv = &.{ "clang", "-o", exe_path, host_path, shim_path },
}) catch |clang_err| {
std.log.err("Failed to link executable with both LLD and clang: LLD unavailable, clang error: {}\n", .{clang_err});
std.process.exit(1);
};
defer gpa.free(link_result.stdout);
defer gpa.free(link_result.stderr);
if (link_result.term.Exited != 0) {
std.log.err("Linker failed with exit code: {}\n", .{link_result.term.Exited});
if (link_result.stderr.len > 0) {
std.log.err("Linker stderr: {s}\n", .{link_result.stderr});
}
if (link_result.stdout.len > 0) {
std.log.err("Linker stdout: {s}\n", .{link_result.stdout});
}
std.process.exit(1);
}
},
linker.LinkError.LinkFailed => {
std.log.err("LLD linker failed to create executable\n", .{});
std.process.exit(1);
},
else => {
std.log.err("Failed to link executable: {}\n", .{err});
std.process.exit(1);
},
};
}
// Set up shared memory with ModuleEnv
const shm_handle = setupSharedMemoryWithModuleEnv(gpa, args.path) catch |err| {
std.log.err("Failed to set up shared memory with ModuleEnv: {}\n", .{err});
std.process.exit(1);
};
// Ensure we clean up shared memory resources on all exit paths
defer {
if (comptime is_windows) {
_ = ipc.platform.windows.UnmapViewOfFile(shm_handle.ptr);
_ = ipc.platform.windows.CloseHandle(@ptrCast(shm_handle.fd));
} else {
_ = posix.munmap(shm_handle.ptr, shm_handle.size);
_ = c.close(shm_handle.fd);
}
}
if (comptime is_windows) {
// Windows: Use handle inheritance approach
runWithWindowsHandleInheritance(gpa, exe_path, shm_handle) catch |err| {
std.log.err("Failed to run with Windows handle inheritance: {}\n", .{err});
std.process.exit(1);
};
} else {
// POSIX: Use existing file descriptor inheritance approach
runWithPosixFdInheritance(gpa, exe_path, shm_handle, &cache_manager) catch |err| {
std.log.err("Failed to run with POSIX fd inheritance: {}\n", .{err});
std.process.exit(1);
};
}
}
/// Run child process using Windows handle inheritance (idiomatic Windows approach)
fn runWithWindowsHandleInheritance(gpa: Allocator, exe_path: []const u8, shm_handle: SharedMemoryHandle) !void {
// Make the shared memory handle inheritable
if (windows.SetHandleInformation(@ptrCast(shm_handle.fd), windows.HANDLE_FLAG_INHERIT, windows.HANDLE_FLAG_INHERIT) == 0) {
std.log.err("Failed to set handle as inheritable\n", .{});
return error.HandleInheritanceFailed;
}
// Convert paths to Windows wide strings
const exe_path_w = try std.unicode.utf8ToUtf16LeAllocZ(gpa, exe_path);
defer gpa.free(exe_path_w);
const cwd = try std.fs.cwd().realpathAlloc(gpa, ".");
defer gpa.free(cwd);
const cwd_w = try std.unicode.utf8ToUtf16LeAllocZ(gpa, cwd);
defer gpa.free(cwd_w);
// Create command line with handle and size as arguments
const handle_uint = @intFromPtr(shm_handle.fd);
const cmd_line = try std.fmt.allocPrintZ(gpa, "\"{s}\" {} {}", .{ exe_path, handle_uint, shm_handle.size });
defer gpa.free(cmd_line);
const cmd_line_w = try std.unicode.utf8ToUtf16LeAllocZ(gpa, cmd_line);
defer gpa.free(cmd_line_w);
// Set up process creation structures
var startup_info = std.mem.zeroes(windows.STARTUPINFOW);
startup_info.cb = @sizeOf(windows.STARTUPINFOW);
var process_info = std.mem.zeroes(windows.PROCESS_INFORMATION);
// Create the child process with handle inheritance
// Create the child process with handle inheritance enabled
const success = windows.CreateProcessW(
exe_path_w.ptr, // Application name
cmd_line_w.ptr, // Command line (mutable)
null, // Process attributes
null, // Thread attributes
1, // bInheritHandles = TRUE
0, // Creation flags
null, // Environment
cwd_w.ptr, // Current directory
&startup_info, // Startup info
&process_info, // Process info
);
if (success == 0) {
std.log.err("CreateProcessW failed\n", .{});
return error.ProcessCreationFailed;
}
// Child process spawned successfully
// Wait for the child process to complete
const wait_result = windows.WaitForSingleObject(process_info.hProcess, windows.INFINITE);
if (wait_result != 0) { // WAIT_OBJECT_0 = 0
std.log.err("WaitForSingleObject failed or timed out\n", .{});
}
// Clean up process handles
_ = ipc.platform.windows.CloseHandle(process_info.hProcess);
_ = ipc.platform.windows.CloseHandle(process_info.hThread);
}
/// Run child process using POSIX file descriptor inheritance (existing approach for Unix)
fn runWithPosixFdInheritance(gpa: Allocator, exe_path: []const u8, shm_handle: SharedMemoryHandle, cache_manager: *CacheManager) !void {
// Get cache directory for temporary files
const temp_cache_dir = cache_manager.config.getTempDir(gpa) catch |err| {
std.log.err("Failed to get temp cache directory: {}\n", .{err});
return err;
};
defer gpa.free(temp_cache_dir);
// Ensure temp cache directory exists
std.fs.cwd().makePath(temp_cache_dir) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => {
std.log.err("Failed to create temp cache directory: {}\n", .{err});
return err;
},
};
// Create temporary directory structure for fd communication
const temp_exe_path = createTempDirStructure(gpa, exe_path, shm_handle, temp_cache_dir) catch |err| {
std.log.err("Failed to create temp dir structure: {}\n", .{err});
return err;
};
defer gpa.free(temp_exe_path);
// Configure fd inheritance
var flags = posix.fcntl(shm_handle.fd, posix.F_GETFD, 0);
if (flags < 0) {
std.log.err("Failed to get fd flags: {}\n", .{c._errno().*});
return error.FdConfigFailed;
}
flags &= ~@as(c_int, posix.FD_CLOEXEC);
if (posix.fcntl(shm_handle.fd, posix.F_SETFD, flags) < 0) {
std.log.err("Failed to set fd flags: {}\n", .{c._errno().*});
return error.FdConfigFailed;
}
// Run the interpreter as a child process from the temp directory
var child = std.process.Child.init(&.{temp_exe_path}, gpa);
child.cwd = std.fs.cwd().realpathAlloc(gpa, ".") catch |err| {
std.log.err("Failed to get current directory: {}\n", .{err});
return err;
};
defer gpa.free(child.cwd.?);
// Forward stdout and stderr
child.stdout_behavior = .Inherit;
child.stderr_behavior = .Inherit;
// Spawn the child process
child.spawn() catch |err| {
std.log.err("Failed to spawn {s}: {}\n", .{ exe_path, err });
return err;
};
// Child process spawned successfully
// Wait for child to complete
_ = child.wait() catch |err| {
std.log.err("Failed waiting for child process: {}\n", .{err});
return err;
};
}
/// Handle for cross-platform shared memory operations.
/// Contains the file descriptor/handle, memory pointer, and size.
pub const SharedMemoryHandle = struct {
fd: if (is_windows) *anyopaque else c_int,
ptr: *anyopaque,
size: usize,
};
/// Write data to shared memory for inter-process communication.
/// Creates a shared memory region and writes the data with a length prefix.
/// Returns a handle that can be used to access the shared memory.
pub fn writeToSharedMemory(data: []const u8) !SharedMemoryHandle {
// Calculate total size needed: length + data
const total_size = @sizeOf(usize) + data.len;
if (comptime is_windows) {
return writeToWindowsSharedMemory(data, total_size);
} else {
return writeToPosixSharedMemory(data, total_size);
}
}
fn writeToWindowsSharedMemory(data: []const u8, total_size: usize) !SharedMemoryHandle {
// Create anonymous shared memory object (no name for handle inheritance)
const shm_handle = ipc.platform.windows.CreateFileMappingW(
ipc.platform.windows.INVALID_HANDLE_VALUE,
null,
ipc.platform.windows.PAGE_READWRITE,
0,
@intCast(total_size),
null, // Anonymous - no name needed for handle inheritance
) orelse {
std.log.err("Failed to create shared memory mapping\n", .{});
return error.SharedMemoryCreateFailed;
};
// Map the shared memory at a fixed address to avoid ASLR issues
const mapped_ptr = ipc.platform.windows.MapViewOfFileEx(
shm_handle,
ipc.platform.windows.FILE_MAP_ALL_ACCESS,
0,
0,
0,
ipc.platform.SHARED_MEMORY_BASE_ADDR,
) orelse {
_ = ipc.platform.windows.CloseHandle(shm_handle);
return error.SharedMemoryMapFailed;
};
// Write length and data
const length_ptr: *usize = @ptrCast(@alignCast(mapped_ptr));
length_ptr.* = data.len;
const data_ptr = @as([*]u8, @ptrCast(mapped_ptr)) + @sizeOf(usize);
@memcpy(data_ptr[0..data.len], data);
return SharedMemoryHandle{
.fd = shm_handle,
.ptr = mapped_ptr,
.size = total_size,
};
}
/// Set up shared memory with a compiled ModuleEnv from a Roc file.
/// This parses, canonicalizes, and type-checks the Roc file, with the resulting ModuleEnv
/// ending up in shared memory because all allocations were done into shared memory.
pub fn setupSharedMemoryWithModuleEnv(gpa: std.mem.Allocator, roc_file_path: []const u8) !SharedMemoryHandle {
// Create shared memory with SharedMemoryAllocator
const page_size = try SharedMemoryAllocator.getSystemPageSize();
var shm = try SharedMemoryAllocator.create(SHARED_MEMORY_SIZE, page_size);
// Don't defer deinit here - we need to keep the shared memory alive
const shm_allocator = shm.allocator();
// Allocate space for the offset value at the beginning
const offset_ptr = try shm_allocator.alloc(u64, 1);
// Also store the canonicalized expression index for the child to evaluate
const expr_idx_ptr = try shm_allocator.alloc(u32, 1);
// Store the base address of the shared memory mapping (for ASLR-safe relocation)
// The child will calculate the offset from its own base address
const shm_base_addr = @intFromPtr(shm.base_ptr);
offset_ptr[0] = shm_base_addr;
// Allocate and store a pointer to the ModuleEnv
const env_ptr = try shm_allocator.create(ModuleEnv);
// Read the actual Roc file
const roc_file = std.fs.cwd().openFile(roc_file_path, .{}) catch |err| {
std.log.err("Failed to open Roc file '{s}': {}\n", .{ roc_file_path, err });
return error.FileNotFound;
};
defer roc_file.close();
// Read the entire file into shared memory
const file_size = try roc_file.getEndPos();
const source = try shm_allocator.alloc(u8, @intCast(file_size));
_ = try roc_file.read(source);
// Extract module name from the file path
const basename = std.fs.path.basename(roc_file_path);
const module_name = try shm_allocator.dupe(u8, basename);
var env = try ModuleEnv.init(shm_allocator, source);
env.common.source = source;
env.module_name = module_name;
try env.common.calcLineStarts(shm_allocator);
// Parse the source code as a full module
var parse_ast = try parse.parse(&env.common, gpa);
// Empty scratch space (required before canonicalization)
parse_ast.store.emptyScratch();
// Initialize CIR fields in ModuleEnv
try env.initCIRFields(shm_allocator, module_name);
// Create canonicalizer
var canonicalizer = try Can.init(&env, &parse_ast, null);
// Canonicalize the entire module
try canonicalizer.canonicalizeFile();
// Find the "main" definition in the module
// Look through all definitions to find one named "main"
var main_expr_idx: ?u32 = null;
const defs = env.store.sliceDefs(env.all_defs);
for (defs) |def_idx| {
const def = env.store.getDef(def_idx);
const pattern = env.store.getPattern(def.pattern);
if (pattern == .assign) {
const ident_idx = pattern.assign.ident;
const ident_text = env.getIdent(ident_idx);
if (std.mem.eql(u8, ident_text, "main")) {
main_expr_idx = @intFromEnum(def.expr);
break;
}
}
}
// Store the main expression index for the child
expr_idx_ptr[0] = main_expr_idx orelse {
std.log.err("No 'main' definition found in module\n", .{});
return error.NoMainFunction;
};
// Type check the module
var checker = try Check.init(shm_allocator, &env.types, &env, &.{}, &env.store.regions);
try checker.checkDefs();
// Copy the ModuleEnv to the allocated space
env_ptr.* = env;
// Clean up the canonicalizer and parsing structures
canonicalizer.deinit();
// Clean up parse_ast since it was allocated with gpa, not shared memory
parse_ast.deinit(gpa);
// Clean up checker since it was allocated with shared memory, but we need to clean up its gpa allocations
checker.deinit();
// Update the header with used size
shm.updateHeader();
// Return the shared memory handle from SharedMemoryAllocator
// This ensures we use the SAME shared memory region for both processes
return SharedMemoryHandle{
.fd = shm.handle,
.ptr = shm.base_ptr,
.size = shm.getUsedSize(),
};
}
fn writeToPosixSharedMemory(data: []const u8, total_size: usize) !SharedMemoryHandle {
const shm_name = "/ROC_FILE_TO_INTERPRET";
// Unlink any existing shared memory object first
_ = posix.shm_unlink(shm_name);
// Create shared memory object
const shm_fd = posix.shm_open(shm_name, 0x0002 | 0x0200, 0o666); // O_RDWR | O_CREAT
if (shm_fd < 0) {
return error.SharedMemoryCreateFailed;
}
// Set the size of the shared memory object
if (c.ftruncate(shm_fd, @intCast(total_size)) != 0) {
_ = c.close(shm_fd);
return error.SharedMemoryTruncateFailed;
}
// Map the shared memory
const mapped_ptr = posix.mmap(
null,
total_size,
0x01 | 0x02, // PROT_READ | PROT_WRITE
0x0001, // MAP_SHARED
shm_fd,
0,
) orelse {
_ = c.close(shm_fd);
return error.SharedMemoryMapFailed;
};
const mapped_memory = @as([*]u8, @ptrCast(mapped_ptr))[0..total_size];
// Write length at the beginning
const length_ptr: *align(1) usize = @ptrCast(mapped_memory.ptr);
length_ptr.* = data.len;
// Write data after the length
const data_ptr = mapped_memory.ptr + @sizeOf(usize);
@memcpy(data_ptr[0..data.len], data);
return SharedMemoryHandle{
.fd = shm_fd,
.ptr = mapped_ptr,
.size = total_size,
};
}
/// Resolve platform specification from a Roc file to find the host library
pub fn resolvePlatformHost(gpa: std.mem.Allocator, roc_file_path: []const u8) (std.mem.Allocator.Error || error{ NoPlatformFound, PlatformNotSupported })![]u8 {
// Read the Roc file to parse the app header
const roc_file = std.fs.cwd().openFile(roc_file_path, .{}) catch |err| switch (err) {
error.FileNotFound => return error.NoPlatformFound,
else => return error.NoPlatformFound, // Treat all file errors as no platform found
};
defer roc_file.close();
const file_size = roc_file.getEndPos() catch return error.NoPlatformFound;
const source = gpa.alloc(u8, @intCast(file_size)) catch return error.OutOfMemory;
defer gpa.free(source);
_ = roc_file.read(source) catch return error.NoPlatformFound;
// Parse the source to find the app header
// Look for "app" followed by platform specification
var lines = std.mem.splitScalar(u8, source, '\n');
while (lines.next()) |line| {
const trimmed = std.mem.trim(u8, line, " \t\r");
// Check if this is an app header line
if (std.mem.startsWith(u8, trimmed, "app")) {
// Look for platform specification after "platform"
if (std.mem.indexOf(u8, trimmed, "platform")) |platform_start| {
const after_platform = trimmed[platform_start + "platform".len ..];
// Find the platform name/URL in quotes
if (std.mem.indexOf(u8, after_platform, "\"")) |quote_start| {
const after_quote = after_platform[quote_start + 1 ..];
if (std.mem.indexOf(u8, after_quote, "\"")) |quote_end| {
const platform_spec = after_quote[0..quote_end];
// If it's a relative path, resolve it relative to the app directory
if (std.mem.startsWith(u8, platform_spec, "./") or std.mem.startsWith(u8, platform_spec, "../")) {
const app_dir = std.fs.path.dirname(roc_file_path) orelse ".";
const platform_path = try std.fs.path.join(gpa, &.{ app_dir, platform_spec });
defer gpa.free(platform_path);
// Look for host library near the platform file
const platform_dir = std.fs.path.dirname(platform_path) orelse ".";
const host_filename = if (comptime builtin.target.os.tag == .windows) "host.lib" else "libhost.a";
const host_path = try std.fs.path.join(gpa, &.{ platform_dir, host_filename });
defer gpa.free(host_path);
std.fs.cwd().access(host_path, .{}) catch {
return error.PlatformNotSupported;
};
return try gpa.dupe(u8, host_path);
}
// Try to resolve platform to a local host library
return resolvePlatformSpecToHostLib(gpa, platform_spec);
}
}
}
}
}
return error.NoPlatformFound;
}
/// Resolve a platform specification to a local host library path
fn resolvePlatformSpecToHostLib(gpa: std.mem.Allocator, platform_spec: []const u8) (std.mem.Allocator.Error || error{PlatformNotSupported})![]u8 {
// Check for common platform names and map them to host libraries
if (std.mem.eql(u8, platform_spec, "cli")) {
// Try to find CLI platform host library
const cli_paths = if (comptime builtin.target.os.tag == .windows)
[_][]const u8{