Files
HyperionOS/Src/Hyperion-firmware-nc/data/boot/nc/boot.lua
T

692 lines
23 KiB
Lua

--:Minify:--
local hostScreen = screen
local hostChip = chip
local hostYield = coroutine.yield
local function throwError(msg)
local okS, sw = pcall(hostScreen.getSize)
if okS then
pcall(hostScreen.set, 170, 0, 0)
pcall(hostScreen.draw)
end
pcall(hostChip.crash, "Hyperion NC boot failure: " .. tostring(msg))
while true do hostYield() end
end
local ok, err = xpcall(function()
local apis = {}
local keep = {
coroutine = true, debug = true, _VERSION = true, assert = true,
error = true, getmetatable = true, ipairs = true, load = true,
math = true, next = true, pairs = true, pcall = true,
rawequal = true, rawget = true, rawlen = true, rawset = true,
select = true, setmetatable = true, string = true, table = true,
tonumber = true, tostring = true, type = true, xpcall = true,
utf8 = true, _G = true
}
local moveKeys = {}
for k in pairs(_G) do
if not keep[k] then moveKeys[#moveKeys + 1] = k end
end
for i = 1, #moveKeys do
local k = moveKeys[i]
apis[k] = _G[k]
_G[k] = nil
end
local fsChip = apis.chip
local fsEvent = apis.event
local fsFiles = apis.files
local fsScreen = apis.screen
if not fsChip or not fsEvent or not fsFiles or not fsScreen then
throwError("missing NeetComputers APIs (need screen/event/files/chip)")
end
local dbgSethook = debug.sethook
function sleep(t)
t = tonumber(t) or 0
if t <= 0 then coroutine.yield() return end
local target = fsChip.getUnixTime() + t
while fsChip.getUnixTime() < target do coroutine.yield() end
end
local bootUnix = fsChip.getUnixTime()
local function fmtDate(t)
t = tonumber(t) or 0
local days = math.floor(t / 86400)
local rem = math.floor(t - days * 86400)
if rem < 0 then rem = 0 end
local z = days + 719468
local era = math.floor(z / 146097)
local doe = z - era * 146097
local yoe = math.floor((doe - math.floor(doe / 1460)
+ math.floor(doe / 36524) - math.floor(doe / 146096)) / 365)
local y = yoe + era * 400
local doy = doe - (365 * yoe + math.floor(yoe / 4) - math.floor(yoe / 100))
local mp = math.floor((5 * doy + 2) / 153)
local d = doy - math.floor((153 * mp + 2) / 5) + 1
local m = mp + 3
if m > 12 then m = m - 12 end
if m <= 2 then y = y + 1 end
local hh = math.floor(rem / 3600)
local mi = math.floor((rem - hh * 3600) / 60)
local ss = rem - hh * 3600 - mi * 60
return string.format("%04d-%02d-%02dT%02d:%02d:%02dZ", y, m, d, hh, mi, ss)
end
local function normPartList(raw)
if type(raw) ~= "table" then return {} end
if type(raw[1]) == "table" and raw[1].name == nil and #raw == 1 then
raw = raw[1]
end
local out = {}
for _, p in ipairs(raw) do
local name = type(p) == "table" and p.name or p
if type(name) == "string" and name ~= "" then
out[#out + 1] = name
end
end
return out
end
local function diskSlots()
local out = {}
local okD, raw = pcall(fsFiles.getDisks)
if okD and type(raw) == "table" then
for _, d in ipairs(raw) do
local slot = type(d) == "table" and (d.slot or d[1]) or d
if type(slot) == "number" then out[#out + 1] = slot end
end
end
if #out == 0 then out = {0} end
table.sort(out)
return out
end
local function isBootPart(slot, part)
local okA, a = pcall(fsFiles.exists, part .. ":/kernel.lua", slot)
if not (okA and a) then return false end
local okB, b = pcall(fsFiles.exists, part .. ":/nc/boot.lua", slot)
return okB and b == true
end
local BOOT_DISK, BOOT_PART = nil, nil
local slots = diskSlots()
for _, slot in ipairs(slots) do
local okB, bp = pcall(fsFiles.getBootPath, slot)
if okB and type(bp) == "string" and bp ~= "" then
local part = bp:match("^([^:]+):")
if part and isBootPart(slot, part) then
BOOT_DISK, BOOT_PART = slot, part
break
end
end
end
if not BOOT_DISK then
local okB, bp = pcall(fsFiles.getBootPath)
if okB and type(bp) == "string" and bp ~= "" then
local part = bp:match("^([^:]+):")
if part then
for _, slot in ipairs(slots) do
if isBootPart(slot, part) then
BOOT_DISK, BOOT_PART = slot, part
break
end
end
end
end
end
if not BOOT_DISK then
for _, slot in ipairs(slots) do
local okP, raw = pcall(fsFiles.getPartitions, slot)
if okP then
for _, part in ipairs(normPartList(raw)) do
if isBootPart(slot, part) then
BOOT_DISK, BOOT_PART = slot, part
break
end
end
end
if BOOT_DISK then break end
end
end
if not BOOT_DISK then
throwError("no bootable Hyperion partition found")
end
local function getFile(path)
local okH, h = pcall(fsFiles.open, BOOT_PART .. ":" .. path, "r", BOOT_DISK)
if not okH or not h then
throwError("cannot open boot file: " .. path)
end
local okR, data = pcall(h.read, "a")
pcall(h.close)
if not okR or type(data) ~= "string" then
throwError("cannot read boot file: " .. path)
end
return data
end
local function readBootData(path)
local okH, h = pcall(fsFiles.open, BOOT_PART .. ":" .. path, "rb", BOOT_DISK)
if not okH or not h then return nil end
local okR, data = pcall(h.read, "a")
pcall(h.close)
if not okR or type(data) ~= "string" then return nil end
return data
end
local function parsePSF(data)
if not data or #data < 4 then return nil, "too short" end
local b1, b2 = data:byte(1, 2)
local glyphs, gw, gh = {}, 8, 0
if b1 == 0x36 and b2 == 0x04 then
local mode, size = data:byte(3, 4)
if not size or size == 0 then return nil, "bad PSF1 header" end
gh = size
local n = (mode % 4 >= 2) and 512 or 256
for i = 0, n - 1 do
local off = 4 + i * size
if off + size > #data then break end
glyphs[i] = data:sub(off + 1, off + size)
end
elseif b1 == 0x72 and b2 == 0xb5 then
local okU, headersize, flags, num, bpg, h, w =
pcall(string.unpack, "<I4I4I4I4I4I4I4", data, 5)
if not okU or not w or not h or w == 0 or h == 0 then
return nil, "bad PSF2 header"
end
gw, gh = w, h
for i = 0, num - 1 do
local off = headersize + i * bpg
if off + bpg > #data then break end
glyphs[i] = data:sub(off + 1, off + bpg)
end
else
return nil, "not a PSF file"
end
return {glyphs = glyphs, w = gw, h = gh, bpr = math.floor((gw + 7) / 8)}
end
local fontData = readBootData("/nc/font.psf")
if not fontData then throwError("missing /nc/font.psf on boot partition") end
local font = parsePSF(fontData)
fontData = nil
if not font then throwError("cannot parse /nc/font.psf") end
local okS, sw, sh = pcall(fsScreen.getSize)
if not okS or type(sw) ~= "number" then
throwError("screen has no usable display")
end
local SW, SH = sw, sh
local CW, CHH = font.w, font.h
local COLS = math.max(1, math.floor(SW / CW))
local ROWS = math.max(1, math.floor(SH / CHH))
local function split24(c)
c = math.floor(tonumber(c) or 0)
if c < 0 then c = 0 end
if c > 0xFFFFFF then c = 0xFFFFFF end
local r = math.floor(c / 65536)
local g = math.floor((c - r * 65536) / 256)
local b = c - r * 65536 - g * 256
return r, g, b
end
local glyphCache = {}
local function glyphBuffer(code, r, g, b)
local key = code * 16777216 + r * 65536 + g * 256 + b
local buf = glyphCache[key]
if buf then return buf end
local gl = font.glyphs[code] or font.glyphs[63]
local on = string.char(r, g, b, 255)
local off = string.char(0, 0, 0, 255)
local chunks = {}
local n = 0
for yy = 0, CHH - 1 do
for xx = 0, CW - 1 do
local byte = gl and gl:byte(yy * font.bpr + math.floor(xx / 8) + 1) or 0
n = n + 1
if (math.floor(byte / (2 ^ (7 - (xx % 8)))) % 2) == 1 then
chunks[n] = on
else
chunks[n] = off
end
end
end
buf = table.concat(chunks)
glyphCache[key] = buf
return buf
end
local function drawTextCell(px, py, code, fg)
local r, g, b = split24(fg)
local buf = glyphBuffer(code, r, g, b)
fsScreen.writeData(px, py, buf, CW)
end
local function fillCellBG(px, py, bg)
local r, g, b = split24(bg)
fsScreen.fill(px, py, px + CW - 1, py + CHH - 1, r, g, b, 255)
end
local function newTerm()
local t = {
cols = COLS, rows = ROWS,
cx = 1, cy = 1,
fg = 0xDBDBAA, bg = 0x000000,
cursor = true,
cells = {},
dirty = {},
lastCurX = nil, lastCurY = nil,
}
for y = 1, ROWS do
local row = {}
for x = 1, COLS do
row[x] = {ch = 32, fg = t.fg, bg = t.bg}
end
t.cells[y] = row
end
local function markRow(y)
t.dirty[y] = true
end
local function paintCell(x, y)
local cell = t.cells[y][x]
local px = (x - 1) * CW
local py = (y - 1) * CHH
fillCellBG(px, py, cell.bg)
if cell.ch ~= 32 then
drawTextCell(px, py, cell.ch, cell.fg)
end
end
local function hideCursor()
if t.lastCurX then
local x, y = t.lastCurX, t.lastCurY
t.lastCurX, t.lastCurY = nil, nil
if t.cells[y] and t.cells[y][x] then paintCell(x, y) end
end
end
local function scrollUp()
hideCursor()
if CHH < SH then
local data = fsScreen.readData(0, CHH, SW - 1, SH - 1)
fsScreen.writeData(0, 0, data, SW)
end
local top = table.remove(t.cells, 1)
for x = 1, COLS do
top[x].ch, top[x].fg, top[x].bg = 32, t.fg, t.bg
end
t.cells[ROWS] = top
local shifted = {}
for y in pairs(t.dirty) do
if y > 1 then shifted[y - 1] = true end
end
shifted[ROWS] = true
t.dirty = shifted
end
function t.present()
hideCursor()
for y in pairs(t.dirty) do
local row = t.cells[y]
if row then
for x = 1, COLS do paintCell(x, y) end
end
end
t.dirty = {}
if t.cursor then
local px = (t.cx - 1) * CW
local py = (t.cy - 1) * CHH
local r, g, b = split24(t.fg)
fsScreen.fill(px, py + CHH - 2, px + CW - 1, py + CHH - 1, r, g, b, 255)
t.lastCurX, t.lastCurY = t.cx, t.cy
end
fsScreen.draw()
end
function t.write(s)
hideCursor()
s = tostring(s)
for i = 1, #s do
local byte = s:byte(i)
if byte == 10 then
t.cx = 1
t.cy = t.cy + 1
elseif byte == 9 then
t.cx = t.cx + (4 - ((t.cx - 1) % 4))
elseif byte == 8 then
if t.cx > 1 then
t.cx = t.cx - 1
local cell = t.cells[t.cy][t.cx]
cell.ch, cell.fg, cell.bg = 32, t.fg, t.bg
markRow(t.cy)
end
else
if t.cx > COLS then
t.cx = 1
t.cy = t.cy + 1
end
if t.cy > ROWS then
scrollUp()
t.cy = ROWS
end
local cell = t.cells[t.cy][t.cx]
cell.ch, cell.fg, cell.bg = byte, t.fg, t.bg
markRow(t.cy)
t.cx = t.cx + 1
end
if t.cx > COLS + 1 then t.cx = COLS + 1 end
if t.cy > ROWS then
scrollUp()
t.cy = ROWS
end
end
t.present()
end
function t.clear()
for y = 1, ROWS do
local row = t.cells[y]
for x = 1, COLS do
row[x].ch, row[x].fg, row[x].bg = 32, t.fg, t.bg
end
end
t.dirty = {}
t.cx, t.cy = 1, 1
hideCursor()
local r, g, b = split24(t.bg)
fsScreen.fill(0, 0, SW - 1, SH - 1, r, g, b, 255)
t.present()
end
function t.getSize()
return t.cols, t.rows
end
function t.getCursor()
return t.cx, t.cy
end
function t.setCursor(x, y)
x, y = tonumber(x), tonumber(y)
if not x or not y then error("Invalid arg") end
if x < 1 then x = 1 end
if y < 1 then y = 1 end
if x > COLS then x = COLS end
if y > ROWS then y = ROWS end
hideCursor()
t.cx, t.cy = x, y
t.present()
end
function t.setFg(c) t.fg = math.floor(tonumber(c) or 0) end
function t.setBg(c) t.bg = math.floor(tonumber(c) or 0) end
function t.getFg() return t.fg end
function t.getBg() return t.bg end
function t.setCursorVisible(v)
t.cursor = v and true or false
t.present()
end
return t
end
local ncGfx = {
screenW = SW, screenH = SH,
cellW = CW, cellH = CHH,
cols = COLS, rows = ROWS,
newTerm = newTerm,
}
local con = newTerm()
con.setCursorVisible(false)
local function readBootFile(name)
local okH, h = pcall(fsFiles.open, BOOT_PART .. ":/nc/" .. name, "r", BOOT_DISK)
if not okH or not h then return "" end
local okR, data = pcall(h.read, "a")
pcall(h.close)
if not okR or type(data) ~= "string" then return "" end
return data
end
local function writeBootFile(name, text)
local okH, h = pcall(fsFiles.open, BOOT_PART .. ":/nc/" .. name, "w", BOOT_DISK)
if not okH or not h then return end
pcall(h.write, tostring(text))
pcall(h.flush)
pcall(h.close)
end
local eventQueue = {}
local function queueEvent(ev, ...)
if #eventQueue >= 512 then table.remove(eventQueue, 1) end
eventQueue[#eventQueue + 1] = {ev, ...}
end
local EFI = {
getEpochMs = function() return math.floor(fsChip.getUnixTime() * 1000) end,
getUptime = function() return math.floor((fsChip.getUnixTime() - bootUnix) * 1000) end,
date = function() return fmtDate(fsChip.getUnixTime()) end,
getMachineEvent = function()
if #eventQueue > 0 then
return table.unpack(table.remove(eventQueue, 1))
else
return nil
end
end,
getEEPROM = function() return readBootFile("eeprom.dat") end,
setEEPROM = function(_, text) writeBootFile("eeprom.dat", text) end,
getNvram = function() return readBootFile("nvram.dat") end,
setNvram = function(_, text) writeBootFile("nvram.dat", text) end,
beep = function() end,
architecture = "nc",
firmware = apis,
status = "running",
nc = ncGfx,
yield = function() coroutine.yield() end,
screenCtl = {
print = function(_, text) con.write(tostring(text) .. "\n") end,
printInline = function(_, text) con.write(tostring(text)) end,
clear = function() con.clear() end,
resetCursor = function() con.setCursor(1, 1) end,
setBackgroundColor = function(_, c) con.setBg(c) end,
setTextColor = function(_, c) con.setFg(c) end,
getBackgroundColor = function() return con.getBg() end,
getTextColor = function() return con.getFg() end,
enable = function() con.setCursorVisible(true) end,
disable = function() con.setCursorVisible(false) end,
},
}
local sliceInfo = setmetatable({}, {__mode = "k"})
function EFI.resumeWithTimeout(co, timeout, ...)
timeout = tonumber(timeout) or 0.05
local start = fsChip.getUnixTime()
local info = sliceInfo[co]
if info and info.result == "success" and (info.dur or 1) < 0.0002 then
local r = {coroutine.resume(co, ...)}
sliceInfo[co] = {result = (r[1] and "success" or "error"),
dur = fsChip.getUnixTime() - start}
if not r[1] then return "error", r[2] end
return "success", table.unpack(r, 2)
end
if not dbgSethook then
local r = {coroutine.resume(co, ...)}
sliceInfo[co] = {result = (r[1] and "success" or "error"),
dur = fsChip.getUnixTime() - start}
if not r[1] then return "error", r[2] end
return "success", table.unpack(r, 2)
end
local deadline = start + timeout
dbgSethook(co, function()
if coroutine.isyieldable() and fsChip.getUnixTime() >= deadline then
coroutine.yield("timeout")
end
end, "", 1000)
local ret = {coroutine.resume(co, ...)}
local stop = fsChip.getUnixTime()
if ret[1] and ret[2] == "timeout" then
sliceInfo[co] = {result = "timeout", dur = stop - start}
return "timeout"
elseif ret[1] == false then
sliceInfo[co] = {result = "error", dur = stop - start}
return "error", ret[2]
else
if dbgSethook then pcall(dbgSethook, co) end
sliceInfo[co] = {result = "success", dur = stop - start}
return "success", table.unpack(ret, 2)
end
end
local Kernel = load(getFile("/kernel.lua"), "@Kernel")
local initFsMod = load(getFile("/nc/initdisks"), "@Init_disks")
local initFs = load(getFile("/initfs"), "@InitFs")
if not Kernel then throwError("cannot parse kernel.lua") end
if not initFsMod then throwError("cannot parse nc/initdisks") end
if not initFs then throwError("cannot parse initfs") end
local disks = initFsMod(apis, BOOT_DISK, BOOT_PART)
local ifs = initFs()
local kernelCo = coroutine.create(function()
local okK, errK = xpcall(Kernel, debug.traceback, EFI)
EFI._kernelDone = true
if not okK then
EFI._kernelErr = errK
EFI.status = EFI.status == "reboot" and "reboot" or "error"
end
end)
EFI.initfs = ifs
EFI.disks = disks
local startTime = fsChip.getUnixTime()
EFI.screenCtl:print("HyperionOS/NC booted from " .. tostring(BOOT_DISK)
.. ":" .. BOOT_PART .. " in "
.. string.format("%.2f", startTime - bootUnix) .. "s")
local function pump()
local okU, q = pcall(fsEvent.getQueue, "User")
if okU and type(q) == "table" then
for i = 1, #q do
local e = q[i]
if type(e) == "table" then
local kind = e[1]
if kind == "keyPressed" then
local code, letter, mods = e[2], e[3], e[4]
queueEvent("keyPressed", 1, code, letter, mods)
if type(letter) == "string" and letter ~= "" then
queueEvent("keyTyped", 1, letter)
end
elseif kind == "keyReleased" then
queueEvent("keyReleased", 1, e[2], e[3], e[4])
elseif kind == "mouseClicked" or kind == "mouseReleased"
or kind == "mouseDragged" or kind == "mouseMoved"
or kind == "mouseScrolled" then
queueEvent(table.unpack(e))
else
queueEvent(table.unpack(e))
end
end
end
end
for _, label in ipairs({"System", "Network", "Peripheral",
"Compatibility", "Unlabeled"}) do
local okQ, qq = pcall(fsEvent.getQueue, label)
if okQ and type(qq) == "table" then
for i = 1, #qq do
local e = qq[i]
if type(e) == "table" then
queueEvent(table.unpack(e))
end
end
end
end
end
local function waitKey()
while true do
pump()
for i = 1, #eventQueue do
local e = eventQueue[i]
if e[1] == "keyPressed" or e[1] == "keyTyped" then
eventQueue = {}
return
end
end
eventQueue = {}
coroutine.yield()
end
end
while true do
pump()
local okR, errR = coroutine.resume(kernelCo)
if not okR then
con.setFg(0xFF0000)
con.write("Hyperion kernel fault:\n" .. tostring(errR)
.. "\nPress any key to shut down.")
con.setFg(0xDBDBAA)
waitKey()
fsChip.shutdown()
return
end
if coroutine.status(kernelCo) == "dead" then
if EFI.status == "reboot" then
fsChip.reboot()
else
if EFI._kernelErr then
con.setFg(0xFF0000)
con.write("Hyperion kernel error:\n"
.. tostring(EFI._kernelErr)
.. "\nPress any key to shut down.")
con.setFg(0xDBDBAA)
waitKey()
end
fsChip.shutdown()
end
return
end
coroutine.yield()
end
end, debug.traceback)
if not ok then
throwError(err)
end