Skip to content

Commit dccb443

Browse files
authored
CH32V: Reorganize startup logic (#881)
This PR changes it so that the compiler can no longer reorder statements in _start, which led to bugs.
1 parent 3e90197 commit dccb443

1 file changed

Lines changed: 12 additions & 15 deletions

File tree

port/wch/ch32v/src/cpus/main.zig

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -220,21 +220,25 @@ pub const startup_logic = struct {
220220
extern fn microzig_main() noreturn;
221221

222222
pub fn _start() callconv(.naked) void {
223-
// Set global pointer.
224223
asm volatile (
224+
\\
225+
// Set global pointer.
225226
\\.option push
226227
\\.option norelax
227228
\\la gp, __global_pointer$
228229
\\.option pop
229-
);
230+
\\
231+
// Set stack pointer.
232+
\\mv sp, %[eos]
230233

231-
// Set stack pointer.
232-
const eos = comptime microzig.utilities.get_end_of_stack();
233-
asm volatile ("mv sp, %[eos]"
234+
// Initialize the system.
235+
\\j _system_init
234236
:
235-
: [eos] "r" (@as(u32, @intFromPtr(eos))),
237+
: [eos] "r" (comptime microzig.utilities.get_end_of_stack()),
236238
);
239+
}
237240

241+
export fn _system_init() callconv(.c) noreturn {
238242
// NOTE: this can only be called once. Otherwise, we get a linker error for duplicate symbols
239243
startup_logic.initialize_system_memories();
240244

@@ -278,11 +282,7 @@ pub const startup_logic = struct {
278282
.mpp = 0x3,
279283
});
280284

281-
// Initialize the system.
282-
@export(&startup_logic._system_init, .{ .name = "_system_init" });
283-
asm volatile (
284-
\\jal _system_init
285-
);
285+
cpu_impl.system_init(microzig.chip);
286286

287287
// Load the address of the `microzig_main` function into the `mepc` register
288288
// and transfer control to it using the `mret` instruction.
@@ -295,6 +295,7 @@ pub const startup_logic = struct {
295295
// machine mode and we are switching to machine mode, but normally this could switch us to
296296
// user mode.
297297
asm volatile ("mret");
298+
unreachable;
298299
}
299300

300301
inline fn initialize_system_memories() void {
@@ -327,10 +328,6 @@ pub const startup_logic = struct {
327328
);
328329
}
329330

330-
fn _system_init() callconv(.c) void {
331-
cpu_impl.system_init(microzig.chip);
332-
}
333-
334331
export fn _reset_vector() linksection("microzig_flash_start") callconv(.naked) void {
335332
asm volatile ("j _start");
336333
}

0 commit comments

Comments
 (0)