The 1.2.5 update #29

Merged
Astronand merged 2 commits from 1.2-dev into main 2026-11-04 14:22:52 -05:00
89 changed files with 3882 additions and 490 deletions
Showing only changes of commit ef4b856ee6 - Show all commits

No files matched your search

@@ -149,7 +149,7 @@ local function creategfx(term, id)
term.setPixel(x,y,aprox(c))
end,
gpixel=function(x,y)
return term.getPixel()
return term.getPixel(x,y)
end,
drawFB=function(x,y,fb,w)
local f=splitFramebufferToStrings(fb,w)
@@ -0,0 +1 @@
Hyperion-firmware-cct
@@ -0,0 +1,2 @@
--:Minify:--
local kernel=...
@@ -78,15 +78,24 @@ for addr, typ in kernel.oc.component.list("keyboard") do
elseif op=="open" then
local h = {
read=function(amount)
amount = amount or 1
local rv=""
for i=1, amount or 1 do
for i=1, amount do
local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then
rv=rv..event[1]
else
break
end
end
if rv=="" then rv=nil end
return rv
if rv~="" then return rv end
local task=kernel.currentTask
task.status="D"
task.io=function()
local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then return event[1] end
end
return nil
end,
write=function(content)
end,
@@ -249,9 +249,14 @@ kernel.devfs.data["input"]["keyboard1"] = function(op, mode)
rv=rv..event[1]
end
end
---@diagnostic disable-next-line: cast-local-type
if rv=="" then rv=nil end
return rv
if rv~="" then return rv end
local task=kernel.currentTask
task.status="D"
task.io=function()
local event = {fifo.pop()}
if event[1] then return event[1] end
end
return nil
end,
gctrl=function()
return serializeBool(kernel.cct.ctrl)..";"..serializeBool(kernel.cct.alt)
+2
View File
@@ -0,0 +1,2 @@
Hyperion
Spsf
@@ -0,0 +1,691 @@
--: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
@@ -0,0 +1,2 @@
return true
Binary file not shown.
@@ -0,0 +1,318 @@
--:Minify:--
-- HyperionOS NeetComputers initdisks.
-- Adapts the NeetComputers files API (disks x partitions) to the Hyperion
-- disk interface documented in docs/kernel/bootloaders/diskAPI.
--
-- Addresses look like "0:hyperion" (disk slot + partition name); the boot
-- partition is additionally aliased as "$".
--
-- NeetComputers file headers are snapshots: reads see the file as it was at
-- open time and writes only persist on flush/close (and always append). This
-- adapter keeps a Lua-side buffer per open handle so that read/seek/write
-- behave like regular POSIX files. Flush rewrites the whole file.
local args = {...}
local apis = args[1]
local bootDisk = args[2]
local bootPart = args[3]
local files = apis.files
local function fp(part, path)
if not path or path == "" then path = "/" end
if path:sub(1, 1) ~= "/" then path = "/" .. path end
return part .. ":" .. path
end
local function normParts(raw)
if type(raw) ~= "table" then return {} end
-- tolerate a doubly-wrapped list
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 ok, raw = pcall(files.getDisks)
if ok 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 partReadOnly(slot, part)
local ok, info = pcall(files.getPartition, part, slot)
if ok and type(info) == "table" then
return info.readonly == true
end
return false
end
local function createDisk(id, slot, part)
local readonly = partReadOnly(slot, part)
local disk = {
address = id,
isReadOnly = function() return readonly end
}
function disk:spaceUsed() return 0 end
function disk:spaceTotal() return 2 ^ 40 end
function disk:list(path)
local ok, r = pcall(files.getChildren, fp(part, path), slot)
if not ok or type(r) ~= "table" then return nil, "not directory" end
local out = {}
for _, n in ipairs(r) do
if type(n) == "string" then out[#out + 1] = n end
end
return out
end
function disk:fileExists(path)
local ok, r = pcall(files.exists, fp(part, path), slot)
if not (ok and r) then return false end
local ok2, d = pcall(files.isDir, fp(part, path), slot)
if ok2 and d then return false end
return true
end
function disk:directoryExists(path)
if not path or path == "" or path == "/" then return true end
local ok, r = pcall(files.isDir, fp(part, path), slot)
return ok and r == true
end
function disk:type(path)
local ok, r = pcall(files.exists, fp(part, path), slot)
if not (ok and r) then return nil end
local ok2, d = pcall(files.isDir, fp(part, path), slot)
if ok2 and d then return "directory" end
return "file"
end
function disk:makeDirectory(path)
local ok, r = pcall(files.makeDir, fp(part, path), slot)
if not ok then return nil, "cannot create directory" end
if r == false then return nil, "cannot create directory" end
return true
end
function disk:remove(path)
local ok, r = pcall(files.delete, fp(part, path), slot)
if not ok then return nil, "cannot delete" end
if r == false then return nil, "cannot delete" end
return true
end
function disk:setLabel(label) return true end
function disk:getLabel() return part end
function disk:attributes(path)
local isDir = self:directoryExists(path)
local size = 0
if not isDir then
local ok, h = pcall(files.open, fp(part, path), "r", slot)
if ok and h then
local ok2, data = pcall(h.read, "a")
pcall(h.close)
if ok2 and type(data) == "string" then size = #data end
end
end
return {
size = size,
isDir = isDir,
isReadOnly = readonly,
modified = 0,
created = 0
}
end
function disk:open(path, mode)
mode = mode or "r"
local wantWrite = mode ~= "r" and mode ~= "rb"
-- Snapshot the current content with a dedicated read handle.
-- ("a"/"ab" headers are not readable themselves, and every header
-- only appends, so all POSIX read/write/seek behavior below runs
-- on this Lua-side buffer; persist() rewrites the file on flush.)
local buf = ""
if mode ~= "w" and mode ~= "wb" then
local okR, hr = pcall(files.open, fp(part, path), "r", slot)
if okR and hr then
local okD, data = pcall(hr.read, "a")
pcall(hr.close)
if okD and type(data) == "string" then buf = data end
end
end
local ok, h = pcall(files.open, fp(part, path), mode, slot)
if not ok or not h then
return nil, "file not found or access denied"
end
-- The live header is only needed to prove the open mode is valid
-- (existence/creation); persist() reopens the file itself.
pcall(h.close)
local pos = 1
if mode == "w" or mode == "wb" then
buf = ""
else
pos = #buf + 1
if mode == "r" or mode == "rb" or mode == "r+" or mode == "rb+"
or mode == "r+b" or mode == "w+" or mode == "wb+"
or mode == "w+b" then
pos = 1
end
end
local closed = false
local handle = {}
function handle.read(n)
if closed then error("EBADF") end
if type(n) == "number" then
if n <= 0 then return nil end
if pos > #buf then return nil end
local chunk = buf:sub(pos, pos + n - 1)
pos = pos + #chunk
if chunk == "" then return nil end
return chunk
end
local fmt = n or "l"
if pos > #buf then return nil end
if fmt == "a" then
local chunk = buf:sub(pos)
pos = #buf + 1
return chunk
elseif fmt == "l" or fmt == "L" then
local s, e = buf:find("\n", pos, true)
if not s then
local chunk = buf:sub(pos)
pos = #buf + 1
return chunk
end
local chunk
if fmt == "l" then chunk = buf:sub(pos, s - 1)
else chunk = buf:sub(pos, s) end
pos = s + 1
return chunk
else
error("EINVAL")
end
end
function handle.readAll()
if closed then error("EBADF") end
local chunk = buf:sub(pos)
pos = #buf + 1
return chunk
end
function handle.write(data)
if closed then error("EBADF") end
if not wantWrite then error("EACCES") end
data = tostring(data)
local before = buf:sub(1, pos - 1)
local after = buf:sub(pos + #data)
buf = before .. data .. after
pos = pos + #data
return true
end
function handle.seek(whence, offset)
if closed then error("EBADF") end
whence = whence or "cur"
offset = offset or 0
local base
if whence == "set" then base = 1
elseif whence == "cur" then base = pos
elseif whence == "end" then base = #buf + 1
else error("EINVAL") end
local np = base + offset
if whence == "end" and offset > 0 then error("EINVAL") end
if np < 1 then error("EINVAL") end
if np > #buf + 1 then error("EINVAL") end
pos = np
return pos - 1
end
local function persist()
if not wantWrite then return true end
local ok2, h2 = pcall(files.open, fp(part, path), "w", slot)
if not ok2 or not h2 then return nil, "flush failed" end
if #buf > 0 then
local ok3, err = pcall(h2.write, buf)
if not ok3 then pcall(h2.close) return nil, err end
end
local ok4, err = pcall(h2.flush)
pcall(h2.close)
if not ok4 then return nil, err end
return true
end
function handle.flush()
if closed then error("EBADF") end
local ok2, err = persist()
if not ok2 then error(err or "EIO") end
return true
end
function handle.close()
if closed then return true end
closed = true
if wantWrite then pcall(persist) end
buf = ""
return true
end
return handle
end
return disk
end
local internal = {}
local disks = {}
internal["$"] = createDisk("$", bootDisk, bootPart)
local function refresh()
disks = {}
for _, slot in ipairs(diskSlots()) do
local ok, raw = pcall(files.getPartitions, slot)
if ok and type(raw) == "table" then
for _, part in ipairs(normParts(raw)) do
if not (slot == bootDisk and part == bootPart) then
local addr = tostring(slot) .. ":" .. part
disks[addr] = createDisk(addr, slot, part)
end
end
end
end
end
local function iter()
refresh()
local combined = {}
for id, obj in pairs(internal) do combined[id] = obj end
for id, obj in pairs(disks) do combined[id] = obj end
return pairs(combined)
end
return {refresh = refresh, list = iter}
@@ -0,0 +1,11 @@
--:Minify:--
local kernel=...
if kernel.arch~="nc" then
kernel.deny("neetcomputers/01_devices.kmod")
kernel.deny("neetcomputers/13_devraw.kmod")
kernel.deny("neetcomputers/22_http.kmod")
kernel.deny("neetcomputers/25_tty.kmod")
kernel.deny("neetcomputers/26_keyboards.kmod")
kernel.deny("neetcomputers/30_daemon.kmod")
kernel.deny("neetcomputers/36_scheduler.kmod")
end
@@ -0,0 +1,19 @@
--:Minify:--
local kernel=...
kernel.nc={}
kernel.nc.io=kernel.apis.io
kernel.nc.chip=kernel.apis.chip
kernel.nc.event=kernel.apis.event
kernel.nc.files=kernel.apis.files
kernel.log("Installed peripherals:")
local ok, peripherals = pcall(kernel.nc.io.getPeripherals)
if ok and type(peripherals)=="table" then
for _, id in ipairs(peripherals) do
local okT, typ = pcall(kernel.nc.io.getType, id)
if not okT then typ = "unknown" end
kernel.log(" "..tostring(id).." : "..tostring(typ))
end
else
kernel.log(" (none)")
end
@@ -0,0 +1,28 @@
--:Minify:--
local kernel=...
local io=kernel.nc.io
local function wrap(id)
return function(op, mode)
if op=="type" then
return "device"
elseif op=="open" then
if kernel.uid~=0 then error("EACCES") end
return io.wrapPeripheral(id)
end
end
end
local ok, peripherals = pcall(io.getPeripherals)
if ok and type(peripherals)=="table" then
for _, id in ipairs(peripherals) do
local obj=wrap(id)
kernel.devfs.data["raw"][tostring(id)]=obj
local okT, typ = pcall(io.getType, id)
typ = (okT and type(typ)=="string") and typ or "unknown"
local typefolder=kernel.devfs.data["raw"]["by-type"][typ]
if not typefolder then typefolder={} end
typefolder[tostring(#table.keys(typefolder)+1)] = obj
kernel.devfs.data["raw"]["by-type"][typ]=typefolder
end
end
Whitespace-only changes.
@@ -0,0 +1,133 @@
--:Minify:--
-- NeetComputers TTY driver: a cell-buffered text terminal rendered through
-- the bootloader's shared framebuffer interface (EFI.nc.newTerm).
local kernel = ...
local ncgfx = kernel.EFI.nc
if not ncgfx or not ncgfx.newTerm then
kernel.panic("neetcomputers/25_tty.kmod: EFI.nc framebuffer missing")
end
local term = ncgfx.newTerm()
-- Interactive programs (hysh, lua REPL, micro) draw their own inverted
-- block cursor; the terminal's hardware underline would sit next to it
-- as a stray extra cursor, so keep it off.
term.setCursorVisible(false)
kernel.nc.term = term
kernel.log("initialized nc framebuffer tty "
.. tostring(ncgfx.screenW) .. "x" .. tostring(ncgfx.screenH)
.. " (" .. tostring(term.cols) .. "x" .. tostring(term.rows) .. " chars)")
kernel.devfs.data["tty"]["1"] = function(op, mode)
if op == "type" then
return "Terminal"
elseif op == "open" then
local h = {
read = function(amount) end,
write = function(content)
term.write(tostring(content))
end,
size = function()
return term.getSize()
end,
clear = function()
term.clear()
end,
gpos = function()
return term.getCursor()
end,
spos = function(x, y)
if not tonumber(x) or not tonumber(y) then error("Invailid arg") end
term.setCursor(x, y)
end,
sfgc = function(c)
term.setFg(c)
end,
sbgc = function(c)
term.setBg(c)
end,
gfgc = function()
return term.getFg()
end,
gbgc = function()
return term.getBg()
end,
isvirt = function()
return false
end,
gplt = function()
return {
0x000000, 0x000040, 0x000080, 0x0000C0, 0x0000FF,
0x002400, 0x002440, 0x002480, 0x0024C0, 0x0024FF,
0x004900, 0x004940, 0x004980, 0x0049C0, 0x0049FF,
0x006D00, 0x006D40, 0x006D80, 0x006DC0, 0x006DFF,
0x009200, 0x009240, 0x009280, 0x0092C0, 0x0092FF,
0x00B600, 0x00B640, 0x00B680, 0x00B6C0, 0x00B6FF,
0x00DB00, 0x00DB40, 0x00DB80, 0x00DBC0, 0x00DBFF,
0x00FF00, 0x00FF40, 0x00FF80, 0x00FFC0, 0x00FFFF,
0x330000, 0x330040, 0x330080, 0x3300C0, 0x3300FF,
0x332400, 0x332440, 0x332480, 0x3324C0, 0x3324FF,
0x334900, 0x334940, 0x334980, 0x3349C0, 0x3349FF,
0x336D00, 0x336D40, 0x336D80, 0x336DC0, 0x336DFF,
0x339200, 0x339240, 0x339280, 0x3392C0, 0x3392FF,
0x33B600, 0x33B640, 0x33B680, 0x33B6C0, 0x33B6FF,
0x33DB00, 0x33DB40, 0x33DB80, 0x33DBC0, 0x33DBFF,
0x33FF00, 0x33FF40, 0x33FF80, 0x33FFC0, 0x33FFFF,
0x660000, 0x660040, 0x660080, 0x6600C0, 0x6600FF,
0x662400, 0x662440, 0x662480, 0x6624C0, 0x6624FF,
0x664900, 0x664940, 0x664980, 0x6649C0, 0x6649FF,
0x666D00, 0x666D40, 0x666D80, 0x666DC0, 0x666DFF,
0x669200, 0x669240, 0x669280, 0x6692C0, 0x6692FF,
0x66B600, 0x66B640, 0x66B680, 0x66B6C0, 0x66B6FF,
0x66DB00, 0x66DB40, 0x66DB80, 0x66DBC0, 0x66DBFF,
0x66FF00, 0x66FF40, 0x66FF80, 0x66FFC0, 0x66FFFF,
0x990000, 0x990040, 0x990080, 0x9900C0, 0x9900FF,
0x992400, 0x992440, 0x992480, 0x9924C0, 0x9924FF,
0x994900, 0x994940, 0x994980, 0x9949C0, 0x9949FF,
0x996D00, 0x996D40, 0x996D80, 0x996DC0, 0x996DFF,
0x999200, 0x999240, 0x999280, 0x9992C0, 0x9992FF,
0x99B600, 0x99B640, 0x99B680, 0x99B6C0, 0x99B6FF,
0x99DB00, 0x99DB40, 0x99DB80, 0x99DBC0, 0x99DBFF,
0x99FF00, 0x99FF40, 0x99FF80, 0x99FFC0, 0x99FFFF,
0xCC0000, 0xCC0040, 0xCC0080, 0xCC00C0, 0xCC00FF,
0xCC2400, 0xCC2440, 0xCC2480, 0xCC24C0, 0xCC24FF,
0xCC4900, 0xCC4940, 0xCC4980, 0xCC49C0, 0xCC49FF,
0xCC6D00, 0xCC6D40, 0xCC6D80, 0xCC6DC0, 0xCC6DFF,
0xCC9200, 0xCC9240, 0xCC9280, 0xCC92C0, 0xCC92FF,
0xCCB600, 0xCCB640, 0xCCB680, 0xCCB6C0, 0xCCB6FF,
0xCCDB00, 0xCCDB40, 0xCCDB80, 0xCCDBC0, 0xCCDBFF,
0xCCFF00, 0xCCFF40, 0xCCFF80, 0xCCFFC0, 0xCCFFFF,
0xFF0000, 0xFF0040, 0xFF0080, 0xFF00C0, 0xFF00FF,
0xFF2400, 0xFF2440, 0xFF2480, 0xFF24C0, 0xFF24FF,
0xFF4900, 0xFF4940, 0xFF4980, 0xFF49C0, 0xFF49FF,
0xFF6D00, 0xFF6D40, 0xFF6D80, 0xFF6DC0, 0xFF6DFF,
0xFF9200, 0xFF9240, 0xFF9280, 0xFF92C0, 0xFF92FF,
0xFFB600, 0xFFB640, 0xFFB680, 0xFFB6C0, 0xFFB6FF,
0xFFDB00, 0xFFDB40, 0xFFDB80, 0xFFDBC0, 0xFFDBFF,
0xFFFF00, 0xFFFF40, 0xFFFF80, 0xFFFFC0, 0xFFFFFF,
0x000000, 0x0F0F0F, 0x1E1E1E, 0x2D2D2D,
0x3C3C3C, 0x4B4B4B, 0x5A5A5A, 0x696969,
0x787878, 0x878787, 0x969696, 0xA5A5A5,
0xB4B4B4, 0xC3C3C3, 0xD2D2D2, 0xE1E1E1
}
end,
gfx = function()
return false
end
}
if mode == "rw" then
return h
elseif mode == "r" then
h["write"] = nil
return h
elseif mode == "w" then
h["read"] = nil
return h
end
end
end
@@ -0,0 +1,129 @@
--:Minify:--
-- NeetComputers keyboard driver. The bootloader delivers User-queue key
-- events as ("keyPressed", 1, code, letter, mods) /
-- ("keyTyped", 1, letter) / ("keyReleased", 1, code, ...); the ncdaemon
-- task (30_daemon.kmod) feeds the fifo below.
local kernel=...
kernel.nc.keyboards={}
local kbs=kernel.nc.keyboards
local keyboard = {}
-- NeetComputers key codes: printable keys are ASCII, the rest follows the
-- emulator/mod keybind tables (Return=13, arrows 128-131, ...).
keyboard.keys = {
back = 8,
delete = 127,
down = 131,
enter = 13,
home = 158,
lcontrol = 132,
left = 128,
lmenu = 133,
lshift = 14,
pageDown = 161,
pageUp = 160,
rcontrol = 132,
right = 129,
rmenu = 133,
rshift = 14,
space = 32,
tab = 9,
up = 130,
["end"] = 159,
numpadenter = 13,
}
kernel.nc.keys=keyboard.keys
for i=0, 255 do
kernel.nc.keys[string.char(i)]=i
end
-------------------------------------------------------------------------------
function keyboard.isAltDown(addr)
return kbs[addr] and kbs[addr].alt or false
end
function keyboard.isControl(char)
return type(char) == "number" and (char < 0x20 or (char >= 0x7F and char <= 0x9F))
end
function keyboard.isControlDown(addr)
return kbs[addr] and kbs[addr].ctrl or false
end
function keyboard.isKeyDown(addr,charOrCode)
if not kbs[addr] then return false end
if type(charOrCode) == "string" then
return kbs[addr].pressedChars[utf8 and utf8.codepoint(charOrCode) or charOrCode:byte()]
elseif type(charOrCode) == "number" then
return kbs[addr].pressedCodes[charOrCode]
end
end
function keyboard.isShiftDown(addr)
return kbs[addr] and kbs[addr].shift or false
end
kernel.nc.keyboard=keyboard
local function serializeBool(bool)
if bool then
return "T"
else
return "F"
end
end
kbs["1"]={pressedChars={}, pressedCodes={}, events=kernel.newFifo(),
ctrl=false, alt=false, shift=false}
kernel.devfs.data["input"]["keyboard1"]=function(op,mode)
if op=="type" then
return "Keyboard"
elseif op=="open" then
local fifo=kernel.nc.keyboards["1"].events
local h = {
read=function(amount)
amount = amount or 1
-- Drain whatever is already queued first.
local rv=""
for i=1, amount do
local event = {fifo.pop()}
if event[1] then
rv=rv..event[1]
else
break
end
end
if rv~="" then return rv end
-- Nothing queued: block the task until the ncdaemon
-- feeds input instead of busy-spinning syscalls.
local task=kernel.currentTask
task.status="D"
task.io=function()
local event = {fifo.pop()}
if event[1] then return event[1] end
end
return nil
end,
write=function(content)
end,
gctrl=function()
local kb=kernel.nc.keyboards["1"]
return serializeBool(kb.ctrl)..";"..serializeBool(kb.alt)
end,
isKeyDown=function(char)
return keyboard.isKeyDown("1",char)
end
}
if mode=="rw" then
return h
elseif mode=="r" then
h["write"]=nil
return h
elseif mode=="w" then
h["read"]=nil
return h
end
end
end
@@ -0,0 +1,106 @@
--:Minify:--
-- NeetComputers input daemon. Consumes kernel machine events produced by
-- the bootloader event pump and feeds /dev/input/keyboard1. Ctrl+C sends
-- SIGINT to all tasks, mirroring the OC/CCT daemons.
local kernel=...
local NCTRACEBACK = debug.traceback
local keys=kernel.nc.keys
kernel.nc.eventhooks=kernel.nc.eventhooks or {}
kernel.processes.ncdaemon = function()
local timeout = false
kernel.log("NC daemon started")
local function isCtrl(mods) return (math.floor((tonumber(mods) or 0) / 2) % 2) == 1 end
local specialKeyMap = {
[keys.up] = "\27[A",
[keys.down] = "\27[B",
[keys.right] = "\27[C",
[keys.left] = "\27[D",
[keys.home] = "\27[H",
[keys["end"]] = "\27[F",
[keys.pageUp] = "\27[5~",
[keys.pageDown] = "\27[6~",
[keys.delete] = "\27[3~",
[keys.enter] = "\n",
[keys.back] = "\b",
[keys.tab] = "\t",
}
while true do
local event = {kernel.EFI.getMachineEvent()}
if event[1] then
local eventType = event[1]
local kb = kernel.nc.keyboards["1"]
if eventType == "keyPressed" then
local code, letter, mods = event[3], event[4], event[5]
kb.pressedCodes[code] = true
if type(letter) == "string" and #letter == 1 then
kb.pressedChars[letter:byte()] = true
end
if isCtrl(mods) then
kb.ctrl = true
local ch = nil
if type(letter) == "string" and #letter == 1 then
ch = letter:lower():byte()
elseif type(code) == "number" and code >= 64 and code <= 95 then
ch = code
end
if ch and ch >= 97 and ch <= 122 then
local byte = ch - 96
if byte == 3 then
for _, task in ipairs(syscall.getTasks()) do
syscall.sigsend(task, 1)
end
else
kb.events.push(string.char(byte))
end
end
else
local special = specialKeyMap[code]
if special then
kb.events.push(special)
end
end
elseif eventType == "keyReleased" then
local code = event[3]
kb.pressedCodes[code] = nil
if type(event[4]) == "string" and #event[4] == 1 then
kb.pressedChars[event[4]:byte()] = nil
end
if not isCtrl(event[5]) then kb.ctrl = false end
elseif eventType == "keyTyped" then
if event[3] then kb.events.push(event[3]) end
else
if kernel.nc.eventhooks[eventType] then
local ok,err = xpcall(kernel.nc.eventhooks[eventType], NCTRACEBACK, table.unpack(event))
if not ok then
kernel.log("Error on eventhook "..eventType.."\n"..err)
end
end
end
timeout = false
else
timeout = true
end
if timeout then
sleep(0.05)
end
end
end
kernel.log("NC daemon queued for execution")
@@ -0,0 +1,187 @@
--:Minify:--
-- NeetComputers scheduler (adaptive timeslice + optional preemption
-- via EFI.resumeWithTimeout; same design as the CCT/OC schedulers).
local kernel=...
-- Cache the real traceback: 48_dbg replaces _G.debug with a restricted
-- table, and re-reading the global in this hot loop flakes on YSLua.
local NCTRACEBACK = debug.traceback
local alpha = 0.85
local C_target = 0.01
local Tmin = 0.0005
local Tmax = 0.5
local lambda_budget = 0.08
local lambda_clamp = 0.03
local lambda_var = 0.02
local k_min = 0.5
local k_max = 0.5
local B = 0.01
function kernel.main()
kernel.log("Starting main loop...")
kernel.saveLog()
local stopLog=5
local logTasks=100
-- Host-tick budget: the bootloader resumes the kernel once per host
-- frame and every EFI:yield ends that resume, so one syscall-step per
-- frame makes interactive use crawl (roughly a frame per syscall).
-- Run a bounded burst of passes per frame instead: a burst where no
-- task ran means everything is parked, so yield at once. The step cap
-- plus preemption keep a runaway task from tripping the host watchdog.
local burstSteps = 0
local maxBurstSteps = 64
while not kernel.exitMain do
if kernel.config.logTasks then
if logTasks<0 then
kernel.log("Active Tasks:")
for i,v in pairs(kernel.tasks) do
kernel.log(v.name.." : "..v.status.." : "..tostring(v.pid).." : "..tostring(v.exit))
end
kernel.log("[END BLOCK]")
logTasks=100
end
logTasks=logTasks-1
end
local N = 0
local Tmin_hit = 0
local Tmax_hit = 0
local totalTaskTime = 0
local taskTimes = {}
for id,hook in ipairs(kernel.mainHooks) do
local ok,err = xpcall(hook, NCTRACEBACK)
if not ok then
kernel.log("[MAIN HOOK ERR]: "..err, "ERROR", 0xFF0000)
kernel.mainHooks[id]=nil
end
end
for pid, task in pairs(kernel.tasks) do
if kernel.exitMain then break end
for _,list in ipairs(kernel.perTaskHooks) do
for id,hook in ipairs(list) do
local ok,err = xpcall(hook, NCTRACEBACK, task, pid)
if not ok then
kernel.log("[TASK HOOK ERR]: "..err, "ERROR", 0xFF0000)
list[id]=nil
end
end
end
if task.status == "R" then
N = N + 1
task.timeSlice = math.min(Tmax, math.max(Tmin, B / (N ^ alpha)))
if task.status == "R" then
local startTime = kernel.EFI:getEpochMs()
local ret
if stopLog > 0 then
kernel.log("Running task " .. tostring(task.pid) .. " (" .. task.name .. ") with time slice " .. string.format("%.3f", task.timeSlice) .. "s", "DBUG", 0x00FFFF)
end
if kernel.config.preempt then
if not task.debugger then
ret = { kernel.EFI.resumeWithTimeout(task.coro, task.timeSlice, table.unpack(task.syscallReturn)) }
else
ret = { coroutine.resume(task.coro, table.unpack(task.syscallReturn)) }
end
else
ret = { coroutine.resume(task.coro, table.unpack(task.syscallReturn)) }
end
local elapsed = kernel.EFI:getEpochMs() - startTime
task.lastTime = elapsed
task.totalTime = (task.totalTime or 0) + elapsed
task.numRuns = (task.numRuns or 0) + 1
taskTimes[#taskTimes+1] = elapsed
totalTaskTime = totalTaskTime + elapsed
if elapsed <= Tmin then Tmin_hit = Tmin_hit + 1 end
if elapsed >= Tmax then Tmax_hit = Tmax_hit + 1 end
if ret[1] == "error" or ret[1] == false then
kernel.log("processHandlerException: " .. tostring(ret[2]), "ERROR", 0xFF0000)
task.status = "Z"
task.exit = "processHandlerException: " .. tostring(ret[2])
elseif ret[1] == "timeout" then
task.ivs = task.ivs + 1
task.syscallReturn = {}
elseif ret[1] == "success" or ret[1] == true then
task.vs = task.vs + 1
if ret[2] == "syscall" then
local scname = ret[3]
if kernel.syscalls[scname] then
if kernel.config.debugSyscalls then
kernel.log("Task " .. task.pid .. " syscall: " .. scname, "DBUG", 0x00FFFF)
for i = 4, #ret do
kernel.log(" inval[" .. (i-3) .. "] = " .. tostring(ret[i]), "DBUG", 0x00FFFF)
end
end
local sysret = { xpcall(kernel.syscalls[scname], NCTRACEBACK, table.unpack(ret, 4)) }
if kernel.config.debugSyscalls then
if not sysret[1] then
kernel.log("Task " .. task.pid .. " syscall " .. scname .. " failed: " .. tostring(sysret[2]), "ERROR", 0xFF0000)
else
kernel.log("Task " .. task.pid .. " syscall " .. scname .. " ok, " .. (#sysret-1) .. " retvals", "DBUG", 0x00FFFF)
for i = 2, #sysret do
local v = type(sysret[i]) == "table" and table.serialize(sysret[i]) or tostring(sysret[i])
kernel.log(" retval[" .. (i-1) .. "] = " .. v, "DBUG", 0x00FFFF)
end
end
end
if not sysret[1] then
task.syscallReturn = { false, sysret[2] }
else
task.syscallReturn = { true, table.unpack(sysret, 2) }
end
else
task.syscallReturn = { false, "Unknown syscall: " .. tostring(scname) }
end
end
end
end
end
-- No yield per task anymore: passes run back-to-back in one
-- host tick (see burst budget below). Yielding here cost a
-- full frame per task-step.
end
burstSteps = burstSteps + N
if N == 0 or burstSteps >= maxBurstSteps then
burstSteps = 0
-- Yield to the host once per burst (even when no task ran):
-- without this an idle system spins without voluntary yields
-- and trips the host watchdog.
kernel.EFI:yield()
end
local T_prev_avg = (N > 0) and (totalTaskTime / N) or 0
local T_prev_var = 0
for _, t in ipairs(taskTimes) do
T_prev_var = T_prev_var + (t - T_prev_avg) ^ 2
end
if N > 0 then T_prev_var = T_prev_var / N end
if N > 0 then
local f_clamp = k_min * (Tmin_hit / N) - k_max * (Tmax_hit / N)
local B_budget = (C_target * (N ^ (alpha - 1))) / math.max(T_prev_avg, 1e-8)
B = B + lambda_budget * (B_budget - B) + lambda_clamp * f_clamp - lambda_var * T_prev_var
end
kernel.hpv.reapDeadTasks()
if stopLog > 0 then
kernel.log("Executed " .. N .. " tasks, avg time: " .. string.format("%.2f", T_prev_avg) .. "ms, var: " .. string.format("%.2f", T_prev_var) .. ", B: " .. string.format("%.5f", B))
stopLog = stopLog - 1
kernel.saveLog()
end
end
kernel.log("Exited main")
kernel.saveLog()
end
+1
View File
@@ -0,0 +1 @@
firmware for NeetComputers
+1
View File
@@ -0,0 +1 @@
1.0.0
+1
View File
@@ -1,3 +1,4 @@
Hyperion
Astronand
Xtimhedae
Spsf
+101 -18
View File
@@ -1,41 +1,73 @@
local args = {...}
local apis = args[1]
local bootdrive = args[2]
local bootaddr = args[3]
local disks = {}
local internal = {}
local function normalize(path)
if type(path) ~= "string" then
return path
end
-- Preserve root directory.
if path == "/" then
return "/"
end
-- Remove trailing slashes.
path = path:gsub("/+$", "")
return path == "" and "/" or path
end
local function createDisk(id, hw)
local disk = {
address = id,
isReadOnly = function() return hw.isReadOnly() end
isReadOnly = function()
return hw.isReadOnly()
end
}
function disk:spaceUsed() return hw.spaceUsed() end
function disk:spaceTotal() return hw.spaceTotal() end
function disk:spaceUsed()
return hw.spaceUsed()
end
function disk:spaceTotal()
return hw.spaceTotal()
end
function disk:list(path)
path = normalize(path)
if not hw.exists(path) or not hw.isDirectory(path) then
return nil, "not directory"
end
local ret = {}
for i, v in ipairs(hw.list(path)) do
if v:sub(-1)=="/" then
ret[i]=v:sub(1,#v-1)
else ret[i]=v end
ret[i] = normalize(v)
end
return ret
end
function disk:fileExists(path)
path = normalize(path)
return hw.exists(path) and not hw.isDirectory(path)
end
function disk:directoryExists(path)
path = normalize(path)
return hw.exists(path) and hw.isDirectory(path)
end
function disk:type(path)
path = normalize(path)
if not hw.exists(path) then
return nil
elseif hw.isDirectory(path) then
@@ -46,17 +78,29 @@ local function createDisk(id, hw)
end
function disk:makeDirectory(path)
hw.makeDirectory(path)
path = normalize(path)
return hw.makeDirectory(path)
end
function disk:remove(path)
if hw.exists(path) then hw.remove(path) end
path = normalize(path)
if hw.exists(path) then
return hw.remove(path)
end
end
function disk:setLabel(label) hw.setLabel(label) end
function disk:getLabel() return hw.getLabel() end
function disk:setLabel(label)
return hw.setLabel(label)
end
function disk:getLabel()
return hw.getLabel()
end
function disk:attributes(path)
path = normalize(path)
return {
size = hw.size(path),
isDir = hw.isDirectory(path),
@@ -67,6 +111,8 @@ local function createDisk(id, hw)
end
function disk:open(path, mode)
path = normalize(path)
local fd = hw.open(path, mode)
if not fd then
@@ -74,44 +120,68 @@ local function createDisk(id, hw)
if dir and not hw.exists(dir) then
local ok, err = hw.makeDirectory(dir)
if not ok then
return nil, err or "could not create parent directory"
end
end
fd = hw.open(path, mode)
if not fd then
return nil, "file not found or access denied"
end
end
return {
read = function(num) return hw.read(fd, num) end,
read = function(num)
return hw.read(fd, num)
end,
readAll = function()
local data = {}
while true do
local chunk = hw.read(fd, math.huge)
if not chunk then break end
local chunk, err = hw.read(fd, 2048)
if chunk == nil then
if err then
return nil, err
end
break
end
if #chunk == 0 then
break
end
data[#data + 1] = chunk
end
return table.concat(data)
end,
write = function(data) return hw.write(fd, data) end,
write = function(data)
return hw.write(fd, data)
end,
seek = function(whence, offset)
return hw.seek(fd, whence, offset)
end,
flush = function()
if fd then
hw.close(fd)
fd = hw.open(path, mode)
end
end,
close = function()
if fd then
hw.close(fd)
fd = nil
end
end
}
end
@@ -122,21 +192,34 @@ internal["$"] = createDisk("$", bootdrive)
local function refresh()
disks = {}
for addr in apis.component.list("filesystem") do
if addr ~= bootaddr then
disks[addr] = createDisk(addr, apis.component.proxy(addr))
disks[addr] = createDisk(
addr,
apis.component.proxy(addr)
)
end
end
end
local function iter()
refresh()
local combined = {}
for id, obj in pairs(internal) do combined[id] = obj end
for id, obj in pairs(disks) do combined[id] = obj end
for id, obj in pairs(internal) do
combined[id] = obj
end
for id, obj in pairs(disks) do
combined[id] = obj
end
return pairs(combined)
end
return {refresh = refresh, list = iter}
return {
refresh = refresh,
list = iter
}
@@ -0,0 +1,442 @@
--:Minify:--
local kernel = ...
local component = kernel.oc and kernel.oc.component
local internetAddress
for address in component.list("internet") do
internetAddress = address
break
end
if not internetAddress then
if kernel.log then
kernel.log("NET: No Internet component available")
end
return
end
local internet = component.proxy(internetAddress)
local tcpEnabled = false
local httpEnabled = false
if internet.isTcpEnabled then
local ok, result = pcall(internet.isTcpEnabled)
tcpEnabled = ok and result == true
end
if internet.isHttpEnabled then
local ok, result = pcall(internet.isHttpEnabled)
httpEnabled = ok and result == true
end
local function closeHandle(handle)
if handle and handle.close then
pcall(handle.close)
end
end
local function parseRawRequest(raw, address)
local headerEnd = raw:find("\r\n\r\n", 1, true)
local headerPart
local body = ""
if headerEnd then
headerPart = raw:sub(1, headerEnd - 1)
body = raw:sub(headerEnd + 4)
else
headerPart = raw
end
local lines = {}
for line in headerPart:gmatch("[^\r\n]+") do
lines[#lines + 1] = line
end
if #lines == 0 then
return nil, "EINVAL"
end
local method, path, ver =
lines[1]:match("^(%S+)%s+(%S+)%s+(%S+)$")
if not method then
return nil, "EINVAL"
end
if path:sub(1, 1) ~= "/" then
return nil, "EINVAL"
end
local headers = {}
for i = 2, #lines do
local k, v = lines[i]:match("^([^:]+):%s*(.*)$")
if k then
headers[k] = v
end
end
local url = address .. path
return {
url = url,
method = method,
headers = headers,
body = body
}, url
end
local function buildHTTPResponse(req)
if req.method ~= "GET" and req.method ~= "POST" then
return nil, "EOPNOTSUPP"
end
local postData
if req.method == "POST" then
postData = req.body or ""
end
local ok, response = pcall(
internet.request,
req.url,
postData,
req.headers
)
if not ok or not response then
return nil, tostring(response or "ECONN")
end
local connected, connectResult = pcall(
response.finishConnect
)
if not connected or connectResult == false then
closeHandle(response)
return nil, tostring(connectResult or "ECONN")
end
local code = 200
local msg = "OK"
local headers = {}
if response.response then
local responseOK, c, m, h = pcall(response.response)
if responseOK then
code = c or code
msg = m or msg
headers = h or headers
end
end
local chunks = {}
while true do
local readOK, chunk = pcall(response.read, 8192)
if not readOK then
closeHandle(response)
return nil, tostring(chunk)
end
if not chunk or #chunk == 0 then
break
end
chunks[#chunks + 1] = chunk
end
closeHandle(response)
local out = {
"HTTP/1.1 " .. tostring(code) .. " " .. tostring(msg)
}
for k, v in pairs(headers) do
if type(v) == "table" then
for i = 1, #v do
out[#out + 1] = k .. ": " .. tostring(v[i])
end
else
out[#out + 1] = k .. ": " .. tostring(v)
end
end
out[#out + 1] = ""
out[#out + 1] = table.concat(chunks)
return table.concat(out, "\r\n")
end
local function closeFile(socket)
if socket.file then
pcall(socket.file.close)
socket.file = nil
end
end
local httpHandler = {}
function httpHandler.connect(fd, address)
local fdo = kernel.currentTask.fd[fd]
if not fdo then
return nil, "EBADF"
end
fdo.socket = fdo.socket or {}
local socket = fdo.socket
socket.active = false
socket.loaded = false
socket.file = nil
fdo.handle.write = function(raw)
local req, url = parseRawRequest(raw, address)
if not req then
return nil, url
end
closeFile(socket)
socket.active = true
socket.loaded = false
socket.url = url
local response, err = buildHTTPResponse(req)
if not response then
socket.active = false
socket.error = err
return nil, err
end
socket.content = response
socket.file = kernel.sfile(response)
socket.loaded = true
socket.error = nil
return true
end
fdo.handle.read = function(count)
if not socket.active then
return
end
if socket.error then
return nil, socket.error
end
if not socket.file then
return
end
return socket.file.read(count)
end
fdo.handle.seek = function(whence, offset)
if not socket.active or not socket.file then
return
end
return socket.file.seek(whence, offset)
end
fdo.handle.close = function()
closeFile(socket)
socket.active = false
socket.loaded = false
socket.content = nil
socket.url = nil
socket.error = nil
return true
end
return true
end
local tcpHandler = {}
local function parseTCPAddress(address)
local host, port
if address:sub(1, 1) == "[" then
host, port = address:match("^%[([^%]]+)%]:(%d+)$")
if not host then
host = address:match("^%[([^%]]+)%]$")
end
else
host, port = address:match("^([^:]+):(%d+)$")
if not host then
host = address
end
end
if not host or host == "" then
return nil, nil, "EINVAL"
end
if port then
port = tonumber(port)
if not port or port < 1 or port > 65535 then
return nil, nil, "EINVAL"
end
end
return host, port
end
function tcpHandler.connect(fd, address)
if not tcpEnabled then
return nil, "EOPNOTSUPP"
end
local fdo = kernel.currentTask.fd[fd]
if not fdo then
return nil, "EBADF"
end
local host, port, err = parseTCPAddress(address)
if not host then
return nil, err
end
fdo.socket = fdo.socket or {}
local socket = fdo.socket
if socket.tcp then
closeHandle(socket.tcp)
end
socket.tcp = nil
socket.active = false
socket.error = nil
socket.host = host
socket.port = port
local ok, tcp = pcall(
internet.connect,
host,
port
)
if not ok or not tcp then
return nil, tostring(tcp or "ECONN")
end
socket.tcp = tcp
socket.active = true
local connected, result = pcall(
tcp.finishConnect
)
if not connected or result == false then
closeHandle(tcp)
socket.tcp = nil
socket.active = false
return nil, tostring(result or "ECONN")
end
fdo.handle.write = function(data)
if not socket.active or not socket.tcp then
return nil, "ENOTCONN"
end
if type(data) ~= "string" then
return nil, "EINVAL"
end
local writeOK, written = pcall(
socket.tcp.write,
data
)
if not writeOK then
return nil, tostring(written)
end
return written
end
fdo.handle.read = function(count)
if not socket.active or not socket.tcp then
return nil, "ENOTCONN"
end
local readOK, data = pcall(
socket.tcp.read,
count
)
if not readOK then
return nil, tostring(data)
end
return data
end
fdo.handle.seek = function()
return nil, "ESPIPE"
end
fdo.handle.close = function()
closeHandle(socket.tcp)
socket.tcp = nil
socket.active = false
socket.error = nil
socket.host = nil
socket.port = nil
return true
end
return true
end
if httpEnabled then
kernel.socket.registerProtocal(
"http://",
httpHandler
)
kernel.socket.registerProtocal(
"https://",
httpHandler
)
if kernel.log then
kernel.log("NET: HTTP/HTTPS initialized")
end
end
if tcpEnabled then
kernel.socket.registerProtocal(
"tcp://",
tcpHandler
)
if kernel.log then
kernel.log("NET: TCP initialized")
end
end
@@ -1,4 +1,3 @@
-- OpenComputers TTY driver
local kernel = ...
local component = kernel.oc.component
@@ -26,7 +25,6 @@ local plt = {
0x660000, 0x660040, 0x660080, 0x6600C0, 0x6600FF,
0x662400, 0x662440, 0x662480, 0x6624C0, 0x6624FF,
0x664900, 0x664940, 0x664980, 0x6649C0, 0x6649FF,
0x666D00, 0x666D40, 0x666D80, 0x666DC0, 0x666DFF,
0x669200, 0x669240, 0x669280, 0x6692C0, 0x6692FF,
0x66B600, 0x66B640, 0x66B680, 0x66B6C0, 0x66B6FF,
0x66DB00, 0x66DB40, 0x66DB80, 0x66DBC0, 0x66DBFF,
@@ -65,108 +63,318 @@ local plt = {
0xB4B4B4, 0xC3C3C3, 0xD2D2D2, 0xE1E1E1
}
local gpus,screens = {},{}
local gpus = {}
local screens = {}
-- Collect GPUs.
for addr, typ in component.list("gpu") do
if typ == "gpu" then
gpus[#gpus+1]=component.proxy(addr)
local gpu = component.proxy(addr)
gpus[#gpus + 1] = {
addr = addr,
gpu = gpu,
screen = nil,
fg = nil,
bg = nil
}
end
end
if #gpus>0 then
-- Collect screens.
for addr, typ in component.list("screen") do
if typ == "screen" then
gpus[1].bind(addr)
local w,h = gpus[1].maxResolution()
gpus[1].setResolution(w,h)
screens[addr]={cx=1,cy=1,w=w,h=h,addr=addr,fg=0,bg=0,gpu=nil}
end
screens[addr] = {
cx = 1,
cy = 1,
w = 0,
h = 0,
addr = addr,
fg = 0xFFFFFF,
bg = 0x000000,
gpu = nil
}
end
end
-- Count screens.
local scrnum = 0
for i,v in pairs(screens) do
for _ in pairs(screens) do
scrnum = scrnum + 1
end
kernel.log("initialized "..tostring(#gpus).." gpus and "..tostring(scrnum).." screens")
-- Find a GPU that can bind to a screen.
local function bindGPU(scr)
if scr.gpu then
local state = scr.gpu
local binds,newid={},0
local curaddr=""
local function scroll(scr, gpu) gpu.copy(1,2,scr.w,scr.h-1,0,-1);gpu.fill(1,scr.h,scr.w,1," ") end
if state.screen == scr.addr then
return state
end
end
for i = 1, #gpus do
local state = gpus[i]
-- Avoid unnecessary rebinding.
if state.screen == scr.addr then
scr.gpu = state
return state
end
-- Try binding this GPU.
local ok, result = pcall(state.gpu.bind, scr.addr)
if ok and result ~= false then
state.screen = scr.addr
state.fg = nil
state.bg = nil
scr.gpu = state
local w, h = state.gpu.maxResolution()
scr.w = w
scr.h = h
pcall(state.gpu.setResolution, w, h)
return state
end
end
error("No GPU available for screen " .. tostring(scr.addr))
end
-- Initialize screens.
for addr, scr in pairs(screens) do
local ok, result = pcall(bindGPU, scr)
if not ok then
kernel.log(
"Failed to initialize screen " ..
tostring(addr) .. ": " .. tostring(result)
)
end
end
kernel.log(
"initialized " ..
tostring(#gpus) ..
" gpus and " ..
tostring(scrnum) ..
" screens"
)
local newid = 0
-- Get the GPU currently assigned to a screen.
local function getGPU(scr)
local state = scr.gpu
if not state then
state = bindGPU(scr)
end
if state.screen ~= scr.addr then
local ok, result = pcall(state.gpu.bind, scr.addr)
if not ok or result == false then
state.screen = nil
state.fg = nil
state.bg = nil
scr.gpu = nil
state = bindGPU(scr)
else
state.screen = scr.addr
state.fg = nil
state.bg = nil
end
end
return state
end
-- Set colors only when they actually change.
local function setColors(state, scr)
local gpu = state.gpu
if state.fg ~= scr.fg then
gpu.setForeground(scr.fg)
state.fg = scr.fg
end
if state.bg ~= scr.bg then
gpu.setBackground(scr.bg)
state.bg = scr.bg
end
end
-- Scroll terminal.
local function scroll(scr, gpu)
gpu.copy(
1, 2,
scr.w, scr.h - 1,
0, -1
)
gpu.fill(
1, scr.h,
scr.w, 1,
" "
)
end
-- Write terminal output.
local function write(text, addr)
local g=gpus[1]
local scr = screens[addr]
if not scr then error("NODEV") end
if curaddr~=addr then g.bind(addr); g.setForeground(scr.fg); g.setBackground(scr.bg) end
if not scr then
error("NODEV")
end
local state = getGPU(scr)
local gpu = state.gpu
setColors(state, scr)
for i = 1, #text do
local char = text:sub(i, i)
if char=="\n" then scr.cx=1;scr.cy=scr.cy+1
elseif char=="\t" then scr.cx=scr.cx+(4-((scr.cx-1)%4))
elseif char=="\b" then if scr.cx>1 then scr.cx=scr.cx-1;g.set(scr.cx,scr.cy," ") end
else g.set(scr.cx,scr.cy,char);scr.cx=scr.cx+1 end
if scr.cx>scr.w then scr.cx=1;scr.cy=scr.cy+1 end
if scr.cy>scr.h then scroll(scr, g);scr.cy=scr.cy-1 end
if char == "\n" then
scr.cx = 1
scr.cy = scr.cy + 1
elseif char == "\t" then
scr.cx = scr.cx + (4 - ((scr.cx - 1) % 4))
elseif char == "\b" then
if scr.cx > 1 then
scr.cx = scr.cx - 1
gpu.set(scr.cx, scr.cy, " ")
end
else
gpu.set(scr.cx, scr.cy, char)
scr.cx = scr.cx + 1
end
if scr.cx > scr.w then
scr.cx = 1
scr.cy = scr.cy + 1
end
if scr.cy > scr.h then
scroll(scr, gpu)
scr.cy = scr.cy - 1
end
end
end
-- Create TTY.
local function newtty(addr)
newid = newid + 1
kernel.devfs.data["tty"][tostring(newid)] = function(op, mode)
if op == "type" then
return "Terminal"
elseif op == "open" then
local h = {
read=function(amount) end,
read = function(amount)
end,
write = function(content)
write(content, addr)
end,
size = function()
return screens[addr].w, screens[addr].h
end,
clear=function()
local g=gpus[1]
local scr = screens[addr]
if addr~=curaddr then g.bind(addr) end
g.fill(1,1,scr.w,scr.h," ");
scr.cx,scr.cy=1,1
return scr.w, scr.h
end,
clear = function()
local scr = screens[addr]
local state = getGPU(scr)
local gpu = state.gpu
setColors(state, scr)
gpu.fill(
1, 1,
scr.w, scr.h,
" "
)
scr.cx = 1
scr.cy = 1
end,
gpos = function()
return screens[addr].cx, screens[addr].cy
local scr = screens[addr]
return scr.cx, scr.cy
end,
spos = function(x, y)
if not tonumber(x) or not tonumber(y) then error("Invailid arg") end
screens[addr].cx, screens[addr].cy = x,y
if not tonumber(x) or not tonumber(y) then
error("Invalid arg")
end
local scr = screens[addr]
scr.cx = x
scr.cy = y
end,
sfgc = function(c)
screens[addr].fg=c
local scr = screens[addr]
if scr.fg ~= c then
scr.fg = c
end
end,
sbgc = function(c)
screens[addr].bg=c
local scr = screens[addr]
if scr.bg ~= c then
scr.bg = c
end
end,
gfgc = function()
return screens[addr].fg
end,
gbgc = function()
return screens[addr].bg
end,
isvirt = function()
return false
end,
gplt = function()
return plt
end,
gfx = function()
return false
end
}
if mode == "rw" then
return h
elseif mode == "r" then
h["write"]=nil
h.write = nil
return h
elseif mode == "w" then
h["read"]=nil
h.read = nil
return h
end
end
@@ -174,7 +382,9 @@ local function newtty(addr)
end
if #gpus >= 1 and scrnum >= 1 then
for addr,obj in pairs(screens) do
for addr, scr in pairs(screens) do
if scr.gpu then
newtty(addr)
end
end
end
@@ -7,19 +7,19 @@ local kbidx=0
local keyboard = {}
keyboard.keys = {
back = 0x0E, -- backspace
back = 0x0E,
delete = 0xD3,
down = 0xD0,
enter = 0x1C,
home = 0xC7,
lcontrol = 0x1D,
left = 0xCB,
lmenu = 0x38, -- left Alt
lmenu = 0x38,
lshift = 0x2A,
pageDown = 0xD1,
rcontrol = 0x9D,
right = 0xCD,
rmenu = 0xB8, -- right Alt
rmenu = 0xB8,
rshift = 0x36,
space = 0x39,
tab = 0x0F,
@@ -33,8 +33,6 @@ for i=0, 255 do
kernel.oc.keys[string.char(i)]=i
end
-------------------------------------------------------------------------------
function keyboard.isAltDown(addr)
return kbs[addr].pressedCodes[keyboard.keys.lmenu] or kbs[addr].pressedCodes[keyboard.keys.rmenu]
end
@@ -78,15 +76,24 @@ for addr, typ in kernel.oc.component.list("keyboard") do
elseif op=="open" then
local h = {
read=function(amount)
amount = amount or 1
local rv=""
for i=1, amount or 1 do
for i=1, amount do
local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then
rv=rv..event[1]
else
break
end
end
if rv=="" then rv=nil end
return rv
if rv~="" then return rv end
local task=kernel.currentTask
task.status="D"
task.io=function()
local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then return event[1] end
end
return nil
end,
write=function(content)
end,
@@ -27,8 +27,6 @@ kernel.processes.ocdaemon = function()
[keys.left] = "\27[D",
[keys.home] = "\27[H",
[keys["end"]] = "\27[F",
--[keys.pageUp] = "\27[5~",
--[keys.pageDown] = "\27[6~",
[keys.delete] = "\27[3~",
[keys.enter] = "\n",
[keys.back] = "\b",
@@ -10,7 +10,6 @@ local lambda_var = 0.02
local k_min = 0.5
local k_max = 0.5
local B = 0.01
local nextyield=0
function kernel.main()
kernel.log("Starting main loop...")
@@ -18,6 +17,9 @@ function kernel.main()
local stopLog=5
local logTasks=100
local burstSteps = 0
local maxBurstSteps = 64
while not kernel.exitMain do
if kernel.config.logTasks then
if logTasks<0 then
@@ -121,6 +123,11 @@ function kernel.main()
end
end
end
end
burstSteps = burstSteps + N
if N == 0 or burstSteps >= maxBurstSteps then
burstSteps = 0
kernel.EFI:yield()
end
+8 -1
View File
@@ -357,6 +357,11 @@ kernel.loadingModule="kernel"
kernel.perTaskHooks={}
kernel.mainHooks={}
kernel.runhooks={}
local loadedmodules={}
function kernel.getLoadedModules()
return table.deepcopy(loadedmodules)
end
-- args {taskobj, pid}
function kernel.execPerTask(func, prior)
@@ -430,7 +435,7 @@ kernel.syscalls["getHostname"]=function() return kernel.hostname end
kernel.syscalls["getHost"]=function() return kernel.apis._HOST end
kernel.syscalls["version"]=function() return kernel.version end
kernel.syscalls["setHostname"]=function(name) if kernel.uid~=0 then error("Permission denied") end kernel.hostname=name end
kernel.syscalls["arch"]=function() return arch end
kernel.syscalls["arch"]=function() return kernel.arch end
kernel.syscalls["sysdump"]=function()
local rv={}
for i,v in pairs(kernel.syscalls) do
@@ -465,6 +470,7 @@ kernel.log("Running modules")
for _,p in ipairs(modules) do
for _,v in ipairs(p) do
kernel.loadingModule=v
EFI:yield()
if not kernel.denied[v] then
if kernel.config.showModLoad then kernel.log("Loading module "..v, "DBUG", 0x00FFFF) end
local code=ifs.readAllText("/lib/modules/"..v)
@@ -476,6 +482,7 @@ for _,p in ipairs(modules) do
local status, err = xpcall(func,debug.traceback, kernel)
if not status then kernel.panic("ModuRunErr: "..tostring(err)) end
if kernel.config.showModLoad then kernel.log("Loaded module "..v, "DBUG", 0x00FFFF) end
loadedmodules[#loadedmodules+1]=v
if kernel.config.moreLogsaves then kernel.saveLog() end
else
if kernel.config.showModLoad then kernel.log("Denied module "..v, "DBUG", 0xFF0000) end
+1 -1
View File
@@ -4,7 +4,7 @@
-- This file is auto-generated during the build process.
-- DEFAULT BOOT CONFIGURATION FILE
return {
initPath = "/sbin/init",
initPath = "/usr/lib/sysinit/sysinit",
maxOpenFiles = 128,
maxFilesPerTask = 16,
preempt = true,
@@ -973,6 +973,9 @@ function vfs.symlink(target, linkPath)
if type(target) ~= "string" or type(linkPath) ~= "string" then error("EINVAL") end
local norm = normalizePath(linkPath)
local parent = norm:match("^(.*)/[^/]+$") or "/"
if not vfs.exists(parent) then
vfs.mkdir(parent)
end
local disk = resolveMount(linkPath)
if disk:isReadOnly() then error("ERDONLY") end
if parent == "" then parent = "/" end
@@ -1017,7 +1020,7 @@ function vfs.access(path, mode)
return true
end
local function updateMeta(path, fn, noFollow)
local function updateMeta(path, fn, noFollow, nullify)
local real = namei(path, noFollow)
local norm = real
local parent = norm:match("^(.*)/[^/]+$") or "/"
@@ -1042,9 +1045,13 @@ local function updateMeta(path, fn, noFollow)
if uf.close then uf.close() end
existing = parseMetafile(raw)
end
if not nullify then
local entry = existing[name] or { etype=0, owner=0, group=0, perms=63, cmeta="" }
fn(entry)
existing[name] = entry
else
existing[name] = nil
end
local f = disk:open(mp, "w"); f.write(makeMetafile(existing)); if f.close then f.close() end
end
@@ -1055,7 +1062,7 @@ function vfs.chmod(path, perms)
local meta = getFileMeta(path)
local euid = (kernel.currentTask and (kernel.currentTask.euid or kernel.currentTask.uid)) or kernel.uid
if euid ~= 0 and euid ~= meta.owner then error("EACCES") end
updateMeta(path, function(e) e.perms = perms end)
updateMeta(path, function(e) e.perms = perms end, nil, not perms)
end
function vfs.fchmod(fd, perms)
@@ -239,6 +239,7 @@ if kernel.EFI.getEEPROM then
write=function(data)
if firstwrite then
kernel.EFI:setEEPROM(data)
firstwrite=false
else
kernel.EFI:setEEPROM(kernel.EFI:getEEPROM()..data)
end
@@ -276,6 +277,7 @@ if kernel.EFI.getNvram then
write=function(data)
if firstwrite then
kernel.EFI:setNvram(data)
firstwrite=false
else
kernel.EFI:setNvram(kernel.EFI:getNvram()..data)
end
@@ -1,102 +1,283 @@
--:Minify:--
local kernel = ...
local os = os
if not kernel.config.tmpToDisk then
local proxy = {}
local data = {}
local timestamps = {}
local now = function() return kernel.EFI:getEpochMs() end
local function touch(path, created)
local time = now()
timestamps[path] = timestamps[path] or {
created = created or time,
modified = time,
}
timestamps[path].modified = time
end
local function getTimestamp(path)
if not timestamps[path] then
local time = now()
timestamps[path] = {
created = time,
modified = time,
}
end
return timestamps[path]
end
proxy.address = "tmpfs0000"
proxy.isvirt = true
proxy.isReadOnly = function() return false end
proxy.isReadOnly = function()
return false
end
proxy.spaceUsed = function() return 0 end
proxy.spaceTotal = function() return 0 end
proxy.spaceUsed = function()
local function size(step)
local total = 0
for _, value in pairs(step) do
if type(value) == "string" then
total = total + #value
elseif type(value) == "table" then
total = total + size(value)
end
end
return total
end
return size(data)
end
proxy.spaceTotal = function()
return math.huge
end
proxy.makeDirectory = function(_, path)
local steps = kernel.vfs.splitPath(path)
local step = data
local current = ""
for i = 1, #steps do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
if not step[steps[i]] then
step[steps[i]] = {}
touch(current)
elseif type(step[steps[i]]) ~= "table" then
error("ENOTDIR")
end
step = step[steps[i]]
end
end
proxy.remove = function(_, path)
local steps = kernel.vfs.splitPath(path)
local step = data
for i=1,#steps-1 do
step = step[steps[i]]
if not step then error("ENOENT") end
end
step[steps[#steps]] = nil
if #steps == 0 then
error("EACCES")
end
proxy.setLabel = function(_, label) end
proxy.getLabel = function() return "tmpfs" end
local step = data
local current = ""
for i = 1, #steps - 1 do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
step = step[steps[i]]
if not step then
error("ENOENT")
end
if type(step) ~= "table" then
error("ENOTDIR")
end
end
local name = steps[#steps]
if step[name] == nil then
error("ENOENT")
end
local function clearTimestamps(value, pathPrefix)
timestamps[pathPrefix] = nil
if type(value) == "table" then
for key, child in pairs(value) do
clearTimestamps(child, pathPrefix .. "/" .. key)
end
end
end
clearTimestamps(step[name], path)
step[name] = nil
end
proxy.setLabel = function(_, label)
end
proxy.getLabel = function()
return "tmpfs"
end
proxy.attributes = function(_, path)
local steps = kernel.vfs.splitPath(path)
local step = data
local current = ""
for i = 1, #steps do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
step = step[steps[i]]
if not step then error("ENOENT") end
if step == nil then
error("ENOENT")
end
end
local time = getTimestamp(current)
return {
size = type(step) == "string" and #step or 0,
modified = 0,
created = 0,
modified = time.modified,
created = time.created,
}
end
function proxy:open(path, mode)
local steps = kernel.vfs.splitPath(path)
if #steps == 0 then
error("EISDIR")
end
local step = data
local current = ""
for i = 1, #steps - 1 do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
if not step[steps[i]] then
if mode == "w" then step[steps[i]] = {} else error("ENOENT") end
if mode == "w" then
step[steps[i]] = {}
touch(current)
else
error("ENOENT")
end
elseif type(step[steps[i]]) ~= "table" then
error("ENOTDIR")
end
step = step[steps[i]]
end
local filename = steps[#steps]
local filepath = current == "" and filename
or current .. "/" .. filename
if mode == "r" then
if type(step[filename]) ~= "string" then error("ENOENT") end
if type(step[filename]) ~= "string" then
if type(step[filename]) == "table" then
error("EISDIR")
end
error("ENOENT")
end
local content = step[filename]
local pos = 1
return {
read = function(amount)
amount = amount or #content
local chunk = content:sub(pos, pos + amount - 1)
pos = pos + #chunk
if chunk == "" then
return nil
end
return chunk
end,
close = function() end,
}
elseif mode == "w" then
step[filename] = ""
local buf = {}
return {
write = function(str)
buf[#buf + 1] = str
end,
close = function()
step[filename] = table.concat(buf)
end,
}
elseif mode == "a" then
if type(step[filename]) ~= "string" then step[filename] = "" end
elseif mode == "w" then
if type(step[filename]) == "table" then
error("EISDIR")
end
local buf = {}
local closed = false
return {
write = function(str)
step[filename] = step[filename] .. str
if closed then
error("EBADF")
end
buf[#buf + 1] = tostring(str)
end,
close = function() end,
close = function()
if closed then
return
end
closed = true
local existed = type(step[filename]) == "string"
step[filename] = table.concat(buf)
if not existed then
local time = now()
timestamps[filepath] = {
created = time,
modified = time,
}
else
touch(filepath)
end
end,
}
elseif mode == "a" then
if type(step[filename]) == "table" then
error("EISDIR")
end
local buf = {
type(step[filename]) == "string" and step[filename] or ""
}
local closed = false
return {
write = function(str)
if closed then
error("EBADF")
end
buf[#buf + 1] = tostring(str)
end,
close = function()
if closed then
return
end
closed = true
local existed = type(step[filename]) == "string"
step[filename] = table.concat(buf)
if not existed then
local time = now()
timestamps[filepath] = {
created = time,
modified = time,
}
else
touch(filepath)
end
end,
}
else
error("EACCES")
end
@@ -105,25 +286,57 @@ if not kernel.config.tmpToDisk then
function proxy:type(path)
local steps = kernel.vfs.splitPath(path)
local step = data
if #steps == 0 then return "directory" end
if #steps == 0 then
return "directory"
end
for i = 1, #steps do
if type(step) ~= "table" then
return false
end
step = step[steps[i]]
if not step then return false end
if step == nil then
return false
end
end
if type(step) == "table" then
return "directory"
end
if type(step) == "string" then
return "file"
end
if type(step) == "table" then return "directory" end
if type(step) == "string" then return "file" end
end
function proxy:list(path)
local steps = kernel.vfs.splitPath(path)
local step = data
local current = ""
for i = 1, #steps do
step = step[steps[i]]
if not step then error("ENOENT") end
current = current == "" and steps[i]
or current .. "/" .. steps[i]
if type(step) ~= "table" then
error("ENOTDIR")
end
if type(step) ~= "table" then error("ENOTDIR") end
step = step[steps[i]]
if step == nil then
error("ENOENT")
end
end
if type(step) ~= "table" then
error("ENOTDIR")
end
local keys = {}
for k,_ in pairs(step) do table.insert(keys, k) end
for k in pairs(step) do
keys[#keys + 1] = k
end
return keys
end
@@ -133,9 +346,11 @@ if not kernel.config.tmpToDisk then
end
kernel.disks["tmpfs0000"] = proxy
kernel.tmpfs={data=data,proxy=proxy}
else
kernel.log("tmpToDisk enabled, skipping tmpfs module")
kernel.log("tmpfs0000 will passthrough to /tmp on the disk")
kernel.runWhenLoaded(function()
kernel.vfs.remove("/tmp")
kernel.vfs.mkdir("/tmp")
@@ -160,7 +160,19 @@ function socket.recv(fd, amount)
return nil, "EOPNOTSUPP"
end
return fdo.handle.read(amount)
local ret = fdo.handle.read(amount)
if ret==nil or ret=="" then
kernel.currentTask.io=function()
ret = fdo.handle.read(amount)
if ret~=nil and ret~="" then
return ret
end
end
kernel.currentTask.status="D"
return
else
return ret
end
end
function socket.sockshutdown(fd)
@@ -10,17 +10,52 @@ local function bit_is_set(num, bit)
return math.floor(num / (2 ^ bit)) % 2 == 1
end
local function loadExecutable(path)
kernel.vfs.access(path, "rx")
if kernel.vfs.type(path)~="file" then error("Target is not file") end
local fd = kernel.vfs.open(path, "r")
local data = kernel.vfs.read(fd, 1024 * 1024 * 4)
if not fd then
error("ENOENT: " .. tostring(path))
end
local chunks = {}
local total = 0
local ok, err = pcall(function()
while true do
local chunk = kernel.vfs.read(fd, 2048)
if not chunk or #chunk == 0 then
break
end
chunks[#chunks + 1] = chunk
total = total + #chunk
end
end)
kernel.vfs.close(fd)
if not ok then
error("EIO reading executable: " .. tostring(err))
end
local data = table.concat(chunks)
local env = kernel.freshUserEnv()
local func, err = load(data, "@" .. path, "t", env)
if not func then kernel.log("Failed to load executable: " .. tostring(err).. " : ".. tostring(path)); error("ENOEXEC: " .. tostring(err)) end
if not func then
kernel.log(
"Failed to load executable: " ..
tostring(err) .. " : " .. tostring(path)
)
error("ENOEXEC: " .. tostring(err))
end
local meta = kernel.vfs.lstat(path)
local suid_set = bit_is_set(meta.perms, 6)
@@ -30,6 +65,7 @@ local function loadExecutable(path)
return func, euid, suid_set
end
local function createTask(func, name, envars, args, tgid, real_uid, eff_uid, clearFds)
local id = nextpid
nextpid = nextpid + 1
@@ -142,6 +178,8 @@ function sys.exec(path, args, envars, clearFds)
task.args = args or {}
task.envars = envars or task.envars or {}
task.name = path
task.ivs = 0
task.vs = 0
task.coro = coroutine.create(function()
local ok, err = xpcall(func, debug.traceback, table.unpack(task.args))
@@ -251,7 +289,7 @@ function sys.stop(pid)
end
end
function sys.continue(pid)
function sys.cont(pid)
local task = tasks[tostring(pid)]
if not task then
return false, "Task does not exist"
@@ -394,7 +432,7 @@ sysc["getTask"] = sys.getTask
sysc["collect"] = sys.collect
sysc["kill"] = sys.kill
sysc["stop"] = sys.stop
sysc["continue"] = sys.continue
sysc["continue"] = sys.cont
sysc["getpid"] = sys.getpid
sysc["getppid"] = sys.getppid
sysc["getTasks"] = sys.getTasks
+1 -1
View File
@@ -58,7 +58,7 @@ syscall.setEnviron("HOME", homedir)
syscall.setEnviron("USER", username)
syscall.setEnviron("SHELL", shell)
local ok, err = pcall(syscall.exec, shell, nil, true)
local ok, err = pcall(syscall.exec, shell, nil, nil, true)
if not ok then
print("su: cannot exec shell '" .. shell .. "': " .. tostring(err))
syscall.exit(1)
+1 -1
View File
@@ -143,7 +143,7 @@ function Font:print(x, y, text, r, g, b)
local glyph = self._glyphs[code]
if glyph then
local buf = getGlyphBuffer(glyph, r, g, b)
screen.drawPixels(cur, y, buf, glyph.width, glyph.height)
screen.writeData(cur, y, buf, glyph.width)
cur = cur + glyph.width + spacing
end
end
-1
View File
@@ -1 +0,0 @@
vector
-1
View File
@@ -1 +0,0 @@
package providing kernel support for framebuffers and graphics
-19
View File
@@ -1,19 +0,0 @@
function lib.load(fd)
function handle.setPixel(x,y,color24)
function handle.getPixel(x,y)
function handle.setPixels(x,y,w,framebuffer)
function handle.getPixels(x,y,w,h)
function handle.frame(x,y,w,h,writeonly)
integer id
recurse lib.load
function handle.framectl(id)
function frame.move(x,y)
function frame.resize(w,h)
function frame.free()
function handle.sync()
function handle.line(x1,y1,x2,y2)
function handle.box(x,y,w,h,c,fill)
function handle.filledBox(x,y,w,h,c)
function handle.text(x,y,font,text)
function handle.free()
function handle.size()
-256
View File
@@ -1,256 +0,0 @@
#000000
#0b0b0b
#222222
#444444
#555555
#777777
#888888
#aaaaaa
#bbbbbb
#dddddd
#eeeeee
#00000b
#000022
#000044
#000055
#000077
#000088
#0000aa
#0000bb
#0000dd
#0000ee
#000b00
#002200
#004400
#005500
#007700
#008800
#00aa00
#00bb00
#00dd00
#00ee00
#0b0000
#220000
#440000
#550000
#770000
#880000
#aa0000
#bb0000
#dd0000
#ee0000
#000033
#000066
#000099
#0000cc
#0000ff
#003300
#003333
#003366
#003399
#0033cc
#0033ff
#006600
#006633
#006666
#006699
#0066cc
#0066ff
#009900
#009933
#009966
#009999
#0099cc
#0099ff
#00cc00
#00cc33
#00cc66
#00cc99
#00cccc
#00ccff
#00ff00
#00ff33
#00ff66
#00ff99
#00ffcc
#00ffff
#330000
#330033
#330066
#330099
#3300cc
#3300ff
#333300
#333333
#333366
#333399
#3333cc
#3333ff
#336600
#336633
#336666
#336699
#3366cc
#3366ff
#339900
#339933
#339966
#339999
#3399cc
#3399ff
#33cc00
#33cc33
#33cc66
#33cc99
#33cccc
#33ccff
#33ff00
#33ff33
#33ff66
#33ff99
#33ffcc
#33ffff
#660000
#660033
#660066
#660099
#6600cc
#6600ff
#663300
#663333
#663366
#663399
#6633cc
#6633ff
#666600
#666633
#666666
#666699
#6666cc
#6666ff
#669900
#669933
#669966
#669999
#6699cc
#6699ff
#66cc00
#66cc33
#66cc66
#66cc99
#66cccc
#66ccff
#66ff00
#66ff33
#66ff66
#66ff99
#66ffcc
#66ffff
#990000
#990033
#990066
#990099
#9900cc
#9900ff
#993300
#993333
#993366
#993399
#9933cc
#9933ff
#996600
#996633
#996666
#996699
#9966cc
#9966ff
#999900
#999933
#999966
#999999
#9999cc
#9999ff
#99cc00
#99cc33
#99cc66
#99cc99
#99cccc
#99ccff
#99ff00
#99ff33
#99ff66
#99ff99
#99ffcc
#99ffff
#cc0000
#cc0033
#cc0066
#cc0099
#cc00cc
#cc00ff
#cc3300
#cc3333
#cc3366
#cc3399
#cc33cc
#cc33ff
#cc6600
#cc6633
#cc6666
#cc6699
#cc66cc
#cc66ff
#cc9900
#cc9933
#cc9966
#cc9999
#cc99cc
#cc99ff
#cccc00
#cccc33
#cccc66
#cccc99
#cccccc
#ccccff
#ccff00
#ccff33
#ccff66
#ccff99
#ccffcc
#ccffff
#ff0000
#ff0033
#ff0066
#ff0099
#ff00cc
#ff00ff
#ff3300
#ff3333
#ff3366
#ff3399
#ff33cc
#ff33ff
#ff6600
#ff6633
#ff6666
#ff6699
#ff66cc
#ff66ff
#ff9900
#ff9933
#ff9966
#ff9999
#ff99cc
#ff99ff
#ffcc00
#ffcc33
#ffcc66
#ffcc99
#ffcccc
#ffccff
#ffff00
#ffff33
#ffff66
#ffff99
#ffffcc
#ffffff
+115 -12
View File
@@ -156,17 +156,18 @@ local function copyfile(src, dst)
return true
end
local function rmtree(path)
local function rmtree(path, p)
local t = syscall.type(path)
if t == "directory" then
local ok, list = pcall(syscall.listdir, path)
if ok then
for _, e in ipairs(list) do
rmtree(path:gsub("/$","").."/"..e)
rmtree(path:gsub("/$","").."/"..e, p)
end
end
end
if t then pcall(syscall.remove, path) end
if p then print(path) end
end
local function copytree(src, dst)
@@ -334,7 +335,7 @@ builtinCmds.mkdir = function(...)
end
builtinCmds.rm = function(...)
local opts, args = parseargs({...}, "rRf")
local opts, args = parseargs({...}, "rRfv")
if #args == 0 then print("rm: missing operand"); return end
local recursive = opts.r or opts.R
for _, a in ipairs(args) do
@@ -344,10 +345,11 @@ builtinCmds.rm = function(...)
if not opts.f then print("rm: cannot remove '"..a.."': No such file or directory") end
elseif t == "directory" then
if not recursive then print("rm: cannot remove '"..a.."': Is a directory")
else rmtree(path) end
else rmtree(path, opts.v) end
else
local ok, err = pcall(syscall.remove, path)
if not ok then print("rm: cannot remove '"..a.."': "..tostring(err)) end
if opts.v then print("Removed: "..path) end
end
end
end
@@ -888,6 +890,74 @@ local function listCommands(prefix)
return results
end
local cacheGen = 0
local cmdCache = { gen = -1, list = {} }
local dirCache = {}
local cachedPath = nil
local cachedCwd = nil
local function invalidateCaches()
cacheGen = cacheGen + 1
cachedPath = nil
cachedCwd = nil
end
local function currentPath()
if not cachedPath then cachedPath = syscall.getEnviron("PATH") or "/bin/" end
return cachedPath
end
local function currentDir()
if not cachedCwd then cachedCwd = syscall.getcwd() end
return cachedCwd
end
local function cachedCommandNames()
if cmdCache.gen ~= cacheGen then
local seen = {}
local results = {}
for name in pairs(builtinCmds) do
if not seen[name] then results[#results+1] = name; seen[name] = true end
end
for _, p in ipairs(string.split(currentPath(), ":")) do
local ok, entries = pcall(syscall.listdir, p)
if ok and entries then
for _, e in ipairs(entries) do
if not seen[e] then results[#results+1] = e; seen[e] = true end
end
end
end
table.sort(results)
cmdCache.list = results
cmdCache.gen = cacheGen
end
return cmdCache.list
end
local function filterByPrefix(list, prefix)
local out = {}
for _, c in ipairs(list) do
if prefix == "" or c:sub(1, #prefix) == prefix then out[#out+1] = c end
end
return out
end
local function cachedDirList(dir)
local e = dirCache[dir]
if not e or e.gen ~= cacheGen then
local count = 0
for _ in pairs(dirCache) do count = count + 1 end
if count > 32 then dirCache = {} end
local ok, list = pcall(listDir, dir, "")
if ok and list then
e = { gen = cacheGen, list = list }
dirCache[dir] = e
end
end
if e then return e.list end
return {}
end
local function commonPrefix(list)
if #list == 0 then return "" end
local pre = list[1]
@@ -1019,6 +1089,8 @@ local function getUserInput()
local cursorPos = 1
local history = 0
local dirty = true
local contentChanged = true
local ghostText = ""
local function getGhostSuffix()
if #input == 0 then return "" end
@@ -1027,22 +1099,22 @@ local function getUserInput()
local candidates
if isFirst then
if partialDir then
local dir = partialDir:sub(1,1) == "/" and partialDir or (syscall.getcwd().."/"..partialDir)
candidates = listDir(dir, partialBase)
local dir = partialDir:sub(1,1) == "/" and partialDir or (currentDir().."/"..partialDir)
candidates = filterByPrefix(cachedDirList(dir), partialBase)
for i, c in ipairs(candidates) do candidates[i] = partialDir..c end
else
candidates = listCommands(partialBase)
candidates = filterByPrefix(cachedCommandNames(), partialBase)
end
else
local dir, base
if partialDir then
dir = partialDir:sub(1,1) == "/" and partialDir or (syscall.getcwd().."/"..partialDir)
dir = partialDir:sub(1,1) == "/" and partialDir or (currentDir().."/"..partialDir)
base = partialBase
else
dir = syscall.getcwd()
dir = currentDir()
base = partialBase
end
candidates = listDir(dir, base)
candidates = filterByPrefix(cachedDirList(dir), base)
if partialDir then
for i, c in ipairs(candidates) do candidates[i] = partialDir..c end
end
@@ -1069,7 +1141,11 @@ local function getUserInput()
syscall.devctl(1,"sfgc",0xFFFFFF); syscall.devctl(1,"sbgc",0x000000)
local after = string.sub(input, cursorPos+1)
syscall.write(1, after)
local ghost = getGhostSuffix()
if contentChanged then
ghostText = getGhostSuffix()
contentChanged = false
end
local ghost = ghostText
if #ghost > 0 then
syscall.devctl(1,"sfgc",0x6D00FF)
syscall.write(1, ghost)
@@ -1080,8 +1156,27 @@ local function getUserInput()
end
end
local function redrawCursorOnly()
local ok, tw = pcall(syscall.devctl, 1, "size")
if not ok or type(tw) ~= "number" then tw = 80 end
local total = (curOffsetX-1) + (cursorPos-1)
local y = curOffsetY + math.floor(total/tw)
local x = (total%tw)+1
syscall.devctl(1,"spos",x,y)
if blinkState then
syscall.devctl(1,"sfgc",0x000000); syscall.devctl(1,"sbgc",0xFFFFFF)
end
if cursorPos > #input then
syscall.write(1, " ")
else
syscall.write(1, string.sub(input, cursorPos, cursorPos))
end
syscall.devctl(1,"sfgc",0xFFFFFF); syscall.devctl(1,"sbgc",0x000000)
end
while true do
local key = syscall.read(0)
local beforeInput, beforeCursor = input, cursorPos
if key and key ~= "" then
if key=="" then if cursorPos>1 then cursorPos=cursorPos-1;dirty=true end
elseif key=="" then if cursorPos<=#input then cursorPos=cursorPos+1;dirty=true end
@@ -1110,6 +1205,7 @@ local function getUserInput()
local newInput, newCursor, needsRedraw = doTabComplete(input, cursorPos)
if needsRedraw then
input = newInput; cursorPos = newCursor
contentChanged = true
local px,py = syscall.devctl(1, "gpos")
if px > 1 then
syscall.devctl(1,"spos",1,py)
@@ -1138,10 +1234,16 @@ local function getUserInput()
input=string.sub(input,1,cursorPos-1)..key..string.sub(input,cursorPos)
cursorPos=cursorPos+1;dirty=true
end
else
sleep(0.02)
end
if input ~= beforeInput or cursorPos ~= beforeCursor then contentChanged = true end
local curBlink = ((math.floor(syscall.getUptime()/500)%2)==0)
if curBlink~=blinkState then blinkState=curBlink;dirty=true end
if dirty then redraw();dirty=false end
if dirty then
if contentChanged then redraw() else redrawCursorOnly() end
dirty=false
end
end
end
@@ -1245,6 +1347,7 @@ while true do
table.insert(commandHistory, command)
end
runCommand(command)
invalidateCaches()
end
end
File renamed without changes.
+434
View File
@@ -0,0 +1,434 @@
--:Minify:--
local C_TITLE = 0x00FFFF
local C_SELECT = 0xFFFFFF
local C_TABLE = 0x00FF00
local C_STRING = 0x00FF88
local C_NUMBER = 0x24FFFF
local C_BOOL = 0xFF6D00
local C_NIL = 0x6D6D6D
local C_OTHER = 0xDBDBDB
local C_ERROR = 0xFF0000
local function color(col)
syscall.devctl(1, "sfgc", col)
end
local function write(s)
syscall.write(1, tostring(s))
end
local function clear()
syscall.devctl(1, "sfgc", 0xFFFFFF)
syscall.devctl(1, "sbgc", 0x000000)
syscall.devctl(1, "clear")
end
local function describe(value, detailed)
local t = type(value)
if t == "table" then
local count = 0
for _ in pairs(value) do
count = count + 1
end
return "{table: " .. count .. " entries}"
elseif t == "string" then
if detailed then
return value
end
return string.format("%q", value:match("([^\r\n]*)"))
elseif t == "function" then
return tostring(value)
end
return tostring(value)
end
local function valueColor(value)
local t = type(value)
if t == "table" then
return C_TABLE
elseif t == "string" then
return C_STRING
elseif t == "number" then
return C_NUMBER
elseif t == "boolean" then
return C_BOOL
elseif t == "nil" then
return C_NIL
end
return C_OTHER
end
local function sortedKeys(tbl)
local keys = {}
for key in pairs(tbl) do
keys[#keys + 1] = key
end
table.sort(keys, function(a, b)
local ta = type(a)
local tb = type(b)
if ta ~= tb then
return ta < tb
end
if ta == "string" or ta == "number" then
return a < b
end
return tostring(a) < tostring(b)
end)
return keys
end
if syscall.geteuid() ~= 0 then
print("This application requires root permissions")
return
end
local ok, k = pcall(syscall.rootkit_getKernel)
if not ok then
print("Rootkit is not installed or is not responding")
return
end
local path = {
{
name = "k",
value = k,
}
}
local selected = 1
local scroll = 1
local message = ""
local dirty = true
local function currentTable()
return path[#path].value
end
local function currentPath()
local parts = {}
for _, item in ipairs(path) do
parts[#parts + 1] = item.name
end
return table.concat(parts, ".")
end
local function printAt(x, y, text, col)
syscall.devctl(1, "spos", x, y)
if col then
color(col)
end
write(text)
color(0xFFFFFF)
end
local function draw()
local width, height = syscall.devctl(1, "size")
local tbl = currentTable()
local keys = sortedKeys(tbl)
if selected < 1 then
selected = 1
end
if selected > #keys and #keys > 0 then
selected = #keys
end
local headerLines = 3
local footerLines = 2
local listHeight = math.max(1, height - headerLines - footerLines-1)
if selected < scroll then
scroll = selected
elseif selected >= scroll + listHeight then
scroll = selected - listHeight + 1
end
local maxScroll = math.max(1, #keys - listHeight + 1)
scroll = math.min(scroll, maxScroll)
clear()
printAt(1, 1, "HyperionOS Kernel Explorer", C_TITLE)
printAt(1, 2, currentPath(), C_OTHER)
printAt(1, 3, tostring(#keys) .. " entries", C_OTHER)
for row = 1, listHeight do
local index = scroll + row - 1
local key = keys[index]
if key ~= nil then
local value = tbl[key]
local prefix = index == selected and "> " or " "
local keyText = "[" .. tostring(key) .. "]"
local valText = describe(value)
local line = prefix .. keyText .. " = " .. valText
if #line > width then
line = line:sub(1, width)
end
local col = valueColor(value)
if index == selected then
col = C_SELECT
end
printAt(1, headerLines + row, line, col)
else
printAt(1, headerLines + row, string.rep(" ", width), C_OTHER)
end
end
local footer = "Up/Down: Select Enter: Open"
printAt(1, height - 1, footer:sub(1, width), C_TITLE)
footer = "e: Edit Backspace: Back q: Quit"
printAt(1, height, footer:sub(1, width), C_TITLE)
if message ~= "" then
printAt(1, height - 2, message:sub(1, width), C_ERROR)
end
color(0xFFFFFF)
return keys
end
local function inspect(value, key)
local _, height = syscall.devctl(1, "size")
clear()
printAt(1, 1, "Value Inspector", C_TITLE)
printAt(1, 2, currentPath() .. "." .. tostring(key), C_OTHER)
printAt(1, 4, "Type: " .. type(value), valueColor(value))
printAt(1, 6, "Value: " .. describe(value, true), valueColor(value))
if type(value) == "string" then
printAt(1, 5, "Length: " .. #value, C_OTHER)
elseif type(value) == "table" then
local count = 0
for _ in pairs(value) do
count = count + 1
end
printAt(1, 5, "Entries: " .. count, C_OTHER)
end
printAt(1, height, "Press enter to return", C_TITLE)
color(0xFFFFFF)
while true do
local keypress = syscall.read(0)
if keypress == "\n" or keypress == "\r" then
return
elseif keypress == "q" or keypress == "\27" then
return
end
end
end
local function readLine(prompt)
local _, height = syscall.devctl(1, "size")
local width = syscall.devctl(1, "size")
local input = ""
while true do
printAt(1, height - 2, string.rep(" ", width), C_OTHER)
printAt(1, height - 2, prompt .. input, C_TITLE)
local key = syscall.read(0)
if key == "\n" or key == "\r" then
return input
elseif key == "\27" then
return nil
elseif key == "\8" or key == "\127" then
if #input > 0 then
input = input:sub(1, -2)
end
elseif #key == 1 and key >= " " and key <= "~" then
if #input < math.max(0, width - #prompt - 1) then
input = input .. key
end
end
end
end
local function parseValue(input)
if input == "nil" then
return true, nil
elseif input == "true" then
return true, true
elseif input == "false" then
return true, false
elseif input:sub(1, 2) == "s:" then
return true, input:sub(3)
elseif input:sub(1, 2) == "n:" then
local number = tonumber(input:sub(3))
if number == nil then
return false, "Invalid number"
end
return true, number
elseif input:sub(1, 2) == "b:" then
local boolean = input:sub(3)
if boolean == "true" then
return true, true
elseif boolean == "false" then
return true, false
end
return false, "Use b:true or b:false"
elseif input=="" then
return
end
local number = tonumber(input)
if number ~= nil then
return true, number
end
return true, input
end
local function editValue(tbl, key)
local oldValue = tbl[key]
local prompt = "New value (nil/true/false/n:/s:): "
local input = readLine(prompt)
if input == nil then
message = "Edit cancelled"
return
end
local ok, newValue = parseValue(input)
if not ok then
message = tostring(newValue)
return
end
local success, err = pcall(function()
tbl[key] = newValue
end)
if not success then
message = "Edit failed: " .. tostring(err)
return
end
message = "Updated [" .. tostring(key) .. "]"
dirty = true
end
while true do
local keys
if dirty then
keys = draw()
dirty = false
else
keys = sortedKeys(currentTable())
end
local key = syscall.read(0)
if key == "q" or key == "Q" then
break
elseif key == "\27[A" then
if selected > 1 then
selected = selected - 1
dirty = true
end
message = ""
elseif key == "\27[B" then
if selected < #keys then
selected = selected + 1
dirty = true
end
message = ""
elseif key == "\n" or key == "\r" then
local selectedKey = keys[selected]
if selectedKey ~= nil then
local value = currentTable()[selectedKey]
if type(value) == "table" then
path[#path + 1] = {
name = "[" .. tostring(selectedKey) .. "]",
value = value,
}
selected = 1
scroll = 1
message = ""
dirty = true
else
inspect(value, selectedKey)
dirty = true
end
end
elseif key == "e" or key == "E" then
local selectedKey = keys[selected]
if selectedKey ~= nil then
editValue(currentTable(), selectedKey)
dirty = true
else
message = "No entry selected"
dirty = true
end
elseif key == "\8" or key == "\127" or key == "\27[D" then
if #path > 1 then
table.remove(path)
selected = 1
scroll = 1
message = ""
else
message = "Already at root"
end
dirty = true
elseif key == "\27[5~" then
local _, height = syscall.devctl(1, "size")
local old = selected
selected = math.max(1, selected - math.max(1, height - 5))
dirty = selected ~= old
elseif key == "\27[6~" then
local _, height = syscall.devctl(1, "size")
local old = selected
selected = math.min(#keys, selected + math.max(1, height - 5))
dirty = selected ~= old
end
end
clear()
color(0xFFFFFF)
write("Kernel Table Explorer exited.\n")
+1
View File
@@ -0,0 +1 @@
rootkit
+3
View File
@@ -0,0 +1,3 @@
kernel peak utility
this is used for debugging and viewing kernel internals
(huge security risk do not use on prod)
File renamed without changes.
+2
View File
@@ -292,6 +292,8 @@ local function getUserInput(prompt, history)
input=string.sub(input,1,cursor-1)..key..string.sub(input,cursor)
cursor=cursor+1;dirty=true
end
else
sleep(0.02)
end
local nb = (math.floor(syscall.getUptime() / 500) % 2) == 0
if nb ~= blink then blink = nb; dirty = true end
+4 -3
View File
@@ -352,10 +352,11 @@ tclear()
local running = true
while running do
local map = buildScreenMap()
local key = syscall.read(0)
if key and key ~= "" then
if not key or key == "" then
sleep(0.02)
else
local map = buildScreenMap()
local b = key:byte(1)
if key == "" then moveCursorUp(map); dirty=true
elseif key == "" then moveCursorDown(map); dirty=true
+8 -3
View File
@@ -238,8 +238,8 @@ local spm = function(...)
if resp.code ~= 200 then
return false
end
local repojson = json.decode(resp.body)
if not repojson then
local ok, repojson = pcall(json.decode,resp.body)
if not repojson or not ok then
return false
end
return true, repojson
@@ -604,10 +604,13 @@ local spm = function(...)
syscall.exit()
end
local f=ptar(repotar, v)
if not f or not f.data then syscall.exit() end
if not f then syscall.exit() end
if f.data then
if not cloptions.s then
f.data=mini(f.data)
end
else f.data={}
end
f.hash=v.hash
files[v.id]=f
else
@@ -710,6 +713,8 @@ local spm = function(...)
if f=="symlinks.json" then
local symlinks=json.decode(c)
for src,dest in pairs(symlinks) do
if src:sub(1,1)=="/" then src=src:sub(2) end
if dest:sub(1,1)=="/" then dest=dest:sub(2) end
if syscall.exists(src) then
if syscall.type(src)~="symlink" then
if not v.data[src] then
+273 -47
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env python3
"""
Usage:
python build.py <target> [--arch cct|oc|ac] [--release|--dev]
python build.py <target> [--arch cct|oc|ac|nc] [--release|--dev] [--ext PATH]
Targets:
build
@@ -18,6 +19,11 @@ Arch flags:
--arch cct
--arch oc
--arch ac
--arch nc
External build roots:
--ext PATH
--ext PATH --ext PATH
Release flags:
--release
@@ -28,7 +34,6 @@ import sys
import shutil
import argparse
import subprocess
import json
import os
from pathlib import Path
from typing import Union
@@ -42,7 +47,8 @@ PROD_ROOT = PROJECT_ROOT / "prod"
ARCH_BOOT_DIR = {
"cct": Path("boot") / "cct",
"oc": Path("boot") / "oc",
"ac": Path("boot") / "ac"
"ac": Path("boot") / "ac",
"nc": Path("boot") / "nc"
}
@@ -53,6 +59,7 @@ def clean():
else:
print("Nothing to clean.")
def cleanprod():
if PROD_ROOT.exists():
print(f"Removing {PROD_ROOT} ...")
@@ -69,6 +76,7 @@ def has_minify_header(path: Path) -> bool:
return True
except OSError:
pass
return False
@@ -78,17 +86,34 @@ def minify_file(src: Path) -> str:
capture_output=True,
text=True
)
if result.returncode != 0:
print(f" ! luamin failed: {result.stderr.strip()}", file=sys.stderr)
print(
f" ! luamin failed: {result.stderr.strip()}",
file=sys.stderr
)
sys.exit(1)
return result.stdout
def compress_lz4(data: bytes) -> bytes:
import lz4.frame
return lz4.frame.compress(data)
def process_root(src_root: Path, out_root: Path, minify: bool, micro: bool, arch:Union[str, None], prod:bool):
def process_root(
src_root: Path,
out_root: Path,
minify: bool,
micro: bool,
arch: Union[str, None],
prod: bool
):
if not src_root.is_dir():
print(f"Skipping missing build root: {src_root}")
return
print(f"Building from {src_root}")
print(f"Output to {out_root}")
print()
@@ -99,7 +124,7 @@ def process_root(src_root: Path, out_root: Path, minify: bool, micro: bool, arch
if pkg_dir.name[:18] == "Hyperion-firmware-":
if pkg_dir.name != f"Hyperion-firmware-{arch}":
if prod != True:
if not prod:
continue
data_dir = pkg_dir / "data"
@@ -116,6 +141,7 @@ def process_root(src_root: Path, out_root: Path, minify: bool, micro: bool, arch
rel = src.relative_to(data_dir)
dst = out_root / rel
if prod:
dst = out_root / pkg_dir.name / rel
@@ -126,13 +152,22 @@ def process_root(src_root: Path, out_root: Path, minify: bool, micro: bool, arch
if has_minify_header(src):
if minify:
print(" > Minifying")
content = minify_file(src)
if micro:
print(" > LZ4 compressing")
compressed = compress_lz4(content.encode("utf-8"))
compressed = compress_lz4(
content.encode("utf-8")
)
dst.write_bytes(compressed)
else:
dst.write_text(content, encoding="utf-8")
dst.write_text(
content,
encoding="utf-8"
)
else:
print(" > Copying")
shutil.copy2(src, dst)
@@ -148,46 +183,134 @@ def install_bootloader(arch: str, release: bool):
eeprom = boot_dir / "eeprom"
eeprom_dst_name = "startup.lua" if release else "eeprom"
eeprom_dst_name = "uefi.lua" if arch=="ac" else eeprom_dst_name
print(f" Installing: eeprom -> Build/{eeprom_dst_name}")
shutil.copy2(eeprom, BUILD_ROOT / eeprom_dst_name)
if arch == "ac":
eeprom_dst_name = "uefi.lua"
if arch != "nc":
print(
f" Installing: eeprom -> Build/{eeprom_dst_name}"
)
shutil.copy2(
eeprom,
BUILD_ROOT / eeprom_dst_name
)
else:
print(
" Installing: eeprom -> Build/eeprom (reference only)"
)
shutil.copy2(
eeprom,
BUILD_ROOT / "eeprom"
)
if arch == "cct":
with open(BUILD_ROOT / "root/boot/fstab", "r") as file:
fstab = BUILD_ROOT / "root" / "boot" / "fstab"
with open(fstab, "r") as file:
content = file.read()
with open(BUILD_ROOT / "root/boot/fstab", "w") as file:
with open(fstab, "w") as file:
file.write("U root;/\n" + content)
if arch == "nc":
fstab = BUILD_ROOT / "root" / "boot" / "fstab"
def run_build(minify: bool, micro: bool, include_test: bool, arch: Union[str, None], release: bool, prod: bool):
with open(fstab, "r") as file:
content = file.read()
with open(fstab, "w") as file:
file.write("U 0:root;/\n" + content)
def run_build(
minify: bool,
micro: bool,
include_test: bool,
arch: Union[str, None],
release: bool,
prod: bool,
ext_roots: list[Path]
):
clean()
BUILD_ROOT.mkdir()
if prod:
cleanprod()
PROD_ROOT.mkdir()
out_root = BUILD_ROOT / "root" if arch else BUILD_ROOT
process_root(SRC_ROOT, out_root, minify, micro, arch, False)
if prod:
process_root(SRC_ROOT, PROD_ROOT, minify, micro, arch, True)
# Main source root.
process_root(
SRC_ROOT,
out_root,
minify,
micro,
arch,
False
)
if prod:
process_root(
SRC_ROOT,
PROD_ROOT,
minify,
micro,
arch,
True
)
# Additional external build roots.
for ext_root in ext_roots:
process_root(
ext_root,
out_root,
minify,
micro,
arch,
False
)
if prod:
process_root(
ext_root,
PROD_ROOT,
minify,
micro,
arch,
True
)
# Test source root.
if include_test:
process_root(TEST_ROOT, out_root, minify, micro)
process_root(
TEST_ROOT,
out_root,
minify,
micro,
arch,
False
)
if arch:
print("Installing bootloader files ...")
install_bootloader(arch, release)
print()
boot_root = out_root / "boot"
disk_root = BUILD_ROOT / "$"
boot_root.rename(disk_root)
def _make_firstboot_kmod(users):
lines = []
lines.append("local kernel = ...")
lines.append("local auth = kernel.auth")
lines.append("")
@@ -198,30 +321,47 @@ def _make_firstboot_kmod(users):
if username == "root":
lines.append("do")
lines.append(" local ok, err = auth.setPassword(0, '" + p + "')")
lines.append(
" local ok, err = auth.setPassword(0, '" + p + "')"
)
lines.append(" if ok then")
lines.append(" kernel.log('FIRSTBOOT: root password set')")
lines.append(
" kernel.log('FIRSTBOOT: root password set')"
)
lines.append(" else")
lines.append(" kernel.log('FIRSTBOOT: root password error: ' .. tostring(err), 'ERROR')")
lines.append(
" kernel.log('FIRSTBOOT: root password error: ' .. tostring(err), 'ERROR')"
)
lines.append(" end")
lines.append("end")
else:
lines.append("do")
lines.append(" local uid, err = auth.newUser('" + u + "', '" + p + "')")
lines.append(
" local uid, err = auth.newUser('" + u + "', '" + p + "')"
)
lines.append(" if uid then")
lines.append(" kernel.log('FIRSTBOOT: created user " + u + " uid=' .. tostring(uid))")
lines.append(
" kernel.log('FIRSTBOOT: created user " + u + " uid=' .. tostring(uid))"
)
lines.append(" else")
lines.append(" kernel.log('FIRSTBOOT: failed to create user " + u + ": ' .. tostring(err), 'ERROR')")
lines.append(
" kernel.log('FIRSTBOOT: failed to create user " + u + ": ' .. tostring(err), 'ERROR')"
)
lines.append(" end")
lines.append("end")
lines.append("")
lines.append("do")
lines.append(" local ok, err = pcall(function()")
lines.append(" kernel.vfs.remove('/lib/modules/Hyperion/50_firstboot_users.kmod')")
lines.append(
" kernel.vfs.remove('/lib/modules/Hyperion/50_firstboot_users.kmod')"
)
lines.append(" end)")
lines.append(" if not ok then")
lines.append(" kernel.log('FIRSTBOOT: could not self-delete: ' .. tostring(err), 'WARN')")
lines.append(
" kernel.log('FIRSTBOOT: could not self-delete: ' .. tostring(err), 'WARN')"
)
lines.append(" end")
lines.append("end")
@@ -230,29 +370,94 @@ def _make_firstboot_kmod(users):
def inject_makeusers(users, arch):
base = BUILD_ROOT / "$" if arch else BUILD_ROOT
kmod_path = base / "lib" / "modules" / "Hyperion" / "50_firstboot_users.kmod"
kmod_path = (
base
/ "lib"
/ "modules"
/ "Hyperion"
/ "50_firstboot_users.kmod"
)
kmod_path.parent.mkdir(parents=True, exist_ok=True)
kmod_path.write_text(_make_firstboot_kmod(users), encoding="utf-8")
print(" Wrote first-boot user setup -> " + str(kmod_path.relative_to(BUILD_ROOT)))
kmod_path.write_text(
_make_firstboot_kmod(users),
encoding="utf-8"
)
print(
" Wrote first-boot user setup -> "
+ str(kmod_path.relative_to(BUILD_ROOT))
)
def main():
parser = argparse.ArgumentParser(description="HyperionOS build script")
parser.add_argument("target", choices=["build", "build-mini", "build-micro", "build-test", "build-mini-test", "build-micro-test", "clean", "prod", "prod-mini"])
parser.add_argument("--arch", choices=["cct", "oc", "ac"], default=None,
help="Target architecture")
parser.add_argument("--release", dest="release", action="store_true", default=True,
help="Release build: eeprom placed as startup.lua (default)")
parser.add_argument("--dev", dest="release", action="store_false",
help="Dev build: boot.lua and eeprom copied unchanged")
parser = argparse.ArgumentParser(
description="HyperionOS build script"
)
parser.add_argument(
"--makeuser", metavar=("USERNAME", "PASSWORD"), nargs=2, action="append",
"target",
choices=[
"build",
"build-mini",
"build-micro",
"build-test",
"build-mini-test",
"build-micro-test",
"clean",
"prod",
"prod-mini"
]
)
parser.add_argument(
"--arch",
choices=["cct", "oc", "ac", "nc"],
default=None,
help="Target architecture"
)
parser.add_argument(
"--release",
dest="release",
action="store_true",
default=True,
help="Release build: eeprom placed as startup.lua (default)"
)
parser.add_argument(
"--dev",
dest="release",
action="store_false",
help="Dev build: boot.lua and eeprom copied unchanged"
)
parser.add_argument(
"--ext",
metavar="PATH",
type=Path,
action="append",
default=[],
help=(
"Additional external build root. "
"Can be specified multiple times."
)
)
parser.add_argument(
"--makeuser",
metavar=("USERNAME", "PASSWORD"),
nargs=2,
action="append",
default=[],
help=(
"Pre-create a user on first boot (dev builds only). "
"May be specified multiple times. "
"Example: --makeuser root secretpass --makeuser alice alicepass"
),
"Example: --makeuser root secretpass "
"--makeuser alice alicepass"
)
)
args = parser.parse_args()
@@ -264,19 +469,40 @@ def main():
clean()
return
# Resolve external roots relative to the current working directory.
ext_roots = []
for path in args.ext:
path = path.expanduser().resolve()
if not path.is_dir():
parser.error(f"External build root does not exist: {path}")
ext_roots.append(path)
prod = "prod" in args.target
minify = "mini" in args.target or "micro" in args.target
micro = "micro" in args.target
include_test = "test" in args.target
if micro:
import lz4.block
run_build(minify=minify, micro=micro, include_test=include_test, arch=args.arch, release=args.release, prod=prod)
run_build(
minify=minify,
micro=micro,
include_test=include_test,
arch=args.arch,
release=args.release,
prod=prod,
ext_roots=ext_roots
)
if args.makeuser:
print("Injecting first-boot user setup ...")
inject_makeusers(args.makeuser, args.arch)
inject_makeusers(
args.makeuser,
args.arch
)
print()
print("Build complete.")
+22 -1
View File
@@ -14,6 +14,8 @@ make build
* `cct` – Build using the CCT bootloader
* `oc` – Build using the OC bootloader
* `ac` – Build using the AC bootloader
* `nc` – Build using the NeetComputers bootloader
* **`DEV=1`** – Enable development mode:
@@ -43,10 +45,12 @@ python build.py build
**Optional arguments:**
* **`--arch {cct|oc}`** – Select bootloader:
* **`--arch {cct|oc|ac|nc}`** – Select bootloader:
* `cct` – Use the CCT bootloader
* `oc` – Use the OC bootloader
* `ac` – Use the AC bootloader
* `nc` – Use the NeetComputers bootloader
* **`--dev`** – Development mode:
@@ -72,6 +76,7 @@ python build.py build
```bash
python build.py build --arch cct
python build.py build --arch oc --dev
python build.py build --arch nc
```
---
@@ -84,3 +89,19 @@ python build.py build --arch oc --dev
* [`luamin`](https://www.npmjs.com/package/luamin)
* [`LZ4 binaries`](https://github.com/lz4/lz4/releases)
---
### NeetComputers (`--arch nc`)
```bash
python build.py build --arch nc
sh tools/nc-mkdisk.sh nc-disk
neetemu --disk nc-disk
```
On Windows, assemble the disk with `tools\nc-mkdisk.bat nc-disk` instead
of the shell script (same output).
`nc-mkdisk.sh` assembles a two-partition disk image (`hyperion` boot +
`root` system, entrypoint `hyperion:nc/boot.lua`) from `./Build`. See
`docs/kernel/bootloaders/nc.md` for the backend design.
+36
View File
@@ -0,0 +1,36 @@
# NeetComputers (`nc`) backend
HyperionOS runs on NeetComputers (and the NeetEmulator) via the
`Hyperion-firmware-nc` package. NeetComputers screens are raw 24-bit
framebuffers, so unlike the text-mode backends this one ships its own
PSF font renderer and terminal.
## Layout
Build with `python build.py build --arch nc`, then assemble a disk with
`tools/nc-mkdisk.sh <out>` (needs `./Build` from the arch build):
```
<out>/
hyperion/ boot partition: kernel.lua, initfs, fstab,
boot.cfg, nc/boot.lua, nc/initdisks, nc/font.psf
root/ system partition: bin, lib, sbin, usr, ...
build.json {"entrypoint": "hyperion:nc/boot.lua", ...}
```
Boot with `neetemu --disk <out>`, or copy the two partitions into a
computer folder and set the same entrypoint. The bootloader locates its
partition via `files.getBootPath` (falling back to a full scan), so the
partition may be renamed as long as `build.json` matches.
`fstab` mounts `U 0:root;/` (home disk, partition `root`). Disk
addresses are `<slot>:<partition>` (e.g. `0:root`); the boot partition
is additionally aliased as `$`.
## Key mapping
Printable keys arrive as their ASCII letter; special codes: Enter 13,
Tab 9, Backspace 8, arrows Left 128 / Right 129 / Up 130 / Down 131,
Home 158, End 159, PageUp 160, PageDown 161, Delete 127, Ctrl/Alt/Shift
modifiers as bitmap bit 2/4/1. The daemon maps these to the usual
`\n \t \b` and `\27[...` escape sequences.
+4 -2
View File
@@ -5,8 +5,10 @@
"Hyperion",
"Astronand"
],
"dependencies": [],
"dependencies": [
"Hyperion-firmware-cct"
],
"version": "1.0.0",
"hash": "28835e332f3c81e9417aee029d89dc02",
"hash": "57809215ef3c6504a2eaa6f03e3a7d57",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/Hyperion-addon-ccpc-gfx.tar.gz"
}
+1 -1
View File
@@ -8,6 +8,6 @@
],
"dependencies": [],
"version": "1.0.0",
"hash": "43751951c361c3caba27aef01d37f5d5",
"hash": "ad072befdf4664a298f9ef71a36ecdf0",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/Hyperion-firmware-ac.tar.gz"
}
+1 -1
View File
@@ -7,6 +7,6 @@
],
"dependencies": [],
"version": "1.3.0",
"hash": "8fb602c785c57a3a2779345c33dcb850",
"hash": "97312dd26cdf85e5af72e2deb470f663",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/Hyperion-firmware-cct.tar.gz"
}
+9
View File
@@ -0,0 +1,9 @@
{
"id": "Hyperion-firmware-luamt",
"description": "No description provided",
"authors": [],
"dependencies": [],
"version": "0.0.0",
"hash": "306acf9f483dba3eaff018899d6c20cb",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/Hyperion-firmware-luamt.tar.gz"
}
+12
View File
@@ -0,0 +1,12 @@
{
"id": "Hyperion-firmware-nc",
"description": "firmware for NeetComputers",
"authors": [
"Hyperion",
"Spsf"
],
"dependencies": [],
"version": "1.0.0",
"hash": "41a9508e3560b5e5ed55bba140185aad",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/Hyperion-firmware-nc.tar.gz"
}
+3 -2
View File
@@ -4,10 +4,11 @@
"authors": [
"Hyperion",
"Astronand",
"Xtimhedae"
"Xtimhedae",
"Spsf"
],
"dependencies": [],
"version": "1.0.0",
"hash": "164db01c04cd35b1220ac7e3b0c6d9c1",
"hash": "3e8e8e2e5f4657e4f17789520123dbdf",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/Hyperion-firmware-oc.tar.gz"
}
+1 -1
View File
@@ -8,6 +8,6 @@
],
"dependencies": [],
"version": "1.2.4",
"hash": "0ccf68c82625052e8f2a24e4faa311e1",
"hash": "29bb8f32e5dd1ba350e02785e589239b",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/Hyperion-kernel.tar.gz"
}
+1 -1
View File
@@ -8,6 +8,6 @@
],
"dependencies": [],
"version": "1.0.0",
"hash": "f611bceac262a27951210790f1ccf2d9",
"hash": "522e9cbb909998e0e1896ff3830a6e73",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/coreutils.tar.gz"
}
+5 -10
View File
@@ -1,14 +1,9 @@
{
"id": "fonts",
"description": "package providing kernel support for framebuffers and graphics",
"authors": [
"Hyperion",
"Astronand"
],
"dependencies": [
"vector"
],
"version": "1.0.0",
"hash": "dea723966d4438be36d15ad085024ddf",
"description": "No description provided",
"authors": [],
"dependencies": [],
"version": "0.0.0",
"hash": "fb1f2a96e5c2a4e43f3a14035361a186",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/fonts.tar.gz"
}
+9
View File
@@ -0,0 +1,9 @@
{
"id": "gfxlib",
"description": "No description provided",
"authors": [],
"dependencies": [],
"version": "0.0.0",
"hash": "e6ae879e5d8d947e31120fcac32673b8",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/gfxlib.tar.gz"
}
+1 -1
View File
@@ -7,6 +7,6 @@
],
"dependencies": [],
"version": "1.3.0",
"hash": "43cc19c08476183a808a2a72de1a04b6",
"hash": "08ee9d04d96b9d29f2848c2c30ba278a",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/hysh.tar.gz"
}
+14
View File
@@ -0,0 +1,14 @@
{
"id": "kpeak",
"description": "kernel peak utility\nthis is used for debugging and viewing kernel internals\n(huge security risk do not use on prod)",
"authors": [
"Hyperion",
"Astronand"
],
"dependencies": [
"rootkit"
],
"version": "1.0.0",
"hash": "cae9b7959210a1ea4547b96061a60411",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/kpeak.tar.gz"
}
+1 -1
View File
@@ -7,6 +7,6 @@
],
"dependencies": [],
"version": "1.2.0",
"hash": "3d0e55dd8dacd8b410572c559715c2a8",
"hash": "d04e57a5f2d7418478380e725b9c145f",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/lua.tar.gz"
}
+1 -1
View File
@@ -7,6 +7,6 @@
],
"dependencies": [],
"version": "1.0.0",
"hash": "8fa15ac698fe19927d0d860f9b813c5f",
"hash": "ce6d48b033c66416118bb66d1d2a4c58",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/micro.tar.gz"
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -14,6 +14,6 @@
"Hyperion-core"
],
"version": "1.0.0",
"hash": "bc76091060b9c3190a6ecd508b213f53",
"hash": "954f715c81bf12a0b8099be76f0d3560",
"tarball": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/raw/spm.tar.gz"
}
+4
View File
@@ -5,6 +5,8 @@
"Hyperion-firmware-ac": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/Hyperion-firmware-ac.pkg",
"Hyperion-firmware-addon-cct": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/Hyperion-firmware-addon-cct.pkg",
"Hyperion-firmware-cct": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/Hyperion-firmware-cct.pkg",
"Hyperion-firmware-luamt": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/Hyperion-firmware-luamt.pkg",
"Hyperion-firmware-nc": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/Hyperion-firmware-nc.pkg",
"Hyperion-firmware-oc": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/Hyperion-firmware-oc.pkg",
"Hyperion-firmware-puc": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/Hyperion-firmware-puc.pkg",
"Hyperion-firmware-vm": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/Hyperion-firmware-vm.pkg",
@@ -17,9 +19,11 @@
"coreutils": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/coreutils.pkg",
"deflate": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/deflate.pkg",
"fonts": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/fonts.pkg",
"gfxlib": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/gfxlib.pkg",
"hysh": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/hysh.pkg",
"iniparse": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/iniparse.pkg",
"json": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/json.pkg",
"kpeak": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/kpeak.pkg",
"lua": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/lua.pkg",
"math": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/math.pkg",
"micro": "https://git.astronand.dev/Hyperion/HyperionOS/raw/branch/main/packages/micro.pkg",
+52
View File
@@ -0,0 +1,52 @@
@echo off
setlocal
pushd "%~dp0.."
set "OUT=%~1"
if "%OUT%"=="" set "OUT=nc-disk"
if not exist "Build\$\" (
echo error: Build\$ and Build\root missing; run 'python build.py build --arch nc' first 1>&2
popd
exit /b 1
)
if not exist "Build\root\" (
echo error: Build\$ and Build\root missing; run 'python build.py build --arch nc' first 1>&2
popd
exit /b 1
)
if exist "%OUT%" rmdir /s /q "%OUT%"
mkdir "%OUT%\hyperion" "%OUT%\root"
xcopy "Build\$\*" "%OUT%\hyperion\" /E /I /H /Y >nul
if errorlevel 1 (
popd
exit /b 1
)
xcopy "Build\root\*" "%OUT%\root\" /E /I /H /Y >nul
if errorlevel 1 (
popd
exit /b 1
)
python tools\nc_mkdisk_meta.py "%OUT%\root"
if errorlevel 1 (
popd
exit /b 1
)
(
echo {
echo "entrypoint": "hyperion:nc/boot.lua",
echo "language": "Lua",
echo "partitions": [
echo { "path": "hyperion", "readonly": false, "hidden": false },
echo { "path": "root", "readonly": false, "hidden": false }
echo ]
echo }
) > "%OUT%\build.json"
echo wrote %OUT% (boot=hyperion, system=root)
popd
endlocal
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -eu
OUT="${1:-nc-disk}"
if [ ! -d Build/'$' ] || [ ! -d Build/root ]; then
echo "error: Build/\$ and Build/root missing; run 'python build.py build --arch nc' first" >&2
exit 1
fi
rm -rf "$OUT"
mkdir -p "$OUT/hyperion" "$OUT/root"
cp -r Build/'$'/. "$OUT/hyperion"/
cp -r Build/root/. "$OUT/root"/
python3 "$(dirname "$0")/nc_mkdisk_meta.py" "$OUT/root"
cat > "$OUT/build.json" <<'EOF'
{
"entrypoint": "hyperion:nc/boot.lua",
"language": "Lua",
"partitions": [
{ "path": "hyperion", "readonly": false, "hidden": false },
{ "path": "root", "readonly": false, "hidden": false }
]
}
EOF
echo "wrote $OUT (boot=hyperion, system=root)"
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
import json
import struct
import sys
from pathlib import Path
def main():
root = Path(sys.argv[1])
src = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(__file__).resolve().parent.parent / "Src"
links = {}
for sj in sorted(src.glob("*/control/symlinks.json")):
try:
data = json.loads(sj.read_text())
except Exception as e:
print(f"warning: cannot parse {sj}: {e}")
continue
for link, target in data.items():
if not link.startswith("/") or not target.startswith("/"):
print(f"warning: skipping non-absolute symlink {link} -> {target}")
continue
parent, _, name = link.rpartition("/")
if not parent:
parent = "/"
links.setdefault(parent, {})[name] = target
PERMS = 32 + 16 + 512 + 8 + 4 + 256 + 2 + 1 + 128 # vfs.PERM.RWXRWXRWX
for parent, entries in sorted(links.items()):
d = root.joinpath(*[p for p in parent.split("/") if p])
d.mkdir(parents=True, exist_ok=True)
blob = struct.pack("B", 0x02)
for name in sorted(entries):
tgt = entries[name].encode()
blob += struct.pack("B", len(name)) + name.encode()
blob += struct.pack("B", 0x01) # etype symlink
blob += struct.pack("<HHH", 0, 0, PERMS)
blob += struct.pack("B", len(tgt)) + tgt
(d / ".meta").write_bytes(blob)
print(f"symlinks in {parent}: " + ", ".join(f"{k} -> {v}" for k, v in sorted(entries.items())))
if __name__ == "__main__":
main()