Files
bare-operating-system/packages/bare-os-seeder/kernel/bin/sh
T
Raven Scott 21325e18d3
Release rolling / release (push) Successful in 9m45s
Harden Coreutils Bump to 0.1.1
2026-08-12 21:47:16 -04:00

473 lines
13 KiB
Plaintext

/* BARE_OS_BIN_API 1.0.0 — bump when staged /bin script semantics change (see developer guide). */
/** Shared helpers for drive-resident /bin scripts (prepended before each command). */
function bareStdin(ctx) {
return typeof ctx.shellStdin === 'string' ? ctx.shellStdin : ''
}
/** @param {number} mode @param {'file' | 'directory' | 'symlink'} type */
function bareFormatModeString(mode, type) {
const typeChar = type === 'directory' ? 'd' : type === 'symlink' ? 'l' : '-'
const perm = mode & 0o777
const r = (bit) => (perm & bit ? 'r' : '-')
const w = (bit) => (perm & bit ? 'w' : '-')
const x = (bit) => (perm & bit ? 'x' : '-')
return (
typeChar +
r(0o400) +
w(0o200) +
x(0o100) +
r(0o040) +
w(0o020) +
x(0o010) +
r(0o004) +
w(0o002) +
x(0o001)
)
}
/** @param {number} mtimeMs @param {number} [nowMs] */
function bareFormatLsMtime(mtimeMs, nowMs) {
const now = nowMs != null ? nowMs : Date.now()
const d = new Date(mtimeMs)
const months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
const mon = months[d.getMonth()]
const day = String(d.getDate()).padStart(2, ' ')
const sixMo = 180 * 24 * 3600 * 1000
if (Math.abs(now - mtimeMs) > sixMo) {
const yr = String(d.getFullYear()).padStart(4, ' ')
return mon + ' ' + day + ' ' + yr
}
const hh = String(d.getHours()).padStart(2, '0')
const mm = String(d.getMinutes()).padStart(2, '0')
return mon + ' ' + day + ' ' + hh + ':' + mm
}
/** @param {number} size */
function barePosixBlocks(size) {
return Math.ceil(Number(size) / 512) || 0
}
/**
* Raw stdout for NUL/binary when **`process.stdout.write`** is missing.
* If **`ctx.bareOsBinWrite(Uint8Array|string)`** is set (tests / host), use it.
* @param {Record<string, unknown>} ctx
* @param {string | Uint8Array} chunk
* @returns {boolean}
*/
function bareOsEmitRaw(ctx, chunk) {
if (typeof ctx.bareOsBinWrite === 'function') {
const b4 = ctx.b4a
const u8 =
typeof chunk === 'string'
? b4 && typeof b4.from === 'function'
? b4.from(chunk)
: new TextEncoder().encode(chunk)
: chunk
ctx.bareOsBinWrite(u8 instanceof Uint8Array ? u8 : new Uint8Array(u8))
return true
}
const w = globalThis.process?.stdout?.write
if (typeof w === 'function') {
w.call(globalThis.process.stdout, chunk)
return true
}
return false
}
/** Session env map (`vfs.env`, then `ctx.env`). Never throws. */
function bareOsEnv(ctx) {
const v = ctx && ctx.vfs && ctx.vfs.env
if (v && typeof v === 'object') return v
const e = ctx && ctx.env
if (e && typeof e === 'object') return e
return {}
}
/**
* Strict POSIX-ish decimal integer (no octal, no exponent, no empty).
* @param {unknown} s
* @returns {number}
*/
function bareOsParseDecInt(s) {
const t = String(s == null ? '' : s).trim()
if (!/^[+-]?(?:0|[1-9][0-9]*)$/.test(t)) return NaN
const n = Number.parseInt(t, 10)
return Number.isSafeInteger(n) ? n : NaN
}
/** @param {unknown} s */
function bareOsParseNonNegInt(s) {
const n = bareOsParseDecInt(s)
return n >= 0 ? n : NaN
}
/**
* @param {Record<string, unknown>} ctx
* @param {string} name
* @param {number} fallback
* @param {number} [min]
* @param {number} [max]
*/
function bareOsEnvInt(ctx, name, fallback, min, max) {
const raw = bareOsEnv(ctx)[name]
if (raw == null || raw === '') return fallback
const n = Number.parseInt(String(raw), 10)
if (!Number.isFinite(n)) return fallback
let v = n
if (min != null && v < min) v = min
if (max != null && v > max) v = max
return v
}
/**
* @param {Record<string, unknown>} ctx
* @param {string} msg
* @param {number} [code]
*/
function bareOsFail(ctx, msg, code) {
if (msg) ctx.console.error(msg)
ctx.exitCode = code == null ? 1 : code
}
/** @param {unknown} e */
function bareOsIsNotFoundErr(e) {
const code = e && typeof e === 'object' ? e.code : ''
if (code === 'ENOENT') return true
const msg = String((e && e.message) || e || '')
return /ENOENT|No such file|not found/i.test(msg)
}
/**
* @param {Record<string, unknown>} ctx
* @param {unknown} buf
* @returns {Uint8Array}
*/
function bareOsToU8(ctx, buf) {
if (!buf) return new Uint8Array(0)
if (buf instanceof Uint8Array) return buf
if (ctx && ctx.b4a && typeof ctx.b4a.from === 'function') return ctx.b4a.from(buf)
return new Uint8Array(buf)
}
/** @param {string} dir @param {string} name */
function bareOsJoinPath(dir, name) {
const d = String(dir || '').replace(/\/+$/, '')
const n = String(name || '').replace(/^\/+/, '')
if (!d || d === '/') return '/' + n
return d + '/' + n
}
/** @param {string} p */
function bareOsBaseName(p) {
const t = String(p || '').replace(/\/+$/, '')
if (!t || t === '/') return t === '/' ? '/' : ''
const i = t.lastIndexOf('/')
return i < 0 ? t : t.slice(i + 1) || t
}
/** @param {string} p */
function bareOsParentDir(p) {
const t = String(p || '').replace(/\/+$/, '') || '/'
if (t === '/') return '/'
const i = t.lastIndexOf('/')
return i <= 0 ? '/' : t.slice(0, i) || '/'
}
/** @param {string} p */
function bareOsNormPath(p) {
return String(p || '').replace(/\/+$/, '') || '/'
}
/**
* @param {Record<string, unknown>} ctx
* @param {string} p
*/
function bareOsResolvePath(ctx, p) {
if (ctx && ctx.vfs && typeof ctx.vfs.resolveLogical === 'function') {
try {
return String(ctx.vfs.resolveLogical(p) || p)
} catch {
/* fall through */
}
}
return String(p || '')
}
/**
* True when dest is src or lives under src (self-copy / self-move).
* @param {Record<string, unknown>} ctx
* @param {string} src
* @param {string} dest
*/
function bareOsDestInsideSrc(ctx, src, dest) {
const s = bareOsNormPath(bareOsResolvePath(ctx, src))
const d = bareOsNormPath(bareOsResolvePath(ctx, dest))
if (s === d) return true
if (s === '/') return d !== '/'
return d === s || d.startsWith(s + '/')
}
const BARE_OS_B64_ALPH =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
/** @param {Uint8Array} u8 */
function bareOsB64Encode(u8) {
let out = ''
let i = 0
for (; i + 2 < u8.length; i += 3) {
const n = (u8[i] << 16) | (u8[i + 1] << 8) | u8[i + 2]
out +=
BARE_OS_B64_ALPH[(n >> 18) & 63] +
BARE_OS_B64_ALPH[(n >> 12) & 63] +
BARE_OS_B64_ALPH[(n >> 6) & 63] +
BARE_OS_B64_ALPH[n & 63]
}
const rest = u8.length - i
if (rest === 1) {
const n = u8[i] << 16
out += BARE_OS_B64_ALPH[(n >> 18) & 63] + BARE_OS_B64_ALPH[(n >> 12) & 63] + '=='
} else if (rest === 2) {
const n = (u8[i] << 16) | (u8[i + 1] << 8)
out +=
BARE_OS_B64_ALPH[(n >> 18) & 63] +
BARE_OS_B64_ALPH[(n >> 12) & 63] +
BARE_OS_B64_ALPH[(n >> 6) & 63] +
'='
}
return out
}
/**
* RFC 4648 Base64 decode (also accepts URL-safe alphabet). Rejects junk.
* @param {string} s
* @returns {Uint8Array}
*/
function bareOsB64Decode(s) {
const t = String(s).replace(/\s+/g, '')
if (!t) return new Uint8Array(0)
if (t.length % 4 === 1) throw new Error('invalid base64 length')
let pad = 0
if (t.endsWith('==')) pad = 2
else if (t.endsWith('=')) pad = 1
const body = pad ? t.slice(0, t.length - pad) : t
const bytes = []
let buf = 0
let bits = 0
for (let i = 0; i < body.length; i++) {
const c = body[i]
let v = BARE_OS_B64_ALPH.indexOf(c)
if (v < 0) {
if (c === '-') v = 62
else if (c === '_') v = 63
else throw new Error('invalid base64 character')
}
buf = (buf << 6) | v
bits += 6
if (bits >= 8) {
bits -= 8
bytes.push((buf >> bits) & 255)
}
}
if (pad) {
const want = Math.floor((body.length * 6) / 8)
if (bytes.length > want) bytes.length = want
}
return new Uint8Array(bytes)
}
/**
* @param {string} s
* @returns {Uint8Array}
*/
function bareOsHexDecode(s) {
const t = String(s).replace(/\s+/g, '')
if (t.length % 2 !== 0) throw new Error('odd hex length')
const out = new Uint8Array(t.length / 2)
for (let i = 0; i < out.length; i++) {
const pair = t.slice(i * 2, i * 2 + 2)
if (!/^[0-9a-fA-F]{2}$/.test(pair)) throw new Error('invalid hex')
out[i] = Number.parseInt(pair, 16)
}
return out
}
/** @param {Uint8Array} u8 */
function bareOsHexEncode(u8) {
let s = ''
for (let i = 0; i < u8.length; i++) s += u8[i].toString(16).padStart(2, '0')
return s
}
async function run(ctx, argv) {
if (argv.length < 2) {
ctx.console.error('usage: sh [-eu] [-s | -c COMMAND | SCRIPT]')
ctx.exitCode = 2
return
}
if (typeof ctx.execLine !== 'function') {
ctx.console.error('sh: execLine is not available (requires a Bare OS booter session)')
ctx.exitCode = 1
return
}
const vfsEnv =
ctx.vfs?.env && typeof ctx.vfs.env === 'object' ? ctx.vfs.env : null
let i = 1
let sawFlags = false
while (i < argv.length) {
const a = argv[i]
if (a === '--') {
i++
break
}
if (a === '-' || !a.startsWith('-')) break
if (a === '-c' || a === '-s') break
sawFlags = true
for (const ch of a.slice(1)) {
if (ch === 'e' && vfsEnv) vfsEnv.BARE_OS_SHELL_ERREXIT = '1'
else if (ch === 'u' && vfsEnv) vfsEnv.BARE_OS_SHELL_NOUNSET = '1'
else if (ch === 'v' && vfsEnv) vfsEnv.BARE_OS_SHELL_XTRACE = '1'
else if (ch === 'x' && vfsEnv) vfsEnv.BARE_OS_SHELL_XTRACE = '1'
else if (ch === 'C' && vfsEnv) vfsEnv.BARE_OS_SHELL_NOCLOBBER = '1'
}
i++
}
const mode = argv[i]
if (mode == null && !sawFlags) {
ctx.console.error('usage: sh [-eu] [-s | -c COMMAND | SCRIPT]')
ctx.exitCode = 2
return
}
if (mode === '-c') {
const command = argv[i + 1]
if (command == null) {
ctx.console.error('sh: option requires an argument -- c')
ctx.console.error('usage: sh -c COMMAND [NAME [ARG ...]] | sh SCRIPT')
ctx.exitCode = 2
return
}
const env = ctx.vfs?.env
/** @type {Record<string, string | undefined> | null} */
const saved = env && typeof env === 'object' ? {} : null
if (saved && env) {
for (const k of ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '#']) {
saved[k] = env[k]
}
env['0'] = argv[i + 3] ?? 'sh'
const args = argv.slice(i + 4)
for (let j = 1; j <= 9; j++) env[String(j)] = args[j - 1] ?? ''
env['#'] = String(args.length)
}
try {
await ctx.execLine(command)
const v = ctx.vfs?.env?.BARE_OS_EXIT_STATUS
const n = Number.parseInt(String(v ?? ''), 10)
if (Number.isFinite(n)) ctx.exitCode = n
} finally {
if (saved && env) {
for (const [k, v] of Object.entries(saved)) {
if (v == null) delete env[k]
else env[k] = v
}
}
}
return
}
if (mode === '-s') {
const stdinText =
typeof ctx.shellStdin === 'string'
? ctx.shellStdin
: typeof ctx.shellStdin === 'object' &&
ctx.shellStdin &&
'data' in ctx.shellStdin
? String(/** @type {{ data?: string }} */ (ctx.shellStdin).data ?? '')
: ''
await runShScriptText(ctx, stdinText, { label: 'stdin' })
return
}
const script = mode
let buf
try {
buf = await ctx.vfs.readFile(script)
} catch (e) {
ctx.console.error('sh: ' + ((e && e.message) || String(e)))
ctx.exitCode = 1
return
}
if (buf == null) {
ctx.console.error('sh: ' + script + ': not found')
ctx.exitCode = 127
return
}
let text = ctx.b4a.toString(buf)
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1)
text = text.replace(/^\ufeff/, '')
if (text.startsWith('#!')) {
const nl = text.indexOf('\n')
text = nl === -1 ? '' : text.slice(nl + 1)
}
await runShScriptText(ctx, text, { label: script })
}
/**
* @param {Record<string, unknown>} ctx
* @param {string} text
* @param {{ label: string }} meta
*/
async function runShScriptText(ctx, text, meta) {
text = String(text || '').replace(/\\\r?\n/g, '')
const lines = text.split(/\r?\n/)
const blocks = []
let cur = ''
let depth = 0
for (let i = 0; i < lines.length; i++) {
const raw = lines[i]
const trimmed = raw.trim()
if (!trimmed || trimmed.startsWith('#')) continue
cur += (cur ? '\n' : '') + raw
const words = trimmed
.replace(/[;(){}]/g, ' ')
.split(/\s+/)
.filter(Boolean)
for (const w of words) {
if (w === 'if' || w === 'for' || w === 'while' || w === 'until' || w === 'case')
depth++
else if (w === 'fi' || w === 'done' || w === 'esac') depth = Math.max(0, depth - 1)
}
if (depth === 0) {
blocks.push(cur)
cur = ''
}
}
if (cur.trim()) blocks.push(cur)
let lineNo = 1
for (const block of blocks) {
const env = ctx.vfs?.env
if (env && typeof env === 'object') {
env.BARE_OS_SH_SCRIPT_LABEL = meta.label
env.BARE_OS_SH_SCRIPT_LINE = String(lineNo)
}
await ctx.execLine(block)
lineNo += block.split(/\r?\n/).length
if ((Number(ctx.exitCode) || 0) !== 0) return
}
ctx.exitCode = 0
}