#! @file heap.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the memory a program holds: the blocks it allocates and gives back #! itself, as `raw_allocate` and `raw_release` do, which the machine knows by #! where each begins and how large it is, so a release of what is no block is #! found, and what a constant holds is told apart from what it may not keep. #! #! Running with its memory checked, as `run --checks` asks, the machine also #! stops at a read or write through a reference or pointer where the program #! holds no memory: in a block it released, which is held back a while before #! its memory is used again so a late use still finds it released, and in a #! stack past the frames in use. Where code of the program's own calls C, whose #! memory the machine does not know, only those, and memory the program mapped #! and gave back, stop it from then on. On Windows `system` is made of calls of #! C, and what those give only its own code reads, so its calls alone do not #! count. It stops at a read of memory nothing wrote, too: of a block #! `raw_allocate` gave, the bytes `raw_resize` added, and a variable #! `undefined`, until each byte is written, which a call of the system or of C #! given an address into the memory counts as doing. As the program ends, the #! blocks it still holds that nothing it keeps reaches are reported, with where #! each was allocated. import sakura::analyzer; import sakura::compiler; import std::containers; module sakura::machine; #! Allocates a block the program gives back itself. #! @param this The machine. #! @param size The bytes it holds. #! @param cleared Whether it is zeroed, as `raw_allocate_zeroed` gives it, #! rather than holding what it may, as `raw_allocate` does. #! @returns Its first byte. pub def interpreter::allocate(&mut this, size: u64, cleared: bool): u64 { val bytes := size == 0 ? 1u : size; val made := (cleared ? raw_allocate_zeroed(bytes) : raw_allocate(bytes)) as u64; this.blocks.set(made, size); # Running with its memory checked, a block not cleared is never written, and # holds bytes no address is made of, so the blocks it reaches are the same # every run. if this.options.checks { this.index_block(made, size); if !cleared { memset(made as *mut u8, unwritten_byte, size); this.forget(made, size); } } return made; } #! What each byte of memory never written holds, running with memory checked: #! a word of them is no address the program holds. const unwritten_byte: u8 = 0xA5; #! The bits of a page of `unwritten`, or null where none of its bytes is #! unwritten: those last looked for, as reads and writes keep to a page mostly, #! or else those the dictionary holds. Each page's bits stay where they are #! once made, however the dictionary grows. #! @param this The machine. #! @param page The page's number. #! @returns Its bits. def interpreter::bits_of(&mut this, page: u64): *mut u64 { return this.seen_bits if page == this.seen_page; this.seen_page = page; this.seen_bits = null; if this.unwritten.get(&page) is some(&bits) { this.seen_bits = bits.data; } return this.seen_bits; } #! Marks bytes as never written, running with memory checked. #! @param this The machine. #! @param at The first. #! @param size How many. pub def interpreter::forget(&mut this, at: u64, size: u64): void { var from := at; val end := at + size; while from < end { val page := from / 4096; val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096; var bits := this.bits_of(page); if bits == null { var made := vector::::new(); made.resize(64); bits = made.data; this.unwritten.set(page, move(&mut made)); this.seen_bits = bits; } var byte := from - page * 4096; while byte < stop - page * 4096 { val word := byte / 64; val mask := word_mask(byte, stop - page * 4096); bits[word] = bits[word] | mask; byte = (word + 1) * 64; } from = stop; } } #! The bits of a word of a page's bits that bytes from one up to another cover, #! within the word the first is in. #! @param byte The first byte, within its page. #! @param end The byte after the last, within the page. #! @returns The bits. def word_mask(byte: u64, end: u64): u64 { val word := byte / 64; val last := end - word * 64 < 64 ? end - word * 64 : 64u; val high := last == 64 ? 0xFFFFFFFFFFFFFFFFu : (1u << last) - 1; return high & ~((1u << (byte % 64)) - 1); } #! Marks bytes as written, running with memory checked. #! @param this The machine. #! @param at The first. #! @param size How many. pub def interpreter::wrote(&mut this, at: u64, size: u64): void { return if this.unwritten.length == 0; # A read or a write is a word of bits mostly. val within := at % 64; if within + size <= 64 && size < 64 { val bits := this.bits_of(at / 4096); if bits != null { bits[at % 4096 / 64] = bits[at % 4096 / 64] & ~(((1u << size) - 1) << within); } return; } var from := at; val end := at + size; while from < end { val page := from / 4096; val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096; val bits := this.bits_of(page); if bits != null { var byte := from - page * 4096; while byte < stop - page * 4096 { val word := byte / 64; bits[word] = bits[word] & ~word_mask(byte, stop - page * 4096); byte = (word + 1) * 64; } } from = stop; } } #! Whether any of some bytes was never written, running with memory checked. #! @param this The machine. #! @param at The first. #! @param size How many. #! @returns Whether one was not. pub def interpreter::unwritten_in(&mut this, at: u64, size: u64): bool { return false if this.unwritten.length == 0; val within := at % 64; if within + size <= 64 && size < 64 { val bits := this.bits_of(at / 4096); return bits != null && (bits[at % 4096 / 64] & (((1u << size) - 1) << within)) != 0; } var from := at; val end := at + size; while from < end { val page := from / 4096; val stop := end < (page + 1) * 4096 ? end : (page + 1) * 4096; val bits := this.bits_of(page); if bits != null { var byte := from - page * 4096; while byte < stop - page * 4096 { val word := byte / 64; return true if (bits[word] & word_mask(byte, stop - page * 4096)) != 0; byte = (word + 1) * 64; } } from = stop; } return false; } #! Copies which of some bytes were never written to where they are copied, #! running with memory checked, as copying them copies what they hold: a copy #! is no read, so what was never written stays so where it went. #! @param this The machine. #! @param to Where the first is copied to. #! @param from The first. #! @param size How many. pub def interpreter::copy_unwritten(&mut this, to: u64, from: u64, size: u64): void { return if this.unwritten.length == 0; if !this.unwritten_in(from, size) { this.wrote(to, size); return; } # Byte by byte, from the end where the copy goes past where it comes from. for k in 0..size { val i := to > from ? size - 1 - k : k; if this.unwritten_in(from + i, 1) { this.forget(to + i, 1); } else { this.wrote(to + i, 1); } } } #! Marks the memory an address the system or C is given points into as #! written, running with memory checked, as what each writes there is not #! known: a block the program holds, whole, or the frames from the address on. #! @param this The machine. #! @param at The address. pub def interpreter::wrote_through(&mut this, at: u64): void { return if this.unwritten.length == 0 || at < null_page; if at >= this.stack as u64 && at < this.top { this.wrote(at, this.top - at); return; } val first := this.indexed_block(at); if first != 0 { this.wrote(first, this.blocks[first]); } } #! Notes a block on each page it is over, to the byte past its end, running #! with its memory checked, so the block an address is within is found among #! those of its page. #! @param this The machine. #! @param address The block's first byte. #! @param size Its bytes. def interpreter::index_block(&mut this, address: u64, size: u64): void { for page in address / 4096..(address + size) / 4096 + 1 { if this.pages.contains(&page) { val held: &mut vector = this.pages[page]; held.append(address); } else { var made := vector::::new(); made.append(address); this.pages.set(page, move(&mut made)); } } } #! Takes a block off the pages it is over, as it is released. #! @param this The machine. #! @param address The block's first byte. #! @param size Its bytes. def interpreter::unindex_block(&mut this, address: u64, size: u64): void { for page in address / 4096..(address + size) / 4096 + 1 { if this.pages.contains(&page) { val held: &mut vector = this.pages[page]; for i in 0..held.length { if held[i] == address { held[i] = held.last(); held.truncate(); break; } } } } } #! The block an address is within, to the byte past its end, among those of #! its page, running with its memory checked: one it is before the end of #! where an address is both the end of one and the start of the next. #! @param this The machine. #! @param at The address. #! @returns The block's first byte, or 0. def interpreter::indexed_block(&mut this, at: u64): u64 { var found: u64 = 0; if this.pages.get(&(at / 4096)) is some(&held) { for &each in held.view() { val first: u64 = each; val size: u64 = this.blocks[first]; if at >= first && at <= first + size { return first if at < first + size; found = first; } } } return found; } #! Gives a block back. #! @param this The machine. #! @param address The block's first byte, or 0, which gives nothing back. #! @returns `invalid_release` where the address is no block the program holds. pub def interpreter::release(&mut this, address: u64): halt { return halt::none if address == 0; if !this.blocks.contains(&address) { return halt::invalid_release; } val size: u64 = this.blocks[address]; this.blocks.remove(&address); this.kept.remove(&address); if this.options.checks { this.wrote(address, size); this.unindex_block(address, size); this.sites.remove(&address); this.hold_back(address, size); return halt::none; } raw_release(address as *mut u8); return halt::none; } #! The bytes of released blocks held back at most, and how many. const held_back_bytes: u64 = 67108864; const held_back_most: u64 = 65536; #! Holds a released block back from being used again, giving back the oldest #! held back where too many are. #! @param this The machine. #! @param address The block's first byte. #! @param size The bytes it holds. def interpreter::hold_back(&mut this, address: u64, size: u64): void { this.released.append(address); this.released_sizes.append(size); this.released_bytes += size; while this.released_bytes > held_back_bytes || this.released.length - this.released_from > held_back_most { val oldest: u64 = this.released[this.released_from]; raw_release(oldest as *mut u8); this.released_bytes -= this.released_sizes[this.released_from]; this.released_from++; } # The list is moved down once half of it is let go of. if this.released_from > 1024 && this.released_from * 2 > this.released.length { var kept := vector::::new(); var sizes := vector::::new(); for i in this.released_from..this.released.length { kept.append(this.released[i]); sizes.append(this.released_sizes[i]); } this.released = move(&mut kept); this.released_sizes = move(&mut sizes); this.released_from = 0; } } #! Notes where a block was allocated, running with its memory checked: the #! innermost frame of a function of the program's own rather than std's. #! @param this The machine. #! @param address The block's first byte. #! @param pc Where the code running is. pub def interpreter::note_site(&mut this, address: u64, pc: u64): void { return if address == 0; var i := this.calls.length; while i > 0 { i--; val function: u32 = this.calls.at(i).function; val at := i == this.calls.length - 1 ? pc : this.calls.at(i + 1).site; if !this.in_std_function(function) || i == 0 { this.sites.set(address, pair_key(function, at as u32)); return; } } } #! Keeps the words of the frames the running thread has in use as the program #! ends by exiting, running with its memory checked, so that the leaks reported #! count them as reaching what they hold: neither a thread stopped as `main` #! returns nor one that exits releases what its locals hold. #! @param this The machine. pub def interpreter::keep_frames(&mut this): void { var at := this.stack as u64; while at + word_size <= this.top { this.ended.append((at as *u64)[0]); at += word_size; } } #! Whether a function is std's, or an anonymous function within one of std's. #! @param this The machine. #! @param function The function. #! @returns Whether it is. def interpreter::in_std_function(&mut this, function: u32): bool { val held := &this.c.program.functions[function]; val decl := held.decl != 0 ? held.decl : held.outer; return decl != 0 && this.c.in_std(decl); } #! Whether a function is `system`'s, or an anonymous function within one of #! `system`'s. #! @param this The machine. #! @param function The function. #! @returns Whether it is. def interpreter::in_system_function(&mut this, function: u32): bool { val held := &this.c.program.functions[function]; val decl := held.decl != 0 ? held.decl : held.outer; return decl != 0 && this.in_system(decl); } #! Whether the code at a place in a function is `system`'s: that of a function #! of `system`'s, or, in the code giving the globals their values, that giving #! one of `system`'s its value, as the file it is written in says. #! @param this The machine. #! @param function The function. #! @param pc Where in its code. #! @returns Whether it is. def interpreter::in_system_code(&mut this, function: u32, pc: u64): bool { return this.in_system_function(function) if function != this.c.program.init; var at: u64 = 0; for &mark in this.c.program.functions[function].compiled.lines { break if mark.pc as u64 > pc; at = mark.at; } # A file of `system`'s declares only what is `system`'s, so any declaration # of the file says whose the code is. if at != 0 { val file := pair_high(at) - 1; for decl in 1..this.c.checker.decls.count { continue if this.c.checker.decls.files.p[decl] != file || this.c.checker.decls.nodes.p[decl] == 0; return this.in_system(decl as u32); } } return true; } #! Whether a declaration is `system`'s, which on Windows is made of calls of C #! whose memory only its own code reads. #! @param this The machine. #! @param decl The declaration. #! @returns Whether it is. def interpreter::in_system(&this, decl: u32): bool { var at: u32 = this.c.checker.decls.modules.p[decl]; var steps := 0; while at != 0 && this.c.checker.modules.parents[at] != 0 && steps < 64 { at = this.c.checker.modules.parents[at]; steps++; } return at != 0 && this.c.checker.modules.names[at] == word::system; } #! Notes the memory a system call that succeeded maps or unmaps, running with #! its memory checked, which the program holds as it does a block: what `mmap` #! and `mremap` give, in whole pages, until `munmap` gives it back. Where the #! program calls C, which takes memory the machine does not know as C's, what #! it gave back is kept apart, so a late use still finds it given back. #! @param this The machine. #! @param number The call, as Linux numbers them. #! @param a Its first argument. #! @param b Its second. #! @param c Its third. #! @param result What it gave. pub def interpreter::note_mapping(&mut this, number: u64, a: u64, b: u64, c: u64, result: u64): void { if number == 9 { this.add_run(result, (b + 4095) / 4096 * 4096); } else if number == 11 { val size := (b + 4095) / 4096 * 4096; drop_runs(&mut this.mapped, a, size); if this.calls_c { drop_runs(&mut this.unmapped, a, size); insert_run(&mut this.unmapped, a, size); } } else if number == 25 { for i in 0..this.mapped.length / 2 { if this.mapped[2 * i] == a { this.mapped.remove_at(2 * i + 1); this.mapped.remove_at(2 * i); break; } } this.add_run(result, (c + 4095) / 4096 * 4096); } } #! Notes memory the program was given, running with its memory checked, among #! the runs kept in order of where each begins. #! @param this The machine. #! @param start Its first byte. #! @param size Its bytes. pub def interpreter::add_run(&mut this, start: u64, size: u64): void { insert_run(&mut this.mapped, start, size); } #! Puts a run of memory among runs kept in order of where each begins. #! @param runs The runs, as pairs of where each begins and its bytes. #! @param start Its first byte. #! @param size Its bytes. def insert_run(runs: &mut vector, start: u64, size: u64): void { var at := runs.length; while at > 0 && runs[at - 2] > start { at -= 2; } runs.insert_at(at, size); runs.insert_at(at, start); } #! Takes the runs of memory lying within some memory from runs kept in order of #! where each begins. #! @param runs The runs, as pairs of where each begins and its bytes. #! @param start The memory's first byte. #! @param size Its bytes. def drop_runs(runs: &mut vector, start: u64, size: u64): void { var i := 0u; while i < runs.length { val first: u64 = runs[i]; val bytes: u64 = runs[i + 1]; if first >= start && first + bytes <= start + size { runs.remove_at(i + 1); runs.remove_at(i); } else { i += 2; } } } #! Of runs of memory, as pairs of where each begins and its bytes in order of #! where each begins, the one that may hold the address: the last beginning at #! or before it, or the count of runs where none does. #! @param runs The runs. #! @param at The address. #! @returns The run's index. def find_run(runs: &vector, at: u64): u64 { val count := runs.length / 2; var low: u64 = 0; var high := count; while low < high { val middle := (low + high) / 2; if runs[2 * middle] <= at { low = middle + 1; } else { high = middle; } } return low == 0 ? count : low - 1; } #! Puts where each datum is and its bytes in order, running with its memory #! checked, so the one an address is within is found by halves. #! @param this The machine. def interpreter::order_data(&mut this): void { for i in 0..this.data.length { val data: u64 = this.data[i]; this.data_runs.append(data); this.data_runs.append(this.c.program.data[i].bytes.length); } # In order of where each begins, two words at a time. for i in 1..this.data_runs.length / 2 { var j := i; while j > 0 && this.data_runs[2 * (j - 1)] > this.data_runs[2 * j] { val start: u64 = this.data_runs[2 * j]; val size: u64 = this.data_runs[2 * j + 1]; this.data_runs[2 * j] = this.data_runs[2 * (j - 1)]; this.data_runs[2 * j + 1] = this.data_runs[2 * (j - 1) + 1]; this.data_runs[2 * (j - 1)] = start; this.data_runs[2 * (j - 1) + 1] = size; j--; } } } #! Whether elements from a pointer lie where the program may read and write #! them, running with its memory checked: in memory it holds or mapped, or, #! where it calls C, anywhere but in a block released and held back, in a stack #! past the frames in use, or in memory it mapped and gave back. That is so of #! code of the program's own only once it has called C, since on Windows #! `system` is made of calls of C, whose memory only `system`'s code reads. #! @param this The machine. #! @param pointer The first element. #! @param count How many. #! @param size The bytes of each. #! @returns Whether they do. pub def interpreter::checked_reach(&mut this, pointer: u64, count: u64, size: u64): bool { # Within the first page, the read or the write itself stops the program, as # one through null, as where memory is not checked. return true if pointer < null_page; return true if count == 0 || size == 0; val bytes := count * size; return false if bytes / count != size; var start: u64 = 0; val end := this.region(pointer, &mut start); return end - pointer >= bytes if end != 0; val run := find_run(&this.mapped, pointer); if run < this.mapped.length / 2 { val first: u64 = this.mapped[2 * run]; val size: u64 = this.mapped[2 * run + 1]; return first + size - pointer >= bytes if pointer < first + size; } return true if this.in_other_frames(pointer, bytes); for i in this.released_from..this.released.length { val first: u64 = this.released[i]; return false if pointer >= first && pointer < first + this.released_sizes[i]; } return false if this.in_stacks(pointer); val gone := find_run(&this.unmapped, pointer); if gone < this.unmapped.length / 2 { val first: u64 = this.unmapped[2 * gone]; val size: u64 = this.unmapped[2 * gone + 1]; return false if pointer < first + size; } return this.calls_c && (this.called_c || this.in_system_function(this.calls.last().function)); } #! Writes what blocks the program allocated it still holds that nothing it #! keeps reaches, as a run with its memory checked does once the program ends: #! those neither a global, nor the frames a thread had in use as the program #! exited, nor a block either reaches holds the address of, with where they were #! allocated, those of each place together. #! @param this The machine. #! @param out Where it is written. pub def interpreter::report_leaks(&mut this, out: &mut string): void { # The blocks, by where each begins, to find the one an address is within. var starts := vector::::new(); for &entry in this.blocks { starts.append(entry.key); } starts.sort(); # The blocks the globals reach, and those they reach in turn. var reached := hashset::::new(); var todo := vector::::new(); this.reach_words(this.globals as u64, this.globals as u64 + this.c.program.globals, &starts, &mut reached, &mut todo); if this.ended.length != 0 { val words := (&this.ended[0]) as *u64 as u64; this.reach_words(words, words + this.ended.length * word_size, &starts, &mut reached, &mut todo); } while todo.length != 0 { val block: u64 = todo.last(); todo.truncate(); this.reach_words(block, block + this.blocks[block], &starts, &mut reached, &mut todo); } # What is lost, by where it was allocated. var places := vector::::new(); var counts := vector::::new(); var sizes := vector::::new(); var blocks: u64 = 0; var bytes: u64 = 0; for &first in starts { continue if reached.contains(&first) || this.kept.contains(&first); val size: u64 = this.blocks[first]; blocks++; bytes += size; var place := string::from("an unknown place", nothing {}); if this.sites.get(&first) is some(site) { val frame := this.site_frame(pair_high(site), pair_low(site) as u64); place = $"{frame.function} ({frame.path}:{frame.line}:{frame.column})"; } var found := places.length; for i in 0..places.length { if places[i].view() == place.view() { found = i; break; } } if found == places.length { places.append(move(&mut place)); counts.append(0); sizes.append(0); } counts[found] += 1; sizes[found] += size; } return if blocks == 0; # The places in order, so the report reads the same each run. var order := vector::::new(); for i in 0..places.length { order.append(i); } for i in 1..order.length { var j := i; while j > 0 && places[order[j - 1]].compare(places[order[j]].view()) > 0 { val held: u64 = order[j]; order[j] = order[j - 1]; order[j - 1] = held; j--; } } val noun := blocks == 1 ? "block" : "blocks"; out.append($"sakura: {blocks} {noun} the program allocated, {bytes} bytes, were never released, and nothing it keeps reaches them:\n"); for &i in order { val count: u64 = counts[i]; val each := count == 1 ? "block" : "blocks"; out.append($" {count} {each}, {sizes[i]} bytes, allocated at {places[i]}\n"); } } #! Marks the blocks the words of memory hold the addresses of, or addresses #! within, which are to have their own words read. #! @param this The machine. #! @param from The first byte. #! @param to The byte past the last. #! @param starts Where each block begins, in order. #! @param reached The blocks marked. #! @param todo The blocks marked whose words are to be read. def interpreter::reach_words(&mut this, from: u64, to: u64, starts: &vector, reached: &mut hashset, todo: &mut vector): void { return if starts.length == 0; var at := (from + word_size - 1) / word_size * word_size; while at + word_size <= to { val word := (at as *u64)[0]; at += word_size; continue if word < starts[0]; val index := starts.view().upper_bound(&word); continue if index == 0; val first: u64 = starts[index - 1]; continue if word >= first + (this.blocks[first] == 0 ? 1 : this.blocks[first]); if reached.insert(first) { todo.append(first); } } } #! Moves a block to one of another size, keeping what fits, and gives the old #! one back. Resizing no block allocates one. #! @param this The machine. #! @param address The block's first byte, or 0. #! @param size The bytes the new one holds. #! @returns The new block's first byte. pub def interpreter::resize(&mut this, address: u64, size: u64): u64 { return this.allocate(size, false) if address == 0; val had: u64 = this.blocks[address]; val made := this.allocate(size, false); val kept := had < size ? had : size; memcpy(made as *mut u8, address as *u8, kept); if this.options.checks { this.copy_unwritten(made, address, kept); } this.release(address); return made; } #! The memory the program holds an address within, while compiling: the #! globals, the frames in use, or a block, each up to the byte past its end. #! @param this The machine. #! @param at The address. #! @param start Where the memory begins is written here. #! @returns Where it ends, or 0 where the program holds no memory there. def interpreter::region(&mut this, at: u64, start: &mut u64): u64 { val globals := this.globals as u64; if at >= globals && at <= globals + this.c.program.globals { start = globals; return globals + this.c.program.globals; } if at >= this.stack as u64 && at <= this.top { start = this.stack as u64; return this.top; } if this.options.checks { val first := this.indexed_block(at); if first != 0 { start = first; return first + this.blocks[first]; } } else { for &entry in this.blocks { if at >= entry.key && at <= entry.key + entry.value { start = entry.key; return entry.key + entry.value; } } } if this.options.checks { val run := find_run(&this.data_runs, at); if run < this.data_runs.length / 2 && at <= this.data_runs[2 * run] + this.data_runs[2 * run + 1] { start = this.data_runs[2 * run]; return start + this.data_runs[2 * run + 1]; } return 0; } for i in 0..this.data.length { val data: u64 = this.data[i]; val size := this.c.program.data[i].bytes.length; if at >= data && at <= data + size { start = data; return data + size; } } return 0; } #! Whether elements from a pointer lie in memory the program holds, as reading #! them while compiling asks. #! @param this The machine. #! @param pointer The first element. #! @param count How many. #! @param size The bytes of each. #! @returns Whether they do. pub def interpreter::reaches(&mut this, pointer: u64, count: u64, size: u64): bool { return false if pointer == 0; return true if count == 0; var start: u64 = 0; val end := this.region(pointer, &mut start); return false if end == 0; val bytes := count * size; return bytes / count == size && end - pointer >= bytes; } #! Whether two pointers are within the same memory, which comparing or #! subtracting them while compiling asks, since where different memory is #! changes from one build to the next. #! @param this The machine. #! @param a One pointer. #! @param b The other. #! @returns Whether they are. pub def interpreter::same_memory(&mut this, a: u64, b: u64): bool { return true if a == b; return false if a == 0 || b == 0; var start: u64 = 0; val end := this.region(a, &mut start); return end != 0 && b >= start && b <= end; }