Path: blob/main/crates/c-api/tests/component/utils.h
3072 views
#pragma once1#include <string_view>23// From crates/component-util/src/lib.rs4inline constexpr std::string_view REALLOC_AND_FREE =5R"END(6(global $last (mut i32) (i32.const 8))7(func $realloc (export "realloc")8(param $old_ptr i32)9(param $old_size i32)10(param $align i32)11(param $new_size i32)12(result i32)1314(local $ret i32)1516;; Test if the old pointer is non-null17local.get $old_ptr18if19;; If the old size is bigger than the new size then20;; this is a shrink and transparently allow it21local.get $old_size22local.get $new_size23i32.gt_u24if25local.get $old_ptr26return27end2829;; otherwise fall through to allocate a new chunk which will later30;; copy data over31end3233;; align up `$last`34(global.set $last35(i32.and36(i32.add37(global.get $last)38(i32.add39(local.get $align)40(i32.const -1)))41(i32.xor42(i32.add43(local.get $align)44(i32.const -1))45(i32.const -1))))4647;; save the current value of `$last` as the return value48global.get $last49local.set $ret5051;; bump our pointer52(global.set $last53(i32.add54(global.get $last)55(local.get $new_size)))5657;; while `memory.size` is less than `$last`, grow memory58;; by one page59(loop $loop60(if61(i32.lt_u62(i32.mul (memory.size) (i32.const 65536))63(global.get $last))64(then65i32.const 166memory.grow67;; test to make sure growth succeeded68i32.const -169i32.eq70if unreachable end7172br $loop)))737475;; ensure anything necessary is set to valid data by spraying a bit76;; pattern that is invalid77local.get $ret78i32.const 0xde79local.get $new_size80memory.fill8182;; If the old pointer is present then that means this was a reallocation83;; of an existing chunk which means the existing data must be copied.84local.get $old_ptr85if86local.get $ret ;; destination87local.get $old_ptr ;; source88local.get $old_size ;; size89memory.copy90end9192local.get $ret93)94)END";959697