#! @file threads.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the threads of a program the machine runs, each a thread of the #! system the machine starts with `std::thread`. They take turns running #! bytecode, in the order they asked, so the machine and its heap are only ever #! used by one: a thread lets the next run as it waits in the system, and every #! few thousand steps where another waits. So threads run at the same time but #! not in parallel, while an executable's run in parallel; a program right in #! one is right in the other. #! #! What a thread has of its own, its stack, calls, texts being formatted, and #! trace, is a strand, which the machine holds while the thread has its turn, #! and the strand keeps while it has none. #! #! A thread that exits, or faults, stops the program: the others stop at their #! next turn, and a wait in the system ends within a tenth of a second while #! threads run, as the machine gives a futex's wait without a time one, so each #! sees it. A fault is reported with the trace of the thread that faulted. import system; import std::thread; import std::time; import sakura::compiler; module sakura::machine; #! The steps a thread takes before it lets another waiting run. const turn_steps: u64 = 4096; #! How long a wait in the system lasts at most while threads run, so a thread #! sees the program stop. const longest_wait: i64 = 100000000; #! What a thread has of its own, which the machine holds while it has its turn. struct strand { var stack: *mut u8; var stack_end: u64; var top: u64; var calls: call_stack; var texts: vector>; var depth: u64; var trace: vector; var countdown: u64; var last_error: u32; #! The error the thread's last C call left, kept across the machine's own work. var thread: u64; #! The number the system knows the thread by, which C calling back on it finds its strand by. var active: bool; #! Whether the machine holds it. var function: u32; #! The function the thread runs, what its closure uses, and the context it is given. var environment: u64; var context: u64; var racer: u32; #! Its number, as the race checker knows it. var clock: vector; #! What it knows of each thread's clock, as the race checker keeps it. } #! What a thread of the system is given to run a thread of the program: the #! machine, and the thread's strand. struct strand_start { var machine: *mut interpreter; var mine: *mut strand; } #! What the threads of a program share, which the machine holds once one starts. struct threading { var next: atomic; #! Turns asked for. var serving: atomic; #! The turn being taken. var strands: vector<*mut strand>; #! Every thread's, the first's among them. var handles: vector>; #! The threads of the system running them. var running: u64; #! Threads started and not yet ended. var stopped: bool; #! Whether the program stopped, exiting or faulting. var stop: halt; #! Why. var trace: vector; #! Where the thread that faulted was. } #! Starts a thread running a function value, given a context, a thread of the #! system taking turns with the others. The first thread started makes what #! they share, the thread running holding the turn. #! @param this The machine. #! @param function The function's index, one more than it. #! @param environment What a closure uses. #! @param context The word the function is given. #! @returns The thread's number, or a negative error number. pub def interpreter::start_thread(&mut this, function: u64, environment: u64, context: u64): i64 { if this.threads == null { val shared := raw_allocate_zeroed(size_of::()) as *mut threading; shared[0].strands = vector::<*mut strand>::new(); shared[0].handles = vector::>::new(); shared[0].trace = vector::::new(); shared[0].next.store(1); val mine := raw_allocate_zeroed(size_of::()) as *mut strand; mine[0].active = true; when os == windows { mine[0].thread = system::thread_id(); } shared[0].strands.append(mine); this.threads = shared; this.strand = mine; this.countdown = turn_steps; } val shared := this.threads; val made := raw_allocate_zeroed(size_of::()) as *mut strand; # Its stack is cleared where the one the program began with is. val size := this.stack_end - this.stack as u64; made[0].stack = this.options.checks ? raw_allocate_zeroed(size) : raw_allocate(size); made[0].stack_end = made[0].stack as u64 + size; made[0].top = made[0].stack as u64; made[0].calls = call_stack::new(); made[0].texts = vector::>::new(); made[0].trace = vector::::new(); made[0].countdown = turn_steps; made[0].function = (function - 1) as u32; made[0].environment = environment; made[0].context = context; this.race_start(made); shared[0].strands.append(made); shared[0].running++; val given := strand_start { machine = this as *mut interpreter, mine = made }; var started := thread::spawn_with(def(at: strand_start) { through(at.machine).thread_main(at.mine); }, given) else (e) { shared[0].strands.truncate(); shared[0].running--; raw_release(made[0].stack); made[0].clock.close(); raw_release(made as *mut u8); return -11; }; val number := started.number() as i64; shared[0].handles.append(move(started)); return number; } #! What a thread of the system runs for a thread of the program: its function, #! in its turns. Where it stops the program, every thread sees it. #! @param this The machine. #! @param mine The thread's strand. def interpreter::thread_main(&mut this, mine: *mut strand): void { val shared := this.threads; when os == windows { mine[0].thread = system::thread_id(); } this.take_turn(mine); if !shared[0].stopped { val ran := this.invoke_value(mine[0].function, mine[0].environment, mine[0].context); if ran != halt::none && ran != halt::elsewhere { this.stop_with(ran); } } # The thread is done: its strand goes, and the turn passes on. this.save(mine); for i in 0..shared[0].strands.length { if shared[0].strands[i] == mine { shared[0].strands.remove_at(i); break; } } shared[0].running--; this.give_turn(); raw_release(mine[0].stack); mine[0].calls.close(); for i in 0..mine[0].texts.length { mine[0].texts[i].close(); } mine[0].texts.close(); mine[0].trace.close(); mine[0].clock.close(); raw_release(mine as *mut u8); } #! Calls a function value from the base of the stack, as a thread begins, and #! runs it until it returns. #! @param this The machine. #! @param index The function. #! @param environment What a closure uses. #! @param context The word it is given. #! @returns Why it stopped, or `none`. def interpreter::invoke_value(&mut this, index: u32, environment: u64, context: u64): halt { val held: routine = this.routines[index]; val fp := this.stack as *mut u64; if this.stack as u64 + held.frame > this.stack_end { return halt::stack_overflow; } memset(this.stack, 0, held.frame); # The context is the first parameter, where the function takes one. if held.frame >= word_size { fp[0] = context; } if held.closure { fp[held.env / word_size] = environment; } this.calls.clear(); this.depth = 0; this.calls.append(call_record { function = index, fp = fp, back = 0, site = 0, results = none }); this.top = this.stack as u64 + held.frame; return this.execute(0); } #! Says the program stopped, for why, where nothing stopped it before, keeping #! the trace of a fault. #! @param this The machine. #! @param why Why. def interpreter::stop_with(&mut this, why: halt): void { val shared := this.threads; return if shared[0].stopped; shared[0].stopped = true; shared[0].stop = why; if why != halt::exited { shared[0].trace = move(&mut this.trace); } } #! Where a thread's run of steps ends: it lets another waiting run. #! @param this The machine. #! @returns `elsewhere` where the program stopped meanwhile, or `none`. def interpreter::next_turn(&mut this): halt { this.countdown = turn_steps; val shared := this.threads; return halt::elsewhere if shared[0].stopped; return halt::none if shared[0].next.load() - shared[0].serving.load() <= 1; val mine := this.strand; this.pause(); return this.resume(mine); } #! Ends a thread's turn, as it waits in the system or lets another run, keeping #! what it has of its own in its strand. #! @param this The machine. pub def interpreter::pause(&mut this): void { return if this.threads == null; this.save(this.strand); this.give_turn(); } #! Takes a thread's next turn. #! @param this The machine. #! @param mine The thread's strand. #! @returns `elsewhere` where the program stopped meanwhile, or `none`. pub def interpreter::resume(&mut this, mine: *mut strand): halt { return halt::none if this.threads == null; this.take_turn(mine); return this.threads[0].stopped ? halt::elsewhere : halt::none; } # Waits for the turn, after every thread that asked before, then holds the # thread's strand. def interpreter::take_turn(&mut this, mine: *mut strand): void { val shared := this.threads; val ticket := shared[0].next.fetch_add(1); while true { val now := shared[0].serving.load(); if now == ticket { break; } _ = system::futex_wait(((&mut shared[0].serving) as *mut atomic) as *mut u32, now, -1); } this.restore(mine); } # Lets the thread that asked next have its turn. def interpreter::give_turn(&mut this): void { val shared := this.threads; _ = shared[0].serving.fetch_add(1); _ = system::futex_wake(((&mut shared[0].serving) as *mut atomic) as *mut u32, 0x7FFFFFFF); } # Keeps what the thread running has of its own in its strand. def interpreter::save(&mut this, into: *mut strand): void { into[0].stack = this.stack; into[0].stack_end = this.stack_end; into[0].top = this.top; into[0].calls = move(&mut this.calls); into[0].texts = move(&mut this.texts); into[0].depth = this.depth; into[0].trace = move(&mut this.trace); into[0].countdown = this.countdown; into[0].last_error = this.last_error; into[0].racer = this.races.thread; into[0].clock = move(&mut this.races.clock); into[0].active = false; } # Holds a thread's strand as the thread running's. def interpreter::restore(&mut this, from: *mut strand): void { this.stack = from[0].stack; this.stack_end = from[0].stack_end; this.top = from[0].top; this.calls = move(&mut from[0].calls); this.texts = move(&mut from[0].texts); this.depth = from[0].depth; this.trace = move(&mut from[0].trace); this.countdown = from[0].countdown; this.last_error = from[0].last_error; this.races.thread = from[0].racer; this.races.clock = move(&mut from[0].clock); this.strand = from; from[0].active = true; } #! Whether bytes from an address lie within the frames another thread of the #! program is using, which a reference into another's locals may reach. #! @param this The machine. #! @param at The address. #! @param bytes How many bytes. #! @returns Whether they do. pub def interpreter::in_other_frames(&mut this, at: u64, bytes: u64): bool { return false if this.threads == null; val shared := this.threads; for i in 0..shared[0].strands.length { val each: *mut strand = shared[0].strands[i]; continue if each == this.strand; return true if at >= each[0].stack as u64 && at <= each[0].top && each[0].top - at >= bytes; } return false; } #! Whether an address lies within the stack of any thread of the program. #! @param this The machine. #! @param at The address. #! @returns Whether it does. pub def interpreter::in_stacks(&mut this, at: u64): bool { return true if at >= this.stack as u64 && at < this.stack_end; return false if this.threads == null; val shared := this.threads; for i in 0..shared[0].strands.length { val each: *mut strand = shared[0].strands[i]; return true if at >= each[0].stack as u64 && at < each[0].stack_end; } return false; } #! In a copy of the program a thread made, which holds that thread alone, the #! other threads are gone. #! @param this The machine. pub def interpreter::forked(&mut this): void { return if this.threads == null; val shared := this.threads; var kept := vector::<*mut strand>::new(); kept.append(this.strand); shared[0].strands = move(&mut kept); shared[0].running = 0; while shared[0].handles.length != 0 { # Their threads of the system are gone with the copy, so none is waited for. var gone := move(&mut shared[0].handles.last); val leaked := &mut vector::>::new(); leaked.append(move(&mut gone)); shared[0].handles.truncate(); } } #! A wait in the system the machine makes for a thread: a futex's wait without a #! time lasts a tenth of a second at most while threads run, so the thread #! sees the program stop. #! @param this The machine. #! @param op The futex's operation. #! @param time Where the time it lasts is, or 0. #! @param into Where a time of the machine's own may be written. #! @returns Where the time is. pub def interpreter::wait_time(&mut this, op: u64, time: u64, into: *mut i64): u64 { return time if this.threads == null || (op & 0x7F) != 0 || time != 0; into[0] = 0; into[1] = longest_wait; return into as u64; } #! Once the program's `main` returns, or the program stops, the threads still #! running stop too: each at its next turn. They are waited for, so nothing of #! the machine is used once it is gone, but for one that never comes back from #! the system. Gives why the program stopped, where a thread stopped it. #! @param this The machine. #! @param ran Why `main` stopped. #! @returns Why the program stopped. pub def interpreter::end_threads(&mut this, ran: halt): halt { return ran if this.threads == null; val shared := this.threads; var result := ran; if shared[0].stopped { result = shared[0].stop; if result != halt::exited { this.trace = move(&mut shared[0].trace); } } else { shared[0].stopped = true; shared[0].stop = ran == halt::none ? halt::exited : ran; } val mine := this.strand; var tries := 0u; while shared[0].running > 0 && tries < 3000 { this.pause(); time::sleep(time::milliseconds(1)); _ = this.resume(mine); tries++; } if shared[0].running > 0 { return result; } # Every thread has ended, so joining each waits for no more than its end. shared[0].handles.close(); shared[0].strands.close(); shared[0].trace.close(); mine[0].clock.close(); raw_release(mine as *mut u8); raw_release(shared as *mut u8); this.threads = null; this.strand = null; this.countdown = 0; return result; }