github.com/taubyte/vm-wasm-utils@v1.0.2/sys/sys.go (about) 1 package sys 2 3 import ( 4 "context" 5 "errors" 6 "fmt" 7 "io" 8 "io/fs" 9 "time" 10 11 "github.com/taubyte/vm-wasm-utils/platform" 12 "github.com/tetratelabs/wazero/sys" 13 ) 14 15 // Context holds module-scoped system resources currently only supported by 16 // built-in host functions. 17 type Context struct { 18 args, environ []string 19 argsSize, environSize uint32 20 stdin io.Reader 21 stdout, stderr io.Writer 22 23 // Note: Using function pointers here keeps them stable for tests. 24 25 walltime *sys.Walltime 26 walltimeResolution sys.ClockResolution 27 nanotime *sys.Nanotime 28 nanotimeResolution sys.ClockResolution 29 nanosleep *sys.Nanosleep 30 randSource io.Reader 31 fsc *FSContext 32 } 33 34 // Args is like os.Args and defaults to nil. 35 // 36 // Note: The count will never be more than math.MaxUint32. 37 // See wazero.ModuleConfig WithArgs 38 func (c *Context) Args() []string { 39 return c.args 40 } 41 42 // ArgsSize is the size to encode Args as Null-terminated strings. 43 // 44 // Note: To get the size without null-terminators, subtract the length of Args from this value. 45 // See wazero.ModuleConfig WithArgs 46 // See https://en.wikipedia.org/wiki/Null-terminated_string 47 func (c *Context) ArgsSize() uint32 { 48 return c.argsSize 49 } 50 51 // Environ are "key=value" entries like os.Environ and default to nil. 52 // 53 // Note: The count will never be more than math.MaxUint32. 54 // See wazero.ModuleConfig WithEnv 55 func (c *Context) Environ() []string { 56 return c.environ 57 } 58 59 // EnvironSize is the size to encode Environ as Null-terminated strings. 60 // 61 // Note: To get the size without null-terminators, subtract the length of Environ from this value. 62 // See wazero.ModuleConfig WithEnv 63 // See https://en.wikipedia.org/wiki/Null-terminated_string 64 func (c *Context) EnvironSize() uint32 { 65 return c.environSize 66 } 67 68 // Stdin is like exec.Cmd Stdin and defaults to a reader of os.DevNull. 69 // See wazero.ModuleConfig WithStdin 70 func (c *Context) Stdin() io.Reader { 71 return c.stdin 72 } 73 74 // Stdout is like exec.Cmd Stdout and defaults to io.Discard. 75 // See wazero.ModuleConfig WithStdout 76 func (c *Context) Stdout() io.Writer { 77 return c.stdout 78 } 79 80 // Stderr is like exec.Cmd Stderr and defaults to io.Discard. 81 // See wazero.ModuleConfig WithStderr 82 func (c *Context) Stderr() io.Writer { 83 return c.stderr 84 } 85 86 // Walltime implements sys.Walltime. 87 func (c *Context) Walltime() (sec int64, nsec int32) { 88 return (*(c.walltime))() 89 } 90 91 // WalltimeResolution returns resolution of Walltime. 92 func (c *Context) WalltimeResolution() sys.ClockResolution { 93 return c.walltimeResolution 94 } 95 96 // Nanotime implements sys.Nanotime. 97 func (c *Context) Nanotime() int64 { 98 return (*(c.nanotime))() 99 } 100 101 // NanotimeResolution returns resolution of Nanotime. 102 func (c *Context) NanotimeResolution() sys.ClockResolution { 103 return c.nanotimeResolution 104 } 105 106 // Nanosleep implements sys.Nanosleep. 107 func (c *Context) Nanosleep(ns int64) { 108 (*(c.nanosleep))(ns) 109 } 110 111 // FS returns a possibly nil file system context. 112 func (c *Context) FS(ctx context.Context) *FSContext { 113 // Override Context when it is passed via context 114 if fsValue := ctx.Value(FSKey{}); fsValue != nil { 115 return fsValue.(*FSContext) 116 } 117 return c.fsc 118 } 119 120 // RandSource is a source of random bytes and defaults to a deterministic source. 121 // see wazero.ModuleConfig WithRandSource 122 func (c *Context) RandSource() io.Reader { 123 return c.randSource 124 } 125 126 // eofReader is safer than reading from os.DevNull as it can never overrun operating system file descriptors. 127 type eofReader struct{} 128 129 // Read implements io.Reader 130 // Note: This doesn't use a pointer reference as it has no state and an empty struct doesn't allocate. 131 func (eofReader) Read([]byte) (int, error) { 132 return 0, io.EOF 133 } 134 135 // DefaultContext returns Context with no values set except a possibly nil fs.FS 136 func DefaultContext(fs fs.FS) *Context { 137 if sysCtx, err := NewContext(0, nil, nil, nil, nil, nil, nil, nil, 0, nil, 0, nil, fs); err != nil { 138 panic(fmt.Errorf("BUG: DefaultContext should never error: %w", err)) 139 } else { 140 return sysCtx 141 } 142 } 143 144 var _ = DefaultContext(nil) // Force panic on bug. 145 var ns sys.Nanosleep = platform.FakeNanosleep 146 147 // NewContext is a factory function which helps avoid needing to know defaults or exporting all fields. 148 // Note: max is exposed for testing. max is only used for env/args validation. 149 func NewContext( 150 max uint32, 151 args, environ []string, 152 stdin io.Reader, 153 stdout, stderr io.Writer, 154 randSource io.Reader, 155 walltime *sys.Walltime, 156 walltimeResolution sys.ClockResolution, 157 nanotime *sys.Nanotime, 158 nanotimeResolution sys.ClockResolution, 159 nanosleep *sys.Nanosleep, 160 fs fs.FS, 161 ) (sysCtx *Context, err error) { 162 sysCtx = &Context{args: args, environ: environ} 163 164 if sysCtx.argsSize, err = nullTerminatedByteCount(max, args); err != nil { 165 return nil, fmt.Errorf("args invalid: %w", err) 166 } 167 168 if sysCtx.environSize, err = nullTerminatedByteCount(max, environ); err != nil { 169 return nil, fmt.Errorf("environ invalid: %w", err) 170 } 171 172 if stdin == nil { 173 sysCtx.stdin = eofReader{} 174 } else { 175 sysCtx.stdin = stdin 176 } 177 178 if stdout == nil { 179 sysCtx.stdout = io.Discard 180 } else { 181 sysCtx.stdout = stdout 182 } 183 184 if stderr == nil { 185 sysCtx.stderr = io.Discard 186 } else { 187 sysCtx.stderr = stderr 188 } 189 190 if randSource == nil { 191 sysCtx.randSource = platform.NewFakeRandSource() 192 } else { 193 sysCtx.randSource = randSource 194 } 195 196 if walltime != nil { 197 if clockResolutionInvalid(walltimeResolution) { 198 return nil, fmt.Errorf("invalid Walltime resolution: %d", walltimeResolution) 199 } 200 sysCtx.walltime = walltime 201 sysCtx.walltimeResolution = walltimeResolution 202 } else { 203 sysCtx.walltime = platform.NewFakeWalltime() 204 sysCtx.walltimeResolution = sys.ClockResolution(time.Microsecond.Nanoseconds()) 205 } 206 207 if nanotime != nil { 208 if clockResolutionInvalid(nanotimeResolution) { 209 return nil, fmt.Errorf("invalid Nanotime resolution: %d", nanotimeResolution) 210 } 211 sysCtx.nanotime = nanotime 212 sysCtx.nanotimeResolution = nanotimeResolution 213 } else { 214 sysCtx.nanotime = platform.NewFakeNanotime() 215 sysCtx.nanotimeResolution = sys.ClockResolution(time.Nanosecond) 216 } 217 218 if nanosleep != nil { 219 sysCtx.nanosleep = nanosleep 220 } else { 221 sysCtx.nanosleep = &ns 222 } 223 224 if fs != nil { 225 sysCtx.fsc = NewFSContext(fs) 226 } else { 227 sysCtx.fsc = NewFSContext(EmptyFS) 228 } 229 230 return 231 } 232 233 // clockResolutionInvalid returns true if the value stored isn't reasonable. 234 func clockResolutionInvalid(resolution sys.ClockResolution) bool { 235 return resolution < 1 || resolution > sys.ClockResolution(time.Hour.Nanoseconds()) 236 } 237 238 // nullTerminatedByteCount ensures the count or Nul-terminated length of the elements doesn't exceed max, and that no 239 // element includes the nul character. 240 func nullTerminatedByteCount(max uint32, elements []string) (uint32, error) { 241 count := uint32(len(elements)) 242 if count > max { 243 return 0, errors.New("exceeds maximum count") 244 } 245 246 // The buffer size is the total size including null terminators. The null terminator count == value count, sum 247 // count with each value length. This works because in Go, the length of a string is the same as its byte count. 248 bufSize, maxSize := uint64(count), uint64(max) // uint64 to allow summing without overflow 249 for _, e := range elements { 250 // As this is null-terminated, We have to validate there are no null characters in the string. 251 for _, c := range e { 252 if c == 0 { 253 return 0, errors.New("contains NUL character") 254 } 255 } 256 257 nextSize := bufSize + uint64(len(e)) 258 if nextSize > maxSize { 259 return 0, errors.New("exceeds maximum size") 260 } 261 bufSize = nextSize 262 263 } 264 return uint32(bufSize), nil 265 }