github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/runtime/runtime_tinygowasm.go (about)

     1  //go:build tinygo.wasm && !wasm_unknown
     2  
     3  package runtime
     4  
     5  import (
     6  	"unsafe"
     7  )
     8  
     9  // Implements __wasi_iovec_t.
    10  type __wasi_iovec_t struct {
    11  	buf    unsafe.Pointer
    12  	bufLen uint
    13  }
    14  
    15  //go:wasmimport wasi_snapshot_preview1 fd_write
    16  func fd_write(id uint32, iovs *__wasi_iovec_t, iovs_len uint, nwritten *uint) (errno uint)
    17  
    18  // See:
    19  // https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-proc_exitrval-exitcode
    20  //
    21  //go:wasmimport wasi_snapshot_preview1 proc_exit
    22  func proc_exit(exitcode uint32)
    23  
    24  const (
    25  	putcharBufferSize = 120
    26  	stdout            = 1
    27  )
    28  
    29  // Using global variables to avoid heap allocation.
    30  var (
    31  	putcharBuffer        = [putcharBufferSize]byte{}
    32  	putcharPosition uint = 0
    33  	putcharIOVec         = __wasi_iovec_t{
    34  		buf: unsafe.Pointer(&putcharBuffer[0]),
    35  	}
    36  	putcharNWritten uint
    37  )
    38  
    39  func putchar(c byte) {
    40  	putcharBuffer[putcharPosition] = c
    41  	putcharPosition++
    42  
    43  	if c == '\n' || putcharPosition >= putcharBufferSize {
    44  		putcharIOVec.bufLen = putcharPosition
    45  		fd_write(stdout, &putcharIOVec, 1, &putcharNWritten)
    46  		putcharPosition = 0
    47  	}
    48  }
    49  
    50  func getchar() byte {
    51  	// dummy, TODO
    52  	return 0
    53  }
    54  
    55  func buffered() int {
    56  	// dummy, TODO
    57  	return 0
    58  }
    59  
    60  //go:linkname now time.now
    61  func now() (sec int64, nsec int32, mono int64) {
    62  	mono = nanotime()
    63  	sec = mono / (1000 * 1000 * 1000)
    64  	nsec = int32(mono - sec*(1000*1000*1000))
    65  	return
    66  }
    67  
    68  // Abort executes the wasm 'unreachable' instruction.
    69  func abort() {
    70  	trap()
    71  }
    72  
    73  //go:linkname syscall_Exit syscall.Exit
    74  func syscall_Exit(code int) {
    75  	proc_exit(uint32(code))
    76  }
    77  
    78  // TinyGo does not yet support any form of parallelism on WebAssembly, so these
    79  // can be left empty.
    80  
    81  //go:linkname procPin sync/atomic.runtime_procPin
    82  func procPin() {
    83  }
    84  
    85  //go:linkname procUnpin sync/atomic.runtime_procUnpin
    86  func procUnpin() {
    87  }
    88  
    89  func hardwareRand() (n uint64, ok bool) {
    90  	n |= uint64(libc_arc4random())
    91  	n |= uint64(libc_arc4random()) << 32
    92  	return n, true
    93  }
    94  
    95  // uint32_t arc4random(void);
    96  //
    97  //export arc4random
    98  func libc_arc4random() uint32