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
|
// SPDX-FileCopyrightText: 2024 Himbeer <himbeer@disroot.org>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
const std = @import("std");
const Console = @import("Console.zig");
const instructions = @import("instructions.zig");
const mem = @import("mem.zig");
const paging = @import("paging.zig");
const process = @import("process.zig");
const syscall = @import("syscall.zig");
const sysexchange = @import("sysexchange.zig");
const userinit = @import("userinit.zig");
const vfs = @import("vfs.zig");
const Result = sysexchange.Result;
const io = std.io;
const tar = std.tar;
const File = tar.Iterator(io.FixedBufferStream([]const u8).Reader).File;
const FileContext = struct {
buffer: []const u8,
fbs: io.FixedBufferStream([]const u8),
};
const iofs = struct {
const debug = struct {
fn write(ptr: [*]const u8, len: usize) callconv(.C) Result(usize) {
// Raise page fault if applicable.
if (len > 0) {
std.mem.doNotOptimizeAway(ptr[0]);
}
const procmem: *paging.Table = @ptrFromInt(instructions.satp.read().ppn << 12);
const paddr = procmem.translate(@intFromPtr(ptr)).?;
const pptr: [*]const u8 = @ptrFromInt(paddr);
const bytes = pptr[0..len];
const console = Console.autoChoose() orelse {
return Result(usize).fromAnyTypeOrError(Error.NoConsole);
};
const w = console.writer();
w.print("{s}", .{bytes}) catch |err| {
return Result(usize).fromAnyTypeOrError(err);
};
return Result(usize).fromAnyTypeOrError(bytes.len);
}
};
};
const processfs = struct {
const self = struct {
fn terminate(pid: u16, thread_id: usize, _: usize) callconv(.C) Result(usize) {
const proc = process.findThread(pid, thread_id).?;
proc.terminate();
process.schedule() catch |err| {
std.debug.panic("Unable to schedule because all processes are terminated: {any}", .{err});
};
}
fn id(pid: u16, _: usize, _: usize) callconv(.C) Result(usize) {
return Result(usize).fromAnyTypeOrError(pid);
}
fn threadId(_: u16, thread_id: usize, _: usize) callconv(.C) Result(usize) {
return Result(usize).fromAnyTypeOrError(thread_id);
}
};
const CreationContext = struct {
rd: vfs.ResourceDescriptor,
buffer: std.ArrayListAligned(u8, paging.page_size),
proc: *process.Info,
};
fn create(pid: u16, thread_id: usize, data: usize) callconv(.C) Result(usize) {
const result = doCreate(pid, thread_id, data);
return Result(usize).fromAnyTypeOrError(result);
}
fn doCreate(pid: u16, thread_id: usize, data: usize) !usize {
paging.setUserMemoryAccess(true);
defer paging.setUserMemoryAccess(false);
const path_c: [*:0]const u8 = @ptrFromInt(data); // fixme: Kernel panic if null pointer
const allocator = mem.page_allocator;
const rd = try vfs.openNonHookZ(path_c);
defer rd.deinit();
if (rd.inode.resource.tag == .dir or rd.inode.resource.tag == .dir_hook) {
return vfs.Error.IsAContainer;
}
const proc = process.findThread(pid, thread_id).?;
var buffer = std.ArrayListAligned(u8, paging.page_size).init(allocator);
defer buffer.clearAndFree();
try buffer.ensureUnusedCapacity(4096);
const ctx = try allocator.create(CreationContext);
defer allocator.destroy(ctx);
ctx.* = .{
.rd = rd,
.buffer = buffer,
.proc = proc,
};
paging.setUserMemoryAccess(false);
defer proc.allowResume();
while (try rd.readHooked(proc, ctx.buffer.items, .{
.hookFn = loadExe,
.context = ctx,
}) > 0) {}
const new_proc = try process.create(allocator, ctx.buffer.items);
return new_proc.id;
}
fn loadExe(context: *anyopaque, driver: *const process.Info) void {
const ctx: *CreationContext = @alignCast(@ptrCast(context));
doLoadExe(ctx, driver) catch |err| {
sysexchange.frameReturn(usize, &ctx.proc.trap_frame, err);
};
}
fn doLoadExe(ctx: *CreationContext, driver: *const process.Info) !void {
const allocator = mem.page_allocator;
defer ctx.proc.allowResume();
const result: Result(usize) = .{
.value = driver.trap_frame.general_purpose_registers[12],
.status = @enumFromInt(driver.trap_frame.general_purpose_registers[13]),
};
if (result.status != .success) {
defer allocator.destroy(ctx);
defer ctx.buffer.clearAndFree();
defer ctx.rd.deinit();
sysexchange.frameReturnResult(usize, &ctx.proc.trap_frame, result);
return;
}
const n = result.value;
if (n == 0) {
defer allocator.destroy(ctx);
defer ctx.buffer.clearAndFree();
defer ctx.rd.deinit();
const new_proc = try process.create(allocator, ctx.buffer.items);
sysexchange.frameReturn(null, &ctx.proc.trap_frame, new_proc.id);
return;
}
try ctx.buffer.ensureUnusedCapacity(4096);
while (try ctx.rd.readHooked(ctx.proc, ctx.buffer.items[ctx.buffer.items.len..], .{
.hookFn = loadExe,
.context = ctx,
}) > 0) {}
const new_proc = try process.create(allocator, ctx.buffer.items);
sysexchange.frameReturn(null, &ctx.proc.trap_frame, new_proc.id);
}
};
pub const Error = error{
NoTarFileInitializer,
NoConsole,
};
pub fn provideBuiltin(allocator: std.mem.Allocator) !void {
try addDir("/io");
try addDir("/userinit");
try addDir("/process");
try addDir("/process/self");
try provideConsole();
try provideUserinit(allocator);
try provideProcess();
}
fn provideConsole() !void {
try vfs.provideResource("/io/debug", .{
.tag = .stream,
.data = .{
.stream = .{
.readFn = null,
.writeFn = iofs.debug.write,
},
},
}, 0, .{
.reclaimable = false,
});
}
fn provideUserinit(allocator: std.mem.Allocator) !void {
var userinit_stream = io.fixedBufferStream(userinit.tarball);
const reader = userinit_stream.reader();
var file_name_buffer: [4086]u8 = undefined;
var link_name_buffer: [4086]u8 = undefined;
var it = tar.iterator(reader, .{
.file_name_buffer = file_name_buffer[0..],
.link_name_buffer = link_name_buffer[0..],
});
while (try it.next()) |file| {
const resolved = try std.fs.path.resolvePosix(allocator, &[_][]const u8{file.name});
const path = try std.fmt.allocPrint(allocator, "/userinit/{s}", .{resolved});
switch (file.kind) {
.file => try addFile(path, file),
.directory => try addDir(path),
.sym_link => {},
}
}
}
fn provideProcess() !void {
try vfs.provideResource("/process/create", .{
.tag = .hook,
.data = .{
.hook = .{
.callback = processfs.create,
},
},
}, 0, .{
.reclaimable = false,
});
try provideProcessSelf();
}
fn provideProcessSelf() !void {
try vfs.provideResource("/process/self/terminate", .{
.tag = .hook,
.data = .{
.hook = .{
.callback = processfs.self.terminate,
},
},
}, 0, .{
.reclaimable = false,
});
try vfs.provideResource("/process/self/id", .{
.tag = .hook,
.data = .{
.hook = .{
.callback = processfs.self.id,
},
},
}, 0, .{
.reclaimable = false,
});
try vfs.provideResource("/process/self/thread_id", .{
.tag = .hook,
.data = .{
.hook = .{
.callback = processfs.self.threadId,
},
},
}, 0, .{
.reclaimable = false,
});
}
fn addFile(path: []const u8, file: File) !void {
const allocator = vfs.treeRoot().allocator;
const buffer = try allocator.alloc(u8, file.size);
try file.reader().readNoEof(buffer);
const initializer = try allocator.create(FileContext);
initializer.* = .{
.buffer = buffer,
.fbs = io.fixedBufferStream(@as([]const u8, buffer)),
};
try vfs.provideResource(path, .{
.tag = .file,
.data = .{
.file = .{
.readFn = read,
.writeFn = null,
.closeFn = close,
.initializer = initializer,
},
},
}, 0, .{
.reclaimable = false,
});
}
fn addDir(path: []const u8) !void {
const allocator = vfs.treeRoot().allocator;
const tree = try allocator.create(vfs.Tree);
tree.* = vfs.Tree.init(allocator);
try vfs.provideResource(path, .{
.tag = .dir,
.data = .{ .dir = tree },
}, 0, .{
.reclaimable = false,
});
}
fn open(context: *vfs.FileContext) !void {
const allocator = vfs.treeRoot().allocator;
const inner = context.inner orelse return Error.NoTarFileInitializer;
const old_context: *FileContext = @alignCast(@ptrCast(inner));
const new_context = try allocator.create(FileContext);
new_context.* = old_context.*;
context.inner = new_context;
}
fn read(context: *vfs.FileContext, ptr: [*]u8, len: usize) callconv(.C) Result(usize) {
if (context.inner == null) {
open(context) catch |err| {
return Result(usize).fromAnyTypeOrError(err);
};
}
const inner: *FileContext = @alignCast(@ptrCast(context.inner.?));
const buffer = ptr[0..len];
return Result(usize).fromAnyTypeOrError(inner.fbs.read(buffer));
}
fn close(context: *vfs.FileContext) callconv(.C) void {
if (context.inner) |inner_opaque| {
const allocator = vfs.treeRoot().allocator;
const inner: *FileContext = @alignCast(@ptrCast(inner_opaque));
allocator.destroy(inner);
}
}
|