16 Commits
Author SHA1 Message Date
Astronand 429a1489d2 Merge pull request '1.2 dev' (#24) from 1.2-dev into main
Reviewed-on: #24
2026-08-25 21:17:07 -04:00
Astronand 211b7fc75b Merge pull request '1.2 dev' (#23) from 1.2-dev into main
Reviewed-on: #23
2026-08-24 09:16:38 -04:00
Astronand 4e7cec2ce1 Merge pull request 'testing update' (#22) from 1.2-dev into main
Reviewed-on: #22
2026-08-21 07:36:55 -04:00
Astronand 7ddc527e00 Merge pull request '1.2 dev' (#21) from 1.2-dev into main
Reviewed-on: #21
2026-08-15 22:41:41 -04:00
Astronand 3a33bd0264 Merge pull request 'fix spm files' (#20) from 1.2-dev into main
Reviewed-on: #20
2026-08-14 21:13:19 -04:00
Astronand 242762ab6b Merge pull request '1.2 dev' (#19) from 1.2-dev into main
Reviewed-on: #19
2026-08-14 20:47:25 -04:00
Astronand 8c18d89489 Merge pull request '1.2-dev' (#18) from 1.2-dev into main
Reviewed-on: #18
2026-03-21 01:12:24 -04:00
Astronand 041663e1e8 Merge pull request 'made newer installer that does not require tar stuff' (#17) from 1.2-dev into main
Reviewed-on: #17
2026-03-21 00:57:16 -04:00
Astronand fcac0ff8d8 Merge pull request 'made system use full salt+pepper' (#16) from 1.2-dev into main
Reviewed-on: #16
2026-03-19 14:11:24 -04:00
Astronand d98555328b Merge pull request '1.2-dev' (#15) from 1.2-dev into main
Reviewed-on: #15
2026-03-19 12:19:44 -04:00
Astronand 61cbb91db2 Merge branch '1.2-dev' 2026-03-19 11:28:56 -04:00
Astronand b79492dbb8 Merge branch 'main' of https://git.astronand.dev/Hyperion/HyperionOS 2026-03-19 11:28:29 -04:00
Astronand bc87c53427 Merge branch '1.2-dev' 2026-03-19 11:28:28 -04:00
Astronand 030e5bfd96 Update install/data/tarbad 2026-03-12 20:59:36 -04:00
Astronand 099638c735 Merge pull request 'update tar' (#12) from 1.2-dev into main
Reviewed-on: #12
2026-03-12 20:55:22 -04:00
Astronand 5172da1b5b Merge pull request '1.2-dev' (#11) from 1.2-dev into main
Reviewed-on: #11
2026-03-12 19:32:16 -04:00
180 changed files with 5740 additions and 6067 deletions

No files matched your search

+2 -2
View File
@@ -6,10 +6,10 @@
"printf", "printf",
"printInline", "printInline",
"toHex", "toHex",
"loadcstr",
"userinput" "userinput"
], ],
"Lua.diagnostics.disable": [ "Lua.diagnostics.disable": [
"need-check-nil", "need-check-nil"
"param-type-mismatch"
] ]
} }
@@ -1,318 +0,0 @@
--:Minify:--
local kernel=...
if not kernel.cct then return end
local plt={
[0]=0x000000,0x0b0b0b,0x222222,0x444444,0x555555,0x777777,0x888888,0xaaaaaa,
0xbbbbbb,0xdddddd,0xeeeeee,0x00000b,0x000022,0x000044,0x000055,0x000077,
0x000088,0x0000aa,0x0000bb,0x0000dd,0x0000ee,0x000b00,0x002200,0x004400,
0x005500,0x007700,0x008800,0x00aa00,0x00bb00,0x00dd00,0x00ee00,0x0b0000,
0x220000,0x440000,0x550000,0x770000,0x880000,0xaa0000,0xbb0000,0xdd0000,
0xee0000,0x000033,0x000066,0x000099,0x0000cc,0x0000ff,0x003300,0x003333,
0x003366,0x003399,0x0033cc,0x0033ff,0x006600,0x006633,0x006666,0x006699,
0x0066cc,0x0066ff,0x009900,0x009933,0x009966,0x009999,0x0099cc,0x0099ff,
0x00cc00,0x00cc33,0x00cc66,0x00cc99,0x00cccc,0x00ccff,0x00ff00,0x00ff33,
0x00ff66,0x00ff99,0x00ffcc,0x00ffff,0x330000,0x330033,0x330066,0x330099,
0x3300cc,0x3300ff,0x333300,0x333333,0x333366,0x333399,0x3333cc,0x3333ff,
0x336600,0x336633,0x336666,0x336699,0x3366cc,0x3366ff,0x339900,0x339933,
0x339966,0x339999,0x3399cc,0x3399ff,0x33cc00,0x33cc33,0x33cc66,0x33cc99,
0x33cccc,0x33ccff,0x33ff00,0x33ff33,0x33ff66,0x33ff99,0x33ffcc,0x33ffff,
0x660000,0x660033,0x660066,0x660099,0x6600cc,0x6600ff,0x663300,0x663333,
0x663366,0x663399,0x6633cc,0x6633ff,0x666600,0x666633,0x666666,0x666699,
0x6666cc,0x6666ff,0x669900,0x669933,0x669966,0x669999,0x6699cc,0x6699ff,
0x66cc00,0x66cc33,0x66cc66,0x66cc99,0x66cccc,0x66ccff,0x66ff00,0x66ff33,
0x66ff66,0x66ff99,0x66ffcc,0x66ffff,0x990000,0x990033,0x990066,0x990099,
0x9900cc,0x9900ff,0x993300,0x993333,0x993366,0x993399,0x9933cc,0x9933ff,
0x996600,0x996633,0x996666,0x996699,0x9966cc,0x9966ff,0x999900,0x999933,
0x999966,0x999999,0x9999cc,0x9999ff,0x99cc00,0x99cc33,0x99cc66,0x99cc99,
0x99cccc,0x99ccff,0x99ff00,0x99ff33,0x99ff66,0x99ff99,0x99ffcc,0x99ffff,
0xcc0000,0xcc0033,0xcc0066,0xcc0099,0xcc00cc,0xcc00ff,0xcc3300,0xcc3333,
0xcc3366,0xcc3399,0xcc33cc,0xcc33ff,0xcc6600,0xcc6633,0xcc6666,0xcc6699,
0xcc66cc,0xcc66ff,0xcc9900,0xcc9933,0xcc9966,0xcc9999,0xcc99cc,0xcc99ff,
0xcccc00,0xcccc33,0xcccc66,0xcccc99,0xcccccc,0xccccff,0xccff00,0xccff33,
0xccff66,0xccff99,0xccffcc,0xccffff,0xff0000,0xff0033,0xff0066,0xff0099,
0xff00cc,0xff00ff,0xff3300,0xff3333,0xff3366,0xff3399,0xff33cc,0xff33ff,
0xff6600,0xff6633,0xff6666,0xff6699,0xff66cc,0xff66ff,0xff9900,0xff9933,
0xff9966,0xff9999,0xff99cc,0xff99ff,0xffcc00,0xffcc33,0xffcc66,0xffcc99,
0xffcccc,0xffccff,0xffff00,0xffff33,0xffff66,0xffff99,0xffffcc,0xffffff,
}
local iplt={}
for i=0, #plt do
iplt[plt[i]]=i
end
local l1f,l1d,l2,ops={},{},{},0
local function findClosest(tbl, target)
local closest = nil
local smallestDiff = math.huge
for k, _ in pairs(tbl) do
if k==target then return k end
local diff = math.abs(k - target)
if diff < smallestDiff then
smallestDiff = diff
closest = k
end
end
return closest
end
local function aprox(c24)
ops = ops + 1
if ops % 1024 == 0 then
l1d = {}
l1f = {}
end
if ops % 8192 == 0 then
l2 = {}
end
if l2[c24] ~= nil then
return l2[c24]
end
if l1d[c24] ~= nil then
l1f[c24] = l1f[c24] + 1
if l1f[c24] >= 16 then
l2[c24] = l1d[c24]
l1d[c24] = nil
l1f[c24] = nil
return l2[c24]
end
return l1d[c24]
end
local closestKey = findClosest(iplt, c24)
if not closestKey then return nil end
local value = iplt[closestKey]
l1d[c24] = value
l1f[c24] = 1
return value
end
local function splitFramebufferToStrings(fb, w)
local rows = {}
for i = 1, #fb, w do
local row_chars = {}
for j = 0, w - 1 do
local val = fb[i + j]
if val ~= nil then
table.insert(row_chars, string.char(aprox(val)))
else
break
end
end
table.insert(rows, table.concat(row_chars))
end
return rows
end
local function creategfx(term, id)
local active=false
term.setGraphicsMode(2)
for i=0, #plt do
term.setPaletteColor(i,plt[i])
end
term.setGraphicsMode(false)
term.setPaletteColor(0x1, 0xFFFFFF)
term.setPaletteColor(0x2, 0xFF0000)
term.setPaletteColor(0x4, 0x00FF00)
term.setPaletteColor(0x8, 0x0000FF)
term.setPaletteColor(0x10, 0x00FFFF)
term.setPaletteColor(0x20, 0xFF00FF)
term.setPaletteColor(0x40, 0xFFFF00)
term.setPaletteColor(0x80, 0xFF6D00)
term.setPaletteColor(0x100, 0x6DFF55)
term.setPaletteColor(0x200, 0x24FFFF)
term.setPaletteColor(0x400, 0x924900)
term.setPaletteColor(0x800, 0x6D6D55)
term.setPaletteColor(0x1000, 0xDBDBAA)
term.setPaletteColor(0x2000, 0x6D00FF)
term.setPaletteColor(0x4000, 0xB6FF00)
term.setPaletteColor(0x8000, 0x000000)
local handle={
gplt=function()
return setmetatable({},{__index=plt,__usermeta=false,__pairs=function() return pairs(plt) end})
end,
spixel=function(x,y,c)
term.setPixel(x,y,aprox(c))
end,
gpixel=function(x,y)
return term.getPixel(x,y)
end,
drawFB=function(x,y,fb,w)
local f=splitFramebufferToStrings(fb,w)
term.drawPixels(x,y,f)
end,
box=function(x,y,w,h,c,fill)
c=aprox(c)
if not fill then
term.drawPixels(x,y,c,w,1)
term.drawPixels(x,y,c,1,h)
term.drawPixels(x+w-1,y,c,1,h)
term.drawPixels(x,y+h-1,c,w,1)
else
term.drawPixels(x,y,c,w,h)
end
end,
circle=function(xc,yc,r,c,fill)
c=aprox(c)
if not fill then
local x = 0
local y = r
local d = 3 - 2 * r
-- Helper function to plot all 8 symmetric points
local function plot8Points(x, y)
term.setPixel(xc + x, yc + y, c)
term.setPixel(xc - x, yc + y, c)
term.setPixel(xc + x, yc - y, c)
term.setPixel(xc - x, yc - y, c)
term.setPixel(xc + y, yc + x, c)
term.setPixel(xc - y, yc + x, c)
term.setPixel(xc + y, yc - x, c)
term.setPixel(xc - y, yc - x, c)
end
plot8Points(x, y)
while y >= x do
x = x + 1
if d > 0 then
y = y - 1
d = d + 4 * (x - y) + 10
else
d = d + 4 * x + 6
end
plot8Points(x, y)
end
else
local x = 0
local y = r
local d = 3 - 2 * r
-- Helper to fill rows using symmetry
local function fillRows(x, y)
-- Width is (2 * coordinate) + 1 to include the center column
local strX = string.rep(string.char(c), 2 * x + 1)
local strY = string.rep(string.char(c), 2 * y + 1)
-- Draw the horizontal spans
term.drawPixels(xc - x, yc + y, {strX})
term.drawPixels(xc - x, yc - y, {strX})
term.drawPixels(xc - y, yc + x, {strY})
term.drawPixels(xc - y, yc - x, {strY})
end
fillRows(x, y)
while y >= x do
x = x + 1
if d > 0 then
y = y - 1
d = d + 4 * (x - y) + 10
else
d = d + 4 * x + 6
end
fillRows(x, y)
end
end
end,
line=function(x1,y1,x2,y2,c)
x1=math.floor(x1+0.5)
y1=math.floor(y1+0.5)
x2=math.floor(x2+0.5)
y2=math.floor(y2+0.5)
c=aprox(c)
local w,h=term.getSize(2)
local dx=math.abs(x2-x1)
local dy=math.abs(y2-y1)
local sx=x1<x2 and 1 or -1
local sy=y1<y2 and 1 or -1
local err=dx-dy
while true do
if 0<x1 and x1<=w and 0<y1 and y1<=h then
term.setPixel(x1,y1,c)
end
if x1==x2 and y1==y2 then
break
end
local e2=2*err
if e2>-dy then
err=err-dy
x1=x1+sx
end
if e2<dx then
err=err+dx
y1=y1+sy
end
end
end,
setMode=function(state)
if state then
term.setGraphicsMode(2)
for i=0, #plt do
term.setPaletteColor(i,plt[i])
end
active=true
else
term.setGraphicsMode(false)
term.setPaletteColor(0x1, 0xFFFFFF)
term.setPaletteColor(0x2, 0xFF0000)
term.setPaletteColor(0x4, 0x00FF00)
term.setPaletteColor(0x8, 0x0000FF)
term.setPaletteColor(0x10, 0x00FFFF)
term.setPaletteColor(0x20, 0xFF00FF)
term.setPaletteColor(0x40, 0xFFFF00)
term.setPaletteColor(0x80, 0xFF6D00)
term.setPaletteColor(0x100, 0x6DFF55)
term.setPaletteColor(0x200, 0x24FFFF)
term.setPaletteColor(0x400, 0x924900)
term.setPaletteColor(0x800, 0x6D6D55)
term.setPaletteColor(0x1000, 0xDBDBAA)
term.setPaletteColor(0x2000, 0x6D00FF)
term.setPaletteColor(0x4000, 0xB6FF00)
term.setPaletteColor(0x8000, 0x000000)
active=false
end
end,
getMode=function()
return active
end,
size=function()
return term.getSize(2)
end,
drawRun=function(y,x1,x2,c)
term.drawPixels(x1,y,c,{string.rep(string.char(aprox(c)),x1-x2)})
end
}
return handle
end
for id,obj in pairs(kernel.cct.term) do
if obj.setGraphicsMode then
kernel.cct.gfx[id]=creategfx(obj, id)
end
end
@@ -1 +0,0 @@
Hyperion-firmware-cct
+121 -3
View File
@@ -1,3 +1,121 @@
---@diagnostic disable-next-line: undefined-global local cp,c=component,computer;local b_addr=c.getBootAddress();local b_fs=cp.proxy(b_addr)
local bootdrive=__UEFI.bootDrive local gpu=cp.list("gpu")() and cp.proxy(cp.list("gpu")())
local e_rom=cp.list("eeprom")() and cp.proxy(cp.list("eeprom")())
local screens={}
for addr in cp.list("screen") do
if gpu then
gpu.bind(addr)
local w,h=gpu.maxResolution()
gpu.setResolution(w,h)
gpu.fill(1,1,w,h," ")
cp.proxy(addr).turnOn()
screens[#screens+1] = {cx=1,cy=1,w=w,h=h,addr=addr}
end
end
local function scroll(scr) gpu.copy(1,2,scr.w,scr.h-1,0,-1);gpu.fill(1,scr.h,scr.w,1," ") end
local function write(t)
if not gpu then return end
for s=1, #screens do
local scr=screens[s]
gpu.bind(scr.addr)
for i=1,#t do
local char=t: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;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);scr.cy=scr.cy-1 end
end
end
end
local function throw(err)
if gpu then
gpu.setBackground(0x0000AA);
gpu.setForeground(0xFFFFFF);
for i=1, #screens do
gpu.fill(1,1,screens[i].w,screens[i].h," ");
screens[i].cx,screens[i].cy=1,1;
end
write("CRITICAL KERNEL ERROR:\n"..tostring(err))
end
while true do c.pullSignal() end
end
local ok,err=xpcall(function()
local apis={}
local _l={coroutine=1,debug=1,_VERSION=1,assert=1,collectgarbage=1,error=1,getmetatable=1,ipairs=1,load=1,math=1,next=1,pairs=1,pcall=1,rawequal=1,rawget=1,rawlen=1,rawset=1,select=1,setmetatable=1,string=1,table=1,tonumber=1,tostring=1,type=1,xpcall=1,_G=1}
for k,v in pairs(_G) do if not _l[k] then apis[k]=v;_G[k]=nil end end
function sleep(t) local s=c.uptime()+t;while c.uptime()<s do c.pullSignal(s-c.uptime()) end end
local function getFile(path)
local h,err=b_fs.open(path,"r")
if not h then throw("Cannot open: "..path) end
local buf,chk="",""
repeat chk=b_fs.read(h,math.huge);buf=buf..(chk or "") until not chk
b_fs.close(h)
return buf
end
local Kernel=load(getFile("/kernel.lua"),"@Kernel")
local initFs=load(getFile("/oc/initdisks"),"@Init_disks")
local fs=load(getFile("/initfs"),"@InitFs")
if not Kernel then throw("Kernel load failed.") end
if initFs then initFs=initFs(apis, b_fs, b_addr) end
if fs then fs=fs() end
local eQ={}
local function qEv(e,...) table.insert(eQ,{e,...}) end
local efi={
getEpochMs=function() return math.floor(c.uptime()*1000) end,
getUptime=function() return c.uptime()*1000 end,
date=function() return tostring(apis.os.date()) end,
getMachineEvent=function()
if #eQ > 0 then
return table.unpack(table.remove(eQ, 1))
else
return nil
end
end,
getEEPROM=function() return e_rom and e_rom.get() or "" end,
setEEPROM=function(_,t) if e_rom then e_rom.set(t) end end,
getNvram=function() return e_rom and e_rom.getData() or "" end,
setNvram=function(_,t) if e_rom then e_rom.setData(t) end end,
beep=function(freq, timeMs) c.beep(freq, timeMs / 1000) end,
initfs=fs,
disks=initFs,
architecture="oc",
firmware=apis,
reboot=false,
yield=function() coroutine.yield() end,
screenCtl={
print=function(_,t) write(tostring(t).."\n") end,
printInline=function(_,t) write(tostring(t)) end,
clear=function() if gpu then for i=1, #screens do local scr=screens[i];gpu.bind(scr.addr);gpu.fill(1,1,scr.w,scr.h," ");scr.cx,scr.cy=1,1 end end end,
resetCursor=function() for i=1, #screens do local scr=screens[i];scr.cx,scr.cy=1,1 end end,
setBackgroundColor=function(_,cl) if gpu then gpu.setBackground(cl) end end,
setTextColor=function(_,cl) if gpu then gpu.setForeground(cl) end end,
enable=function() end,
disable=function() end
}
}
local kCo=coroutine.create(function()
local s,e=xpcall(Kernel,debug.traceback,efi)
if not s and not efi.reboot then throw(e) end
if efi.reboot then c.shutdown(true) else c.shutdown() end
end)
efi.screenCtl:print("Loaded in "..tostring(c.uptime()).."s")
while true do
local st,e=coroutine.resume(kCo)
c.pushSignal("NoSleep")
local ex=false
while not ex do
local ev={c.pullSignal(0)}
if ev[1]=="key_down" then qEv("keyPressed",1,ev[3]);qEv("keyTyped",1,string.char(ev[3]))
elseif ev[1]=="key_up" then qEv("keyReleased",1,ev[3])
end
if ev[1]=="NoSleep" then ex=true else qEv(table.unpack(ev)) end
end
if st=="error" or coroutine.status(kCo)=="dead" then
if efi.reboot then c.shutdown(true) end
throw("Kernel fault: "..tostring(e))
end
end
end,debug.traceback)
if not ok then throw("Boot fault: "..err) end
+59 -137
View File
@@ -1,146 +1,68 @@
local comp,disks,autocomplete,ev,ent,data,path,exit,dirty,ls,eb,sb,bp=components,{},false,nil,true,"","",false,true,{},false local init
local c,gpu=comp:getFirst("computer"),comp:getFirst("gpu") do
if gpu then sb=gpu:newBuffer(48,32) end local component_invoke = component.invoke
--c.nvram.data="1/ac/boot.lua" local function boot_invoke(address, method, ...)
local function resetScreens() local result = table.pack(pcall(component_invoke, address, method, ...))
sb=gpu:newBuffer(64,48) if not result[1] then
for typ, obj in comp:list() do return nil, result[2]
if typ=="screen" then gpu:assignBuffer(sb,obj) end
end
end
resetScreens()
local function displayError(err)
if not gpu then return end
gpu:freeAllBuffers()
resetScreens()
sb:pasteText(0,0,"FILL_SPILL",err)
end
local function bootloader()
for typ, obj in comp:list() do
if typ~="massStorage" then goto skip end
disks[tostring(obj.diskId)]=obj
::skip::
end
local function display(text)
print(text)
if not sb then print("NO_SB") return end
sb:pasteText(0,0,"FILL_SPILL",text)
end
local function boot()
local pos = path:find("/", 1, true)
if not pos then displayError("EINVAL") sleep(5) return end
local id,p = path:sub(1,pos-1),path:sub(pos)
if not disks[id] then displayError("ENODEV") sleep(5) return end
local init,err=load(disks[id]:open(p):read(-1),"@init","t",_G)
if err then displayError(err) sleep(5) return end
local ret = {xpcall(init, debug.traceback)}
if not ret[1] then
displayError("EFI PROGRAM ERROR: "..err)
sleep(5)
return false
else else
if ret[2]=="ENTER_BIOS" then return table.unpack(result, 2, result.n)
c.nvram.ENTER_BIOS=true
return true
end
return table.unpack(ret, 2)
end end
end end
if c.nvram then -- backwards compatibility, may remove later
path=c.nvram.data or "" local eeprom = component.list("eeprom")()
eb=c.nvram.ENTER_BIOS computer.getBootAddress = function()
c.nvram.ENTER_BIOS=false return boot_invoke(eeprom, "getData")
end end
computer.setBootAddress = function(address)
return boot_invoke(eeprom, "setData", address)
end
local function drainev() do
local screen = component.list("screen")()
local gpu = component.list("gpu")()
if gpu and screen then
boot_invoke(gpu, "bind", screen)
end
end
local function tryLoadFrom(address)
local handle, reason = boot_invoke(address, "open", "/oc/boot.lua")
if not handle then
return nil, reason
end
local buffer = ""
repeat repeat
ev={c:getMachineEvent()} local data, reason = boot_invoke(address, "read", handle, math.maxinteger or math.huge)
if ev[1]=="charTyped" then ent=false end if not data and reason then
until not ev[1] return nil, reason
end end
buffer = buffer .. (data or "")
if path=="" or eb then drainev() ent=false else until not data
display("Press key to enter boot menu...") boot_invoke(address, "close", handle)
sleep(3) return load(buffer, "=init")
drainev() end
if ent then return boot() end local reason
end if computer.getBootAddress() then
init, reason = tryLoadFrom(computer.getBootAddress())
local function proc(key) end
if key=="\n" then exit=true if not init then
elseif key=="\b" then path=path:sub(1,#path-1) dirty=true computer.setBootAddress()
elseif key=="\t" then print("autocomplete") for address in component.list("filesystem") do
else path=path..key dirty=true end init, reason = tryLoadFrom(address)
end if init then
computer.setBootAddress(address)
local function get() break
data="" end
local pos = path:find("/", 1, true)
local trailingslash=false
if path:sub(#path)=="/" then trailingslash=true end
if not pos then
for id in pairs(disks) do
if id:sub(1,#path)==path then
data=data..id.."\n"
end
end
else
if not trailingslash then
local n=""
for i=#path, 0, -1 do
if path:sub(i,i)~="/" then
n=path:sub(i,i)..n
else break end
end
local ok,ret=pcall(function()
return disks[path:sub(1,pos-1)]:list(path:sub(pos,#path-#n))
end)
if ok then
ls = ret
end
for _,p in ipairs(ls) do
if p:sub(1,#n) == n then
data=data..p.."\n"
end
end
else
local ok,ret=pcall(function()
return disks[path:sub(1,pos-1)]:list(path:sub(pos))
end)
if ok then
ls=ret
for _,p in ipairs(ls) do
data=data..p.."\n"
end
end
end
end end
end
if not init then
error("no bootable medium found" .. (reason and (": " .. tostring(reason)) or ""), 0)
end
end end
local ok, err = xpcall(init,debug.traceback)
if not ent then if not ok then
while true do error(err)
get()
if dirty then
for i=0,31 do sb:clearRow(i) end
display("Select boot file...\n"..path.."\n\n"..data)
dirty=false
end
ev={c:getMachineEvent()}
if ev[1]=="charTyped" then proc(ev[2]) end
if exit then return boot() end
end
end
end
local ret={xpcall(bootloader,debug.traceback)}
if not ret[1] then
displayError(ret[2])
error(ret[2])
else else
return table.unpack(ret, 2) return err
end end
@@ -1,2 +0,0 @@
--:Minify:--
local kernel=...
@@ -78,24 +78,15 @@ for addr, typ in kernel.oc.component.list("keyboard") do
elseif op=="open" then elseif op=="open" then
local h = { local h = {
read=function(amount) read=function(amount)
amount = amount or 1
local rv="" local rv=""
for i=1, amount do for i=1, amount or 1 do
local event = {kernel.oc.keyboards[addr].events.pop()} local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then if event[1] then
rv=rv..event[1] rv=rv..event[1]
else
break
end end
end end
if rv~="" then return rv end if rv=="" then rv=nil end
local task=kernel.currentTask return rv
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, end,
write=function(content) write=function(content)
end, end,
@@ -1,5 +0,0 @@
--:Minify:--
local kernel=...
if kernel.arch~="cct" then
kernel.deny("cc-tweaked/31_keyboards.kmod")
end
@@ -0,0 +1,387 @@
--:Minify:--
local BOOT_DRIVE_PATH = ({...})[1] or "/$"
---@diagnostic disable-next-line: undefined-global
local term = term
local os = os
local function write(text)
local x, y = term.getCursorPos()
local w, h = term.getSize()
for i = 1, #text do
local c = text:sub(i, i)
if c == "\n" then
y = y + 1
x = 1
elseif c == "\t" then
local tabSize = 4
local spaces = tabSize - ((x - 1) % tabSize)
term.write(string.rep(" ", spaces))
x = x + spaces
elseif c == "\b" then
if x > 1 then
x = x - 1
term.setCursorPos(x, y)
term.write(" ")
term.setCursorPos(x, y)
end
else
if x <= w and y <= h then
term.setCursorPos(x, y)
term.write(c)
x = x + 1
end
end
if x > w then
x = 1
y = y + 1
end
if y - 1 >= h then
term.scroll(1)
y = h
term.setCursorPos(x, y)
end
end
term.setCursorPos(x, y)
end
local function displaySuperBadError(err)
term.setBackgroundColor(0x1)
term.setTextColor(0x4)
term.clear()
term.setCursorPos(1, 1)
term.write("A critical error occurred while loading the system:")
term.setCursorPos(1, 3)
write(err)
while true do end
end
term.setCursorBlink(false)
local ok, err = xpcall(function()
local apis = {BOOT_DRIVE_PATH = BOOT_DRIVE_PATH}
local lua = {
coroutine = true,
debug = true,
_VERSION = true,
assert = true,
collectgarbage = true,
error = true,
gcinfo = true,
getmetatable = true,
ipairs = true,
__inext = 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,
_G = true
}
local debug = debug
for i, v in pairs(_G) do
if not lua[i] or lua[i] == nil then
apis[i] = v
_G[i] = nil
end
end
local acekeys={
[apis.keys.enter]="\n",
[apis.keys.tab]="\t",
[apis.keys.backspace]="\b",
[apis.keys.up]="\17",
[apis.keys.down]="\18",
[apis.keys.left]="\19",
[apis.keys.right]="\20",
}
function sleep(time)
local stoptime = apis.os.clock() + (time)
while stoptime > apis.os.clock() do end
end
apis.term.setPaletteColor(0x1, 0xFFFFFF) -- #000000
apis.term.setPaletteColor(0x2, 0xFF0000) -- #FFFFFF
apis.term.setPaletteColor(0x4, 0x00FF00) -- #FF0000
apis.term.setPaletteColor(0x8, 0x0000FF) -- #00FF00
apis.term.setPaletteColor(0x10, 0x00FFFF) -- #0000FF
apis.term.setPaletteColor(0x20, 0xFF00FF) -- #00FFFF
apis.term.setPaletteColor(0x40, 0xFFFF00) -- #FF00FF
apis.term.setPaletteColor(0x80, 0xFF6D00) -- #FFFF00
apis.term.setPaletteColor(0x100, 0x6DFF55) -- #FF6D00
apis.term.setPaletteColor(0x200, 0x24FFFF) -- #6DFF55
apis.term.setPaletteColor(0x400, 0x924900) -- #24FFFF
apis.term.setPaletteColor(0x800, 0x6D6D55) -- #924900
apis.term.setPaletteColor(0x1000, 0xDBDBAA) -- #6D6D55
apis.term.setPaletteColor(0x2000, 0x6D00FF) -- #DBDBAA
apis.term.setPaletteColor(0x4000, 0xB6FF00) -- #6D00FF
apis.term.setPaletteColor(0x8000, 0x000000) -- #B6FF00
local function getFile(path)
local file = apis.fs.open(path, "r")
if not file then
displaySuperBadError("Could not open file: " .. path)
end
local content = file.readAll()
file.close()
return content
end
local Kernel = load(getFile(BOOT_DRIVE_PATH .. "/boot/kernel.lua"),"@Kernel")
local initFs = load(getFile(BOOT_DRIVE_PATH .. "/boot/cct/initdisks"),"@Init_disks")(apis)
local fs = load(getFile(BOOT_DRIVE_PATH .. "/boot/initfs"), "@InitFs")()
if not Kernel then displaySuperBadError("Could not load kernel.") end
if not initFs then displaySuperBadError("Could not load initdisks.") end
if not fs then displaySuperBadError("Could not load initfs.") end
if not apis.fs.exists("/nvram.dat") then
local file = apis.fs.open("/nvram.dat", "w")
file.write("Hello, World!")
file.close()
end
local eeprom
if apis.fs.exists("/startup.lua") then
eeprom="/startup.lua"
elseif apis.fs.exists("/eeprom") then
eeprom="/eeprom"
end
local eventQueue = {}
local function queueEvent(event, ...)
table.insert(eventQueue, {event, ...})
end
local colors = {
[0x000000]=0x0001,
[0xFFFFFF]=0x0002,
[0xFF0000]=0x0004,
[0x00FF00]=0x0008,
[0x0000FF]=0x0010,
[0x00FFFF]=0x0020,
[0xFF00FF]=0x0040,
[0xFFFF00]=0x0080,
[0xFF6D00]=0x0100,
[0x6DFF55]=0x0200,
[0x24FFFF]=0x0400,
[0x924900]=0x0800,
[0x6D6D55]=0x1000,
[0xDBDBAA]=0x2000,
[0x6D00FF]=0x4000,
[0xB6FF00]=0x8000
}
local fg,bg=0x6D6D55,0x000000
local l1f,l1d,l2,ops={},{},{},0
local function findClosest(tbl, target)
local closest = nil
local smallestDiff = math.huge
for k, _ in pairs(tbl) do
local diff = math.abs(k - target)
if diff < smallestDiff then
smallestDiff = diff
closest = k
end
end
return closest
end
local function aprox(c24)
ops = ops + 1
if ops % 1024 == 0 then
l1d = {}
l1f = {}
end
if ops % 8192 == 0 then
l2 = {}
end
if l2[c24] ~= nil then
return l2[c24]
end
if l1d[c24] ~= nil then
l1f[c24] = l1f[c24] + 1
if l1f[c24] >= 16 then
l2[c24] = l1d[c24]
l1d[c24] = nil
l1f[c24] = nil
return l2[c24]
end
return l1d[c24]
end
local closestKey = findClosest(colors, c24)
if not closestKey then return nil end
local value = colors[closestKey]
l1d[c24] = value
l1f[c24] = 1
return value
end
local EFI = {
getEpochMs = function() return apis.os.epoch("utc") end,
getUptime = function() return apis.os.clock() * 1000 end,
date = function() return apis.os.date("!%Y-%m-%dT%H:%M:%SZ", apis.os.epoch("utc") / 1000) end,
getMachineEvent = function()
if #eventQueue > 0 then
return table.unpack(table.remove(eventQueue, 1))
else
return nil
end
end,
getEEPROM = function() return getFile(eeprom) end,
setEEPROM = function(_, text)
local h = apis.fs.open(eeprom, "w")
h.write(text)
h.close()
end,
initfs=fs,
disks=initFs,
screenCtl={
print = function(_, text) write(text .. "\n") end,
printInline = function(_, text) write(text) end,
clear = function()
apis.term.clear()
apis.term.setCursorPos(1, 1)
end,
setCursorPos = function(_, x, y)
apis.term.setCursorPos(x, y)
end,
getCursorPos = function() return apis.term.getCursorPos() end,
getSize = function() return apis.term.getSize() end,
setBackgroundColor = function(_, color)
apis.term.setBackgroundColor(aprox(color))
end,
setTextColor = function(_, color)
apis.term.setTextColor(aprox(color))
end,
getBackgroundColor = function()
return bg
end,
getTextColor = function()
return fg
end,
enable=function() end,
disable=function() end
},
architecture="cct",
getNvram = function() return getFile("/nvram.dat") end,
setNvram = function(_, text)
local h = apis.fs.open("/nvram.dat", "w")
h.write(text)
h.close()
end,
firmware=apis,
reboot=false
}
apis.term.setBackgroundColor(0x8000)
apis.term.setTextColor(0x1000)
apis.term.clear()
apis.term.setCursorPos(1, 1)
local kernelCoro = coroutine.create(function()
---@diagnostic disable-next-line: param-type-mismatch
local ok, err = xpcall(Kernel, debug.traceback, EFI)
if not ok and not EFI.reboot then displaySuperBadError(err) end
if err then
apis.os.reboot()
else
apis.os.shutdown()
end
end)
function EFI.resumeWithTimeout(co, timeout, ...)
local startTime = EFI.getEpochMs()
debug.sethook(co, function()
if EFI.getEpochMs() > startTime + timeout then
return coroutine.yield("timeout")
end
end, "", 1000)
local ret = {coroutine.resume(co, ...)}
if ret[1] and ret[2] == "timeout" then
return "timeout"
elseif ret[1] == false then
return "error", ret[2]
else
debug.sethook(co)
return "success", table.unpack(ret, 2)
end
end
write("Loaded in " .. tostring(apis.os.clock()) .. " seconds.\n")
while true do
local status, err = EFI.resumeWithTimeout(kernelCoro, 50)
apis.os.queueEvent("NoSleep")
local exit = false
while not exit do
local event = {coroutine.yield()}
if event[1] == "key" then
queueEvent("keyPressed", 1, event[2])
if acekeys[event[2]] then
queueEvent("keyTyped", 1, acekeys[event[2]])
end
elseif event[1] == "char" then
queueEvent("keyTyped", 1, event[2])
elseif event[1] == "key_up" then
queueEvent("keyReleased", 1, event[2])
elseif event[1] == "disk" then
queueEvent("componentAdded", "disk")
elseif event[1] == "disk_eject" then
queueEvent("componentRemoved", "disk")
elseif event[1] == "modem_message" then
queueEvent("modem_message", table.unpack(event, 2))
elseif event[1] == "rednet_message" then
queueEvent("rednet_message", table.unpack(event, 2))
elseif event[1] == "http_success" then
queueEvent("http_success", table.unpack(event, 2))
elseif event[1] == "http_failure" then
queueEvent("http_failure", table.unpack(event, 2))
elseif event[1] == "NoSleep" then
exit = true
end
end
if status == "error" or coroutine.status(kernelCoro) == "dead" then
if EFI.reboot then
apis.os.reboot()
end
displaySuperBadError("Kernel error: " .. tostring(err))
coroutine.yield("key")
end
initFs:refresh()
end
end, debug.traceback)
if not ok then displaySuperBadError("Fatal error during boot: " .. err) end
while true do coroutine.yield("key") end
@@ -0,0 +1,119 @@
--:Minify:--
local BOOT_DRIVE_PATH=({...})[1] or "/$"
-- UnBIOS by JackMacWindows
-- This will undo most of the changes/additions made in the BIOS, but some things may remain wrapped if `debug` is unavailable
-- To use, just place a `bios.lua` in the root of the drive, and run this program
-- Here's a list of things that are irreversibly changed:
-- * both `bit` and `bit32` are kept for compatibility
-- * string metatable blocking (on old versions of CC)
-- In addition, if `debug` is not available these things are also irreversibly changed:
-- * old Lua 5.1 `load` function (for loading from a function)
-- * `loadstring` prefixing (before CC:T 1.96.0)
-- * `http.request`
-- * `os.shutdown` and `os.reboot`
-- * `peripheral`
-- * `turtle.equip[Left|Right]`
-- Licensed under the MIT license
local args = {...}
local keptAPIs = {keys=true, bit32 = true, bit = true, ccemux = true, config = true, coroutine = true, debug = true, fs = true, http = true, mounter = true, os = true, periphemu = true, peripheral = true, redstone = true, rs = true, term = true, utf8 = true, _HOST = true, _CC_DEFAULT_SETTINGS = true, _CC_DISABLE_LUA51_FEATURES = true, _VERSION = true, assert = true, collectgarbage = true, error = true, gcinfo = true, getfenv = true, getmetatable = true, ipairs = true, __inext = true,load = true, loadstring = true, math = true, newproxy = true, next = true, pairs = true, pcall = true, rawequal = true, rawget = true, rawlen = true, rawset = true, select = true, setfenv = true, setmetatable = true, string = true, table = true, tonumber = true, tostring = true, type = true, unpack = true, xpcall = true, turtle = true, pocket = true, commands = true, _G = true}
local t = {}
for k in pairs(_G) do if not keptAPIs[k] then table.insert(t, k) end end
for _,k in ipairs(t) do _G[k] = nil end
local native = _G.term.native()
for _, method in ipairs {"nativePaletteColor", "nativePaletteColour", "screenshot"} do native[method] = _G.term[method] end
_G.term = native
if _G.http then
_G.http.checkURL = _G.http.checkURLAsync
_G.http.websocket = _G.http.websocketAsync
end
if _G.commands then _G.commands = _G.commands.native end
if _G.turtle then _G.turtle.native, _G.turtle.craft = nil end
local delete = {os = {"version", "pullEventRaw", "pullEvent", "run", "loadAPI", "unloadAPI", "sleep"}, http = _G.http and {"get", "post", "put", "delete", "patch", "options", "head", "trace", "listen", "checkURLAsync", "websocketAsync"}, fs = {"complete", "isDriveRoot"}}
for k,v in pairs(delete) do for _,a in ipairs(v) do _G[k][a] = nil end end
-- Set up TLCO
-- This functions by crashing `rednet.run` by removing `os.pullEventRaw`. Normally
-- this would cause `parallel` to throw an error, but we replace `error` with an
-- empty placeholder to let it continue and return without throwing. This results
-- in the `pcall` returning successfully, preventing the error-displaying code
-- from running - essentially making it so that `os.shutdown` is called immediately
-- after the new BIOS exits.
--
-- From there, the setup code is placed in `term.native` since it's the first
-- thing called after `parallel` exits. This loads the new BIOS and prepares it
-- for execution. Finally, it overwrites `os.shutdown` with the new function to
-- allow it to be the last function called in the original BIOS, and returns.
-- From there execution continues, calling the `term.redirect` dummy, skipping
-- over the error-handling code (since `pcall` returned ok), and calling
-- `os.shutdown()`. The real `os.shutdown` is re-added, and the new BIOS is tail
-- called, which effectively makes it run as the main chunk.
local olderror = error
_G.error = function() end
_G.term.redirect = function() end
function _G.term.native()
_G.term.native = nil
_G.term.redirect = nil
_G.error = olderror
term.setBackgroundColor(32768)
term.setTextColor(1)
term.setCursorPos(1, 1)
term.setCursorBlink(true)
term.clear()
local file = fs.open(BOOT_DRIVE_PATH.."/boot/cct/boot.lua", "r")
if file == nil then
term.setCursorBlink(false)
term.setTextColor(16384)
term.write("Could not find /boot/cct/boot.lua. UnBIOS cannot continue.")
term.setCursorPos(1, 2)
term.write("Press any key to continue")
coroutine.yield("key")
os.shutdown()
end
local fn, err = loadstring(file.readAll(), "@bootloader")
file.close()
if fn == nil then
term.setCursorBlink(false)
term.setTextColor(16384)
term.write("Could not load /boot/cc/boot.lua. UnBIOS cannot continue.")
term.setCursorPos(1, 2)
term.write(err)
term.setCursorPos(1, 3)
term.write("Press any key to continue")
coroutine.yield("key")
os.shutdown()
end
setfenv(fn, _G)
local oldshutdown = os.shutdown
os.shutdown = function()
os.shutdown = oldshutdown
return fn(BOOT_DRIVE_PATH)
end
end
if debug then
-- Restore functions that were overwritten in the BIOS
-- Apparently this has to be done *after* redefining term.native
local function restoreValue(tab, idx, name, hint)
local i, key, value = 1, debug.getupvalue(tab[idx], hint)
while key ~= name and key ~= nil do
key, value = debug.getupvalue(tab[idx], i)
i=i+1
end
tab[idx] = value or tab[idx]
end
restoreValue(_G, "loadstring", "nativeloadstring", 1)
restoreValue(_G, "load", "nativeload", 5)
if http then restoreValue(http, "request", "nativeHTTPRequest", 3) end
restoreValue(os, "shutdown", "nativeShutdown", 1)
restoreValue(os, "reboot", "nativeReboot", 1)
if turtle then
restoreValue(turtle, "equipLeft", "v", 1)
restoreValue(turtle, "equipRight", "v", 1)
end
do
local i, key, value = 1, debug.getupvalue(peripheral.isPresent, 2)
while key ~= "native" and key ~= nil do
key, value = debug.getupvalue(peripheral.isPresent, i)
i=i+1
end
_G.peripheral = value or peripheral
end
end
@@ -0,0 +1,272 @@
--:Minify:--
local apis = ({...})[1]
local BOOT_DRIVE_PATH = apis.BOOT_DRIVE_PATH
local fs = apis.fs
local native = apis.peripheral
local peripheral = {}
local sides = {"top", "bottom", "left", "right", "front", "back"}
function peripheral.getNames()
local results = {}
for n = 1, #sides do
local side = sides[n]
if native.isPresent(side) then
table.insert(results, side)
if native.hasType(side, "peripheral_hub") then
local remote = native.call(side, "getNamesRemote")
for _, name in ipairs(remote) do
table.insert(results, name)
end
end
end
end
return results
end
function peripheral.isPresent(name)
if native.isPresent(name) then
return true
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then
return true
end
end
return false
end
function peripheral.getType(peripheral)
if type(peripheral) == "string" then
if native.isPresent(peripheral) then
return native.getType(peripheral)
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", peripheral) then
return native.call(side, "getTypeRemote", peripheral)
end
end
return nil
else
local mt = getmetatable(peripheral)
if not mt or mt.__name ~= "peripheral" or type(mt.types) ~= "table" then
error("bad argument #1 (table is not a peripheral)", 2)
end
return table.unpack(mt.types)
end
end
function peripheral.hasType(peripheral, peripheral_type)
if type(peripheral) == "string" then
if native.isPresent(peripheral) then
return native.hasType(peripheral, peripheral_type)
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", peripheral) then
return native.call(side, "hasTypeRemote", peripheral, peripheral_type)
end
end
return nil
else
local mt = getmetatable(peripheral)
if not mt or mt.__name ~= "peripheral" or type(mt.types) ~= "table" then
error("bad argument #1 (table is not a peripheral)", 2)
end
return mt.types[peripheral_type] ~= nil
end
end
function peripheral.getMethods(name)
if native.isPresent(name) then
return native.getMethods(name)
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then
return native.call(side, "getMethodsRemote", name)
end
end
return nil
end
function peripheral.getName(peripheral)
local mt = getmetatable(peripheral)
if not mt or mt.__name ~= "peripheral" or type(mt.name) ~= "string" then
error("bad argument #1 (table is not a peripheral)", 2)
end
return mt.name
end
function peripheral.call(name, method, ...)
if native.isPresent(name) then
return native.call(name, method, ...)
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then
return native.call(side, "callRemote", name, method, ...)
end
end
return nil
end
function peripheral.wrap(name)
local methods = peripheral.getMethods(name)
if not methods then
return nil
end
local types = { peripheral.getType(name) }
for i = 1, #types do types[types[i]] = true end
local result = setmetatable({}, {
__name = "peripheral",
name = name,
type = types[1],
types = types,
})
for _, method in ipairs(methods) do
result[method] = function(...)
return peripheral.call(name, method, ...)
end
end
return result
end
function peripheral.find(ty, filter)
local results = {}
for _, name in ipairs(peripheral.getNames()) do
if peripheral.hasType(name, ty) then
local wrapped = peripheral.wrap(name)
if filter == nil or filter(name, wrapped) then
table.insert(results, wrapped)
end
end
end
return table.unpack(results)
end
local disks = {}
local internal = {}
local function norm(path)
if not path or path == "" then return "/" end
return fs.combine("/", path)
end
local function createDisk(id, basePath, readonly, periph)
basePath = norm(basePath)
local disk = {address = id, isReadOnly = function() return readonly end}
function disk:spaceUsed()
return fs.getCapacity(basePath) - fs.getFreeSpace(basePath)
end
function disk:spaceTotal() return fs.getCapacity(basePath) end
function disk:list(path)
local p = fs.combine(basePath, path)
if not fs.exists(p) or not fs.isDir(p) then
return nil, "not directory"
end
return fs.list(p)
end
function disk:fileExists(path)
local p = fs.combine(basePath, path)
return fs.exists(p) and not fs.isDir(p)
end
function disk:directoryExists(path)
local p = fs.combine(basePath, path)
return fs.exists(p) and fs.isDir(p)
end
function disk:type(path)
local p = fs.combine(basePath, path)
if not fs.exists(p) then
return nil
elseif fs.isDir(p) then
return "directory"
else
return "file"
end
end
function disk:makeDirectory(path)
local p = fs.combine(basePath, path)
fs.makeDir(p)
return true
end
function disk:remove(path)
local p = fs.combine(basePath, path)
if fs.exists(p) then fs.delete(p) end
return true
end
function disk:setLabel(label) periph.setLabel(label) end
function disk:getLabel(label) return periph.getLabel() end
function disk:attributes(path)
local p = fs.combine(basePath, path)
return fs.attributes(p)
end
function disk:open(path, mode)
local p = fs.combine(basePath, path)
return fs.open(p, mode)
end
return disk
end
internal["$"] = createDisk("$", BOOT_DRIVE_PATH, false, {
setLabel = function(label)
local h = fs.open("/.label", "w")
h.write(label)
h.close()
end,
getLabel = function()
local h = fs.open("/.label", "r")
if not h then return "$" end
local label = h.readAll()
h.close()
return label
end
})
internal["rom"] = createDisk("rom", "/rom", true, {
setLabel = function(label)
error("Device is read-only")
end,
getLabel = function()
return "cctrom"
end
})
local function refresh()
disks={}
for _, disk in ipairs({peripheral.find("drive")}) do
if disk.isDiskPresent() then
disks[tostring(disk.getDiskID())]=createDisk("cctdisk"..tostring(disk.getDiskID()), disk.getMountPath(), false, fs)
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,6 @@
--:Minify:--
local kernel=...
if kernel.gfx then
end
@@ -494,7 +494,7 @@ local ok, err = xpcall(function()
h.close() h.close()
end, end,
firmware=apis, firmware=apis,
status="running", reboot=false,
beep=function() end beep=function() end
} }
@@ -505,7 +505,7 @@ local ok, err = xpcall(function()
local kernelCoro = coroutine.create(function() local kernelCoro = coroutine.create(function()
--pf --pf
---@diagnostic disable-next-line: param-type-mismatch ---@diagnostic disable-next-line: param-type-mismatch-
local ok, err = xpcall(Kernel, debug.traceback, EFI) local ok, err = xpcall(Kernel, debug.traceback, EFI)
if not ok then if not ok then
error(err) error(err)
@@ -569,18 +569,14 @@ local ok, err = xpcall(function()
end end
end end
if status == "error" or coroutine.status(kernelCoro) == "dead" then if status == "error" or coroutine.status(kernelCoro) == "dead" then
if EFI.status=="reboot" then if EFI.reboot then
apis.os.reboot() apis.os.reboot()
elseif EFI.status=="shutdown" then
apis.os.shutdown()
end end
displaySuperBadError("Kernel error: " .. tostring(err)) displaySuperBadError("Kernel error: " .. tostring(err))
coroutine.yield("key") coroutine.yield("key")
elseif status == "success" then elseif status == "success" then
if EFI.status=="reboot" then if EFI.reboot then
apis.os.reboot() apis.os.reboot()
elseif EFI.status=="shutdown" then
apis.os.shutdown()
end end
displaySuperBadError("Kernel error: Attempted to yield main thread\n"..debug.traceback(kernelCoro, "Attempted to yield main thread")) displaySuperBadError("Kernel error: Attempted to yield main thread\n"..debug.traceback(kernelCoro, "Attempted to yield main thread"))
coroutine.yield("key") coroutine.yield("key")
@@ -163,7 +163,7 @@ local function createDisk(id, basePath, readonly, periph)
local disk = {address = id, isReadOnly = function() return readonly end} local disk = {address = id, isReadOnly = function() return readonly end}
function disk:spaceUsed() function disk:spaceUsed()
return (fs.getCapacity(basePath) or 0) - (fs.getFreeSpace(basePath) or 0) return fs.getCapacity(basePath) - fs.getFreeSpace(basePath)
end end
function disk:spaceTotal() return fs.getCapacity(basePath) end function disk:spaceTotal() return fs.getCapacity(basePath) end
@@ -1,12 +0,0 @@
--:Minify:--
local kernel=...
if kernel.arch~="cct" then
kernel.deny("cc-tweaked/01_periph.kmod")
kernel.deny("cc-tweaked/13_devraw.kmod")
kernel.deny("cc-tweaked/22_http.kmod")
kernel.deny("cc-tweaked/25_mouse.kmod")
kernel.deny("cc-tweaked/25_tty.kmod")
kernel.deny("cc-tweaked/30_daemon.kmod")
kernel.deny("cc-tweaked/46_scheduler.kmod")
kernel.deny("cc-tweaked/51_gpio.kmod")
end
@@ -1,25 +0,0 @@
--:Minify:--
local kernel=...
local fifo=kernel.newFifo()
kernel.devfs.data["input"]["mouse1"] = function(op, mode)
if op=="type" then
return "Mouse"
elseif op=="open" then
local h = {
read=function(amount)
local rv=""
for i=1, amount or 1 do
local event = {fifo.pop()}
if event[1] then
rv=rv..event[1]
end
end
---@diagnostic disable-next-line: cast-local-type
if rv=="" then rv=nil end
return rv
end
}
return h
end
end
kernel.cct.mouse={fifo=fifo}
@@ -1,8 +1,6 @@
--:Minify:-- --:Minify:--
local kernel = ... local kernel = ...
local peripheral=kernel.cct.peripheral local peripheral=kernel.cct.peripheral
kernel.cct.gfx={}
kernel.cct.term={}
local colors = { local colors = {
[0xFFFFFF]=0x0001, [0xFFFFFF]=0x0001,
@@ -157,7 +155,6 @@ local function serializeBool(bool)
end end
local function newtty(obj, id, ev) local function newtty(obj, id, ev)
kernel.cct.term[id]=obj
obj.setPaletteColor(0x1, 0xFFFFFF) -- #000000 obj.setPaletteColor(0x1, 0xFFFFFF) -- #000000
obj.setPaletteColor(0x2, 0xFF0000) -- #FFFFFF obj.setPaletteColor(0x2, 0xFF0000) -- #FFFFFF
obj.setPaletteColor(0x4, 0x00FF00) -- #FF0000 obj.setPaletteColor(0x4, 0x00FF00) -- #FF0000
@@ -179,6 +176,17 @@ local function newtty(obj, id, ev)
return "Terminal" return "Terminal"
elseif op=="open" then elseif op=="open" then
local h = { local h = {
read=function(amount)
local rv=""
for i=1, amount or 1 do
local event = {ev()}
if event[1] then
rv=rv..event[1]
end
end
if rv=="" then rv=nil end
return rv
end,
write=function(content) write=function(content)
write(content, obj) write(content, obj)
end, end,
@@ -213,16 +221,18 @@ local function newtty(obj, id, ev)
return false return false
end, end,
gplt=function() gplt=function()
return table.deepcopy(plt) return plt
end,
gfx=function(...)
if kernel.cct.gfx[id] then return kernel.cct.gfx[id] else return false end
end,
id=function()
return id
end end
} }
return h 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
end end
end end
@@ -249,19 +259,23 @@ kernel.devfs.data["input"]["keyboard1"] = function(op, mode)
rv=rv..event[1] rv=rv..event[1]
end end
end end
if rv~="" then return rv end if rv=="" then rv=nil end
local task=kernel.currentTask return rv
task.status="D" end,
task.io=function() write=function(content)
local event = {fifo.pop()}
if event[1] then return event[1] end
end
return nil
end, end,
gctrl=function() gctrl=function()
return serializeBool(kernel.cct.ctrl)..";"..serializeBool(kernel.cct.alt) return serializeBool(kernel.cct.ctrl)..";"..serializeBool(kernel.cct.alt)
end end
} }
return h 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
end end
@@ -71,10 +71,8 @@ kernel.processes.cctdaemon = function()
elseif eventType == "mouse_scroll" then elseif eventType == "mouse_scroll" then
if event[2] == 1 then if event[2] == 1 then
kernel.cct.fifo.push("S") kernel.cct.fifo.push("S")
kernel.cct.mouse.fifo.push("S")
else else
kernel.cct.fifo.push("T") kernel.cct.fifo.push("T")
kernel.cct.mouse.fifo.push("T")
end end
elseif eventType == "http_success" then elseif eventType == "http_success" then
if kernel.cct.httpqueue[event[2]] then if kernel.cct.httpqueue[event[2]] then
@@ -87,16 +85,6 @@ kernel.processes.cctdaemon = function()
kernel.cct.httperror[event[2]]=event[3] kernel.cct.httperror[event[2]]=event[3]
kernel.cct.httpresponse[event[2]]=event[4] kernel.cct.httpresponse[event[2]]=event[4]
end end
elseif eventType == "mouse_click" then
--";X;Y;C"
-- 1 = left
-- 2 = right
-- 3 = middle
kernel.cct.mouse.fifo.push(";"..tostring(event[3])..";"..tostring(event[4])..";"..tostring(event[2]))
elseif eventType == "mouse_drag" then
kernel.cct.mouse.fifo.push(";"..tostring(event[3])..";"..tostring(event[4])..";"..tostring(event[2]))
elseif eventType == "mouse_up" then
kernel.cct.mouse.fifo.push(";"..tostring(event[3])..";"..tostring(event[4])..";"..tostring(event[2]))
else else
if kernel.cct.eventhooks[eventType] then if kernel.cct.eventhooks[eventType] then
local ok,err = xpcall(kernel.cct.eventhooks[eventType], debug.traceback, table.unpack(event)) local ok,err = xpcall(kernel.cct.eventhooks[eventType], debug.traceback, table.unpack(event))
@@ -35,14 +35,6 @@ function kernel.main()
local totalTaskTime = 0 local totalTaskTime = 0
local taskTimes = {} local taskTimes = {}
for id,hook in ipairs(kernel.mainHooks) do
local ok,err = xpcall(hook, debug.traceback)
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 for pid, task in pairs(kernel.tasks) do
if kernel.exitMain then break end if kernel.exitMain then break end
@@ -50,7 +42,7 @@ function kernel.main()
for id,hook in ipairs(list) do for id,hook in ipairs(list) do
local ok,err = xpcall(hook, debug.traceback, task, pid) local ok,err = xpcall(hook, debug.traceback, task, pid)
if not ok then if not ok then
kernel.log("[TASK HOOK ERR]: "..err, "ERROR", 0xFF0000) kernel.log("[MAIN HOOK ERR]: "..err, "ERROR", 0xFF0000)
list[id]=nil list[id]=nil
end end
end end
@@ -156,6 +148,4 @@ function kernel.main()
kernel.saveLog() kernel.saveLog()
end end
end end
kernel.log("Exited main")
kernel.saveLog()
end end
Whitespace-only changes.
-2
View File
@@ -1,2 +0,0 @@
Hyperion
Spsf
@@ -1,691 +0,0 @@
--: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
@@ -1,2 +0,0 @@
return true
Binary file not shown.
@@ -1,318 +0,0 @@
--: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}
@@ -1,11 +0,0 @@
--: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
@@ -1,19 +0,0 @@
--: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
@@ -1,28 +0,0 @@
--: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
@@ -1,133 +0,0 @@
--: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
@@ -1,129 +0,0 @@
--: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
@@ -1,106 +0,0 @@
--: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")
@@ -1,187 +0,0 @@
--: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
@@ -1 +0,0 @@
firmware for NeetComputers
-1
View File
@@ -1 +0,0 @@
1.0.0
+1 -2
View File
@@ -1,4 +1,3 @@
Hyperion Hyperion
Astronand Astronand
Xtimhedae Xtimhedae
Spsf
@@ -1,4 +1,3 @@
---@diagnostic disable-next-line: undefined-global
local cp,c=component,computer;local b_addr=c.getBootAddress();local b_fs=cp.proxy(b_addr) local cp,c=component,computer;local b_addr=c.getBootAddress();local b_fs=cp.proxy(b_addr)
local gpu=cp.list("gpu")() and cp.proxy(cp.list("gpu")()) local gpu=cp.list("gpu")() and cp.proxy(cp.list("gpu")())
local e_rom=cp.list("eeprom")() and cp.proxy(cp.list("eeprom")()) local e_rom=cp.list("eeprom")() and cp.proxy(cp.list("eeprom")())
+21 -110
View File
@@ -1,73 +1,35 @@
local args = {...} local args = {...}
local apis = args[1] local apis = args[1]
local bootdrive = args[2] local bootdrive = args[2]
local bootaddr = args[3] local bootaddr = args[3]
local disks = {} local disks = {}
local internal = {} 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 function createDisk(id, hw)
local disk = { local disk = {
address = id, address = id,
isReadOnly = function() isReadOnly = function() return hw.isReadOnly() end
return hw.isReadOnly()
end
} }
function disk:spaceUsed() function disk:spaceUsed() return hw.spaceUsed() end
return hw.spaceUsed() function disk:spaceTotal() return hw.spaceTotal() end
end
function disk:spaceTotal()
return hw.spaceTotal()
end
function disk:list(path) function disk:list(path)
path = normalize(path)
if not hw.exists(path) or not hw.isDirectory(path) then if not hw.exists(path) or not hw.isDirectory(path) then
return nil, "not directory" return nil, "not directory"
end end
return hw.list(path)
local ret = {}
for i, v in ipairs(hw.list(path)) do
ret[i] = normalize(v)
end
return ret
end end
function disk:fileExists(path) function disk:fileExists(path)
path = normalize(path)
return hw.exists(path) and not hw.isDirectory(path) return hw.exists(path) and not hw.isDirectory(path)
end end
function disk:directoryExists(path) function disk:directoryExists(path)
path = normalize(path)
return hw.exists(path) and hw.isDirectory(path) return hw.exists(path) and hw.isDirectory(path)
end end
function disk:type(path) function disk:type(path)
path = normalize(path)
if not hw.exists(path) then if not hw.exists(path) then
return nil return nil
elseif hw.isDirectory(path) then elseif hw.isDirectory(path) then
@@ -78,29 +40,17 @@ local function createDisk(id, hw)
end end
function disk:makeDirectory(path) function disk:makeDirectory(path)
path = normalize(path) hw.makeDirectory(path)
return hw.makeDirectory(path)
end end
function disk:remove(path) function disk:remove(path)
path = normalize(path) if hw.exists(path) then hw.remove(path) end
if hw.exists(path) then
return hw.remove(path)
end
end end
function disk:setLabel(label) function disk:setLabel(label) hw.setLabel(label) end
return hw.setLabel(label) function disk:getLabel() return hw.getLabel() end
end
function disk:getLabel()
return hw.getLabel()
end
function disk:attributes(path) function disk:attributes(path)
path = normalize(path)
return { return {
size = hw.size(path), size = hw.size(path),
isDir = hw.isDirectory(path), isDir = hw.isDirectory(path),
@@ -111,8 +61,6 @@ local function createDisk(id, hw)
end end
function disk:open(path, mode) function disk:open(path, mode)
path = normalize(path)
local fd = hw.open(path, mode) local fd = hw.open(path, mode)
if not fd then if not fd then
@@ -120,67 +68,43 @@ local function createDisk(id, hw)
if dir and not hw.exists(dir) then if dir and not hw.exists(dir) then
local ok, err = hw.makeDirectory(dir) local ok, err = hw.makeDirectory(dir)
if not ok then if not ok then
return nil, err or "could not create parent directory" return nil, err or "could not create parent directory"
end end
end end
fd = hw.open(path, mode) fd = hw.open(path, mode)
if not fd then if not fd then
return nil, "file not found or access denied" return nil, "file not found or access denied"
end end
end end
return { return {
read = function(num) read = function(num) return hw.read(fd, num) end,
return hw.read(fd, num)
end,
readAll = function() readAll = function()
local data = {} local data = {}
while true do while true do
local chunk, err = hw.read(fd, 2048) local chunk = hw.read(fd, math.huge)
if not chunk then break end
if chunk == nil then
if err then
return nil, err
end
break
end
if #chunk == 0 then
break
end
data[#data + 1] = chunk data[#data + 1] = chunk
end end
return table.concat(data) return table.concat(data)
end, end,
write = function(data) write = function(data) return hw.write(fd, data) end,
return hw.write(fd, data)
end,
seek = function(whence, offset) seek = function(whence, offset)
return hw.seek(fd, whence, offset) return hw.seek(fd, whence, offset)
end, end,
flush = function() flush = function()
if fd then hw.close(fd)
hw.close(fd) fd = hw.open(path, mode)
fd = hw.open(path, mode)
end
end, end,
close = function() close = function()
if fd then hw.close(fd)
hw.close(fd) fd = nil
fd = nil
end
end end
} }
end end
@@ -192,34 +116,21 @@ internal["$"] = createDisk("$", bootdrive)
local function refresh() local function refresh()
disks = {} disks = {}
for addr in apis.component.list("filesystem") do for addr in apis.component.list("filesystem") do
if addr ~= bootaddr then if addr ~= bootaddr then
disks[addr] = createDisk( disks[addr] = createDisk(addr, apis.component.proxy(addr))
addr,
apis.component.proxy(addr)
)
end end
end end
end end
local function iter() local function iter()
refresh() refresh()
local combined = {} local combined = {}
for id, obj in pairs(internal) do for id, obj in pairs(internal) do combined[id] = obj end
combined[id] = obj for id, obj in pairs(disks) do combined[id] = obj end
end
for id, obj in pairs(disks) do
combined[id] = obj
end
return pairs(combined) return pairs(combined)
end end
return { return {refresh = refresh, list = iter}
refresh = refresh,
list = iter
}
@@ -1,11 +0,0 @@
--:Minify:--
local kernel=...
if kernel.arch~="oc" then
kernel.deny("opencomputers/01_devices.kmod")
kernel.deny("opencomputers/13_devraw.kmod")
kernel.deny("opencomputers/22_http.kmod")
kernel.deny("opencomputers/25_tty.kmod")
kernel.deny("opencomputers/26_keyboards.kmod")
kernel.deny("opencomputers/30_daemon.kmod")
kernel.deny("opencomputers/36_scheduler.kmod")
end
@@ -1,442 +0,0 @@
--: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,3 +1,4 @@
-- OpenComputers TTY driver
local kernel = ... local kernel = ...
local component = kernel.oc.component local component = kernel.oc.component
@@ -25,6 +26,7 @@ local plt = {
0x660000, 0x660040, 0x660080, 0x6600C0, 0x6600FF, 0x660000, 0x660040, 0x660080, 0x6600C0, 0x6600FF,
0x662400, 0x662440, 0x662480, 0x6624C0, 0x6624FF, 0x662400, 0x662440, 0x662480, 0x6624C0, 0x6624FF,
0x664900, 0x664940, 0x664980, 0x6649C0, 0x6649FF, 0x664900, 0x664940, 0x664980, 0x6649C0, 0x6649FF,
0x666D00, 0x666D40, 0x666D80, 0x666DC0, 0x666DFF,
0x669200, 0x669240, 0x669280, 0x6692C0, 0x6692FF, 0x669200, 0x669240, 0x669280, 0x6692C0, 0x6692FF,
0x66B600, 0x66B640, 0x66B680, 0x66B6C0, 0x66B6FF, 0x66B600, 0x66B640, 0x66B680, 0x66B6C0, 0x66B6FF,
0x66DB00, 0x66DB40, 0x66DB80, 0x66DBC0, 0x66DBFF, 0x66DB00, 0x66DB40, 0x66DB80, 0x66DBC0, 0x66DBFF,
@@ -63,328 +65,113 @@ local plt = {
0xB4B4B4, 0xC3C3C3, 0xD2D2D2, 0xE1E1E1 0xB4B4B4, 0xC3C3C3, 0xD2D2D2, 0xE1E1E1
} }
local gpus = {} local gpus,screens = {},{}
local screens = {}
-- Collect GPUs.
for addr, typ in component.list("gpu") do for addr, typ in component.list("gpu") do
if typ == "gpu" then if typ == "gpu" then
local gpu = component.proxy(addr) gpus[#gpus+1]=component.proxy(addr)
gpus[#gpus + 1] = {
addr = addr,
gpu = gpu,
screen = nil,
fg = nil,
bg = nil
}
end end
end end
-- Collect screens. if #gpus>0 then
for addr, typ in component.list("screen") do for addr, typ in component.list("screen") do
if typ == "screen" then if typ == "screen" then
screens[addr] = { gpus[1].bind(addr)
cx = 1, local w,h = gpus[1].maxResolution()
cy = 1, gpus[1].setResolution(w,h)
w = 0, screens[addr]={cx=1,cy=1,w=w,h=h,addr=addr,fg=0,bg=0,gpu=nil}
h = 0, end
addr = addr,
fg = 0xFFFFFF,
bg = 0x000000,
gpu = nil
}
end end
end end
-- Count screens.
local scrnum = 0 local scrnum = 0
for i,v in pairs(screens) do
for _ in pairs(screens) do scrnum=scrnum+1
scrnum = scrnum + 1
end end
-- Find a GPU that can bind to a screen. kernel.log("initialized "..tostring(#gpus).." gpus and "..tostring(scrnum).." screens")
local function bindGPU(scr)
if scr.gpu then
local state = scr.gpu
if state.screen == scr.addr then local binds,newid={},0
return state local curaddr=""
end 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
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 function write(text, addr)
local scr = screens[addr] local g=gpus[1]
local scr=screens[addr]
if not scr then if not scr then error("NODEV") end
error("NODEV") if curaddr~=addr then g.bind(addr); g.setForeground(scr.fg); g.setBackground(scr.bg) end
end for i=1,#text do
local char=text:sub(i,i)
local state = getGPU(scr) if char=="\n" then scr.cx=1;scr.cy=scr.cy+1
local gpu = state.gpu 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
setColors(state, scr) 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
for i = 1, #text do if scr.cy>scr.h then scroll(scr, g);scr.cy=scr.cy-1 end
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
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
end end
-- Create TTY.
local function newtty(addr) local function newtty(addr)
newid = newid + 1 newid=newid+1
kernel.devfs.data["tty"][tostring(newid)]=function(op, mode)
kernel.devfs.data["tty"][tostring(newid)] = function(op, mode) if op=="type" then
if op == "type" then
return "Terminal" return "Terminal"
elseif op=="open" then
elseif op == "open" then
local h = { local h = {
read = function(amount) read=function(amount) end,
end, write=function(content)
write = function(content)
write(content, addr) write(content, addr)
end, end,
size=function()
size = function() return screens[addr].w, screens[addr].h
local scr = screens[addr]
return scr.w, scr.h
end, end,
clear=function()
clear = function() local g=gpus[1]
local scr = screens[addr] local scr=screens[addr]
local state = getGPU(scr) if addr~=curaddr then g.bind(addr) end
local gpu = state.gpu g.fill(1,1,scr.w,scr.h," ");
scr.cx,scr.cy=1,1
setColors(state, scr)
gpu.fill(
1, 1,
scr.w, scr.h,
" "
)
scr.cx = 1
scr.cy = 1
end, end,
gpos=function()
gpos = function() return screens[addr].cx, screens[addr].cy
local scr = screens[addr]
return scr.cx, scr.cy
end, end,
spos=function(x,y)
spos = function(x, y) if not tonumber(x) or not tonumber(y) then error("Invailid arg") end
if not tonumber(x) or not tonumber(y) then screens[addr].cx, screens[addr].cy = x,y
error("Invalid arg")
end
local scr = screens[addr]
scr.cx = x
scr.cy = y
end, end,
sfgc=function(c)
sfgc = function(c) screens[addr].fg=c
local scr = screens[addr]
if scr.fg ~= c then
scr.fg = c
end
end, end,
sbgc=function(c)
sbgc = function(c) screens[addr].bg=c
local scr = screens[addr]
if scr.bg ~= c then
scr.bg = c
end
end, end,
gfgc=function()
gfgc = function()
return screens[addr].fg return screens[addr].fg
end, end,
gbgc=function()
gbgc = function()
return screens[addr].bg return screens[addr].bg
end, end,
isvirt=function()
isvirt = function()
return false return false
end, end,
gplt=function()
gplt = function()
return plt return plt
end,
gfx = function()
return false
end end
} }
if mode=="rw" then
if mode == "rw" then
return h return h
elseif mode=="r" then
elseif mode == "r" then h["write"]=nil
h.write = nil
return h return h
elseif mode=="w" then
elseif mode == "w" then h["read"]=nil
h.read = nil
return h return h
end end
end end
end end
end end
if #gpus >= 1 and scrnum >= 1 then if #gpus>=1 and scrnum>=1 then
for addr, scr in pairs(screens) do for addr,obj in pairs(screens) do
if scr.gpu then newtty(addr)
newtty(addr)
end
end end
end end
@@ -7,19 +7,19 @@ local kbidx=0
local keyboard = {} local keyboard = {}
keyboard.keys = { keyboard.keys = {
back = 0x0E, back = 0x0E, -- backspace
delete = 0xD3, delete = 0xD3,
down = 0xD0, down = 0xD0,
enter = 0x1C, enter = 0x1C,
home = 0xC7, home = 0xC7,
lcontrol = 0x1D, lcontrol = 0x1D,
left = 0xCB, left = 0xCB,
lmenu = 0x38, lmenu = 0x38, -- left Alt
lshift = 0x2A, lshift = 0x2A,
pageDown = 0xD1, pageDown = 0xD1,
rcontrol = 0x9D, rcontrol = 0x9D,
right = 0xCD, right = 0xCD,
rmenu = 0xB8, rmenu = 0xB8, -- right Alt
rshift = 0x36, rshift = 0x36,
space = 0x39, space = 0x39,
tab = 0x0F, tab = 0x0F,
@@ -33,6 +33,8 @@ for i=0, 255 do
kernel.oc.keys[string.char(i)]=i kernel.oc.keys[string.char(i)]=i
end end
-------------------------------------------------------------------------------
function keyboard.isAltDown(addr) function keyboard.isAltDown(addr)
return kbs[addr].pressedCodes[keyboard.keys.lmenu] or kbs[addr].pressedCodes[keyboard.keys.rmenu] return kbs[addr].pressedCodes[keyboard.keys.lmenu] or kbs[addr].pressedCodes[keyboard.keys.rmenu]
end end
@@ -76,24 +78,15 @@ for addr, typ in kernel.oc.component.list("keyboard") do
elseif op=="open" then elseif op=="open" then
local h = { local h = {
read=function(amount) read=function(amount)
amount = amount or 1
local rv="" local rv=""
for i=1, amount do for i=1, amount or 1 do
local event = {kernel.oc.keyboards[addr].events.pop()} local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then if event[1] then
rv=rv..event[1] rv=rv..event[1]
else
break
end end
end end
if rv~="" then return rv end if rv=="" then rv=nil end
local task=kernel.currentTask return rv
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, end,
write=function(content) write=function(content)
end, end,
@@ -27,6 +27,8 @@ kernel.processes.ocdaemon = function()
[keys.left] = "\27[D", [keys.left] = "\27[D",
[keys.home] = "\27[H", [keys.home] = "\27[H",
[keys["end"]] = "\27[F", [keys["end"]] = "\27[F",
--[keys.pageUp] = "\27[5~",
--[keys.pageDown] = "\27[6~",
[keys.delete] = "\27[3~", [keys.delete] = "\27[3~",
[keys.enter] = "\n", [keys.enter] = "\n",
[keys.back] = "\b", [keys.back] = "\b",
@@ -10,6 +10,7 @@ local lambda_var = 0.02
local k_min = 0.5 local k_min = 0.5
local k_max = 0.5 local k_max = 0.5
local B = 0.01 local B = 0.01
local nextyield=0
function kernel.main() function kernel.main()
kernel.log("Starting main loop...") kernel.log("Starting main loop...")
@@ -17,9 +18,6 @@ function kernel.main()
local stopLog=5 local stopLog=5
local logTasks=100 local logTasks=100
local burstSteps = 0
local maxBurstSteps = 64
while not kernel.exitMain do while not kernel.exitMain do
if kernel.config.logTasks then if kernel.config.logTasks then
if logTasks<0 then if logTasks<0 then
@@ -123,12 +121,10 @@ function kernel.main()
end end
end end
end end
end if kernel.EFI:getEpochMs()>=nextyield then
kernel.EFI:yield()
burstSteps = burstSteps + N nextyield=kernel.EFI:getEpochMs()+5000
if N == 0 or burstSteps >= maxBurstSteps then end
burstSteps = 0
kernel.EFI:yield()
end end
local T_prev_avg = (N > 0) and (totalTaskTime / N) or 0 local T_prev_avg = (N > 0) and (totalTaskTime / N) or 0
@@ -151,4 +147,4 @@ function kernel.main()
kernel.saveLog() kernel.saveLog()
end end
end end
end end
@@ -1,593 +0,0 @@
--:Minify:--
local BOOT_DRIVE_PATH = ({...})[1] or "/$"
---@diagnostic disable-next-line: undefined-global
local lterm = term
local function write(text, term)
local x, y = term.getCursorPos()
local w, h = term.getSize()
for i = 1, #text do
local c = text:sub(i, i)
if c == "\n" then
y = y + 1
x = 1
elseif c == "\t" then
local tabSize = 4
local spaces = tabSize - ((x - 1) % tabSize)
term.write(string.rep(" ", spaces))
x = x + spaces
elseif c == "\b" then
if x > 1 then
x = x - 1
term.setCursorPos(x, y)
term.write(" ")
term.setCursorPos(x, y)
end
else
if x <= w and y <= h then
term.setCursorPos(x, y)
term.write(c)
x = x + 1
end
end
if x > w then
x = 1
y = y + 1
end
if y - 1 >= h then
term.scroll(1)
y = h
term.setCursorPos(x, y)
end
end
term.setCursorPos(x, y)
end
local function displaySuperBadError(err, noyield)
lterm.setBackgroundColor(0x1)
lterm.setTextColor(0x4)
lterm.clear()
lterm.setCursorPos(1, 1)
lterm.write("A critical error occurred while loading the system:")
lterm.setCursorPos(1, 3)
write(err, lterm)
coroutine.yield("key")
end
term.setCursorBlink(false)
local ok, err = xpcall(function()
--p
local apis = {BOOT_DRIVE_PATH = BOOT_DRIVE_PATH}
local lua = {
coroutine = true,
debug = true,
_VERSION = true,
assert = true,
collectgarbage = true,
error = true,
gcinfo = true,
getmetatable = true,
ipairs = true,
__inext = 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,
_G = true
}
local debug = debug
for i, v in pairs(_G) do
if not lua[i] or lua[i] == nil then
apis[i] = v
_G[i] = nil
end
end
--p
local acekeys={
[apis.keys.enter]="\n",
[apis.keys.tab]="\t",
[apis.keys.backspace]="\b",
[apis.keys.up]="\17",
[apis.keys.down]="\18",
[apis.keys.left]="\19",
[apis.keys.right]="\20",
}
function sleep(time)
local stoptime = apis.os.clock() + (time)
while stoptime > apis.os.clock() do end
end
apis.term.setPaletteColor(0x1, 0xFFFFFF) -- #000000
apis.term.setPaletteColor(0x2, 0xFF0000) -- #FFFFFF
apis.term.setPaletteColor(0x4, 0x00FF00) -- #FF0000
apis.term.setPaletteColor(0x8, 0x0000FF) -- #00FF00
apis.term.setPaletteColor(0x10, 0x00FFFF) -- #0000FF
apis.term.setPaletteColor(0x20, 0xFF00FF) -- #00FFFF
apis.term.setPaletteColor(0x40, 0xFFFF00) -- #FF00FF
apis.term.setPaletteColor(0x80, 0xFF6D00) -- #FFFF00
apis.term.setPaletteColor(0x100, 0x6DFF55) -- #FF6D00
apis.term.setPaletteColor(0x200, 0x24FFFF) -- #6DFF55
apis.term.setPaletteColor(0x400, 0x924900) -- #24FFFF
apis.term.setPaletteColor(0x800, 0x6D6D55) -- #924900
apis.term.setPaletteColor(0x1000, 0xDBDBAA) -- #6D6D55
apis.term.setPaletteColor(0x2000, 0x6D00FF) -- #DBDBAA
apis.term.setPaletteColor(0x4000, 0xB6FF00) -- #6D00FF
apis.term.setPaletteColor(0x8000, 0x000000) -- #B6FF00
local function getFile(path)
local file = apis.fs.open(path, "r")
if not file then
displaySuperBadError("Could not open file: " .. path)
end
local content = file.readAll()
file.close()
return content
end
local Kernel = load(getFile(BOOT_DRIVE_PATH .. "/kernel.lua"),"@Kernel")
local initFs = load(getFile(BOOT_DRIVE_PATH .. "/cct/initdisks"),"@Init_disks")(apis)
local fs = load(getFile(BOOT_DRIVE_PATH .. "/initfs"), "@InitFs")()
if not Kernel then displaySuperBadError("Could not load kernel.") end
if not initFs then displaySuperBadError("Could not load initdisks.") end
if not fs then displaySuperBadError("Could not load initfs.") end
if not apis.fs.exists("/nvram.dat") then
local file = apis.fs.open("/nvram.dat", "w")
file.write("Hello, World!")
file.close()
end
local eeprom
if apis.fs.exists("/startup.lua") then
eeprom="/startup.lua"
elseif apis.fs.exists("/eeprom") then
eeprom="/eeprom"
end
local eventQueue = {}
local function queueEvent(event, ...)
table.insert(eventQueue, {event, ...})
end
local colors = {
[0xFFFFFF]=0x0001,
[0xFF0000]=0x0002,
[0x00FF00]=0x0004,
[0x0000FF]=0x0008,
[0x00FFFF]=0x0010,
[0xFF00FF]=0x0020,
[0xFFFF00]=0x0040,
[0xFF6D00]=0x0080,
[0x6DFF55]=0x0100,
[0x24FFFF]=0x0200,
[0x924900]=0x0400,
[0x6D6D55]=0x0800,
[0xDBDBAA]=0x1000,
[0x6D00FF]=0x2000,
[0xB6FF00]=0x4000,
[0x000000]=0x8000
}
local fg,bg=0x6D6D55,0x000000
local l1f,l1d,l2,ops={},{},{},0
local function findClosest(tbl, target)
local closest = nil
local smallestDiff = math.huge
for k, _ in pairs(tbl) do
if k==target then return k end
local diff = math.abs(k - target)
if diff < smallestDiff then
smallestDiff = diff
closest = k
end
end
return closest
end
local function aprox(c24)
ops = ops + 1
if ops % 1024 == 0 then
l1d = {}
l1f = {}
end
if ops % 8192 == 0 then
l2 = {}
end
if l2[c24] ~= nil then
return l2[c24]
end
if l1d[c24] ~= nil then
l1f[c24] = l1f[c24] + 1
if l1f[c24] >= 16 then
l2[c24] = l1d[c24]
l1d[c24] = nil
l1f[c24] = nil
return l2[c24]
end
return l1d[c24]
end
local closestKey = findClosest(colors, c24)
if not closestKey then return nil end
local value = colors[closestKey]
l1d[c24] = value
l1f[c24] = 1
return value
end
--p
local p={}
local native = apis.peripheral
local sides = {"top", "bottom", "left", "right", "front", "back"}
function p.getNames()
local results = {}
for n = 1, #sides do
local side = sides[n]
if native.isPresent(side) then
table.insert(results, side)
if native.hasType(side, "peripheral_hub") then
local remote = native.call(side, "getNamesRemote")
for _, name in ipairs(remote) do
table.insert(results, name)
end
end
end
end
return results
end
function p.isPresent(name)
if native.isPresent(name) then
return true
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then
return true
end
end
return false
end
function p.getType(peripheral)
if type(peripheral) == "string" then
if native.isPresent(peripheral) then
return native.getType(peripheral)
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", peripheral) then
return native.call(side, "getTypeRemote", peripheral)
end
end
return nil
else
local mt = getmetatable(peripheral)
if not mt or mt.__name ~= "peripheral" or type(mt.types) ~= "table" then
error("bad argument #1 (table is not a peripheral)", 2)
end
return table.unpack(mt.types)
end
end
function p.hasType(peripheral, peripheral_type)
if type(peripheral) == "string" then
if native.isPresent(peripheral) then
return native.hasType(peripheral, peripheral_type)
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", peripheral) then
return native.call(side, "hasTypeRemote", peripheral, peripheral_type)
end
end
return nil
else
local mt = getmetatable(peripheral)
if not mt or mt.__name ~= "peripheral" or type(mt.types) ~= "table" then
error("bad argument #1 (table is not a peripheral)", 2)
end
return mt.types[peripheral_type] ~= nil
end
end
function p.getMethods(name)
if native.isPresent(name) then
return native.getMethods(name)
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then
return native.call(side, "getMethodsRemote", name)
end
end
return nil
end
function p.getName(peripheral)
local mt = getmetatable(peripheral)
if not mt or mt.__name ~= "peripheral" or type(mt.name) ~= "string" then
error("bad argument #1 (table is not a peripheral)", 2)
end
return mt.name
end
function p.call(name, method, ...)
if native.isPresent(name) then
return native.call(name, method, ...)
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then
return native.call(side, "callRemote", name, method, ...)
end
end
return nil
end
function p.wrap(name)
local methods = p.getMethods(name)
if not methods then
return nil
end
local types = { p.getType(name) }
for i = 1, #types do types[types[i]] = true end
local result = setmetatable({}, {
__name = "peripheral",
name = name,
type = types[1],
types = types,
})
for _, method in ipairs(methods) do
result[method] = function(...)
return p.call(name, method, ...)
end
end
return result
end
function p.find(ty, filter)
local results = {}
for _, name in ipairs(p.getNames()) do
if p.hasType(name, ty) then
local wrapped = p.wrap(name)
if filter == nil or filter(name, wrapped) then
table.insert(results, wrapped)
end
end
end
return table.unpack(results)
end
--p
local allscreens = {p.find("monitor")}
for i=1, #allscreens do
allscreens[i].setTextScale(.5)
allscreens[i].clear()
allscreens[i].setCursorPos(1,1)
end
allscreens[#allscreens+1] = apis.term
local callAsyncQueue = {}
local callAsyncReturn = {}
apis.callAsyncReturn = callAsyncReturn
local callidx=0
function apis.callAsync(func, ...)
callidx=callidx+1
callAsyncQueue[#callAsyncQueue+1] = {callidx, func, ...}
return callidx
end
local EFI = {
yield=function() end,
getEpochMs = function() return apis.os.epoch("utc") end,
getUptime = function() return apis.os.clock() * 1000 end,
date = function() return apis.os.date("!%Y-%m-%dT%H:%M:%SZ", apis.os.epoch("utc") / 1000) end,
getMachineEvent = function()
if #eventQueue > 0 then
return table.unpack(table.remove(eventQueue, 1))
else
return nil
end
end,
getEEPROM = function() return getFile(eeprom) end,
setEEPROM = function(_, text)
local h = apis.fs.open(eeprom, "w")
h.write(text)
h.close()
end,
initfs=fs,
disks=initFs,
screenCtl={
print = function(_, text)
for i=1, #allscreens do
write(text.."\n", allscreens[i])
end
end,
printInline = function(_, text)
for i=1, #allscreens do
write(text, allscreens[i])
end
end,
clear = function()
for i=1, #allscreens do
allscreens[i].clear()
allscreens[i].setCursorPos(1, 1)
end
end,
resetCursor = function()
for i=1, #allscreens do
allscreens[i].setCursorPos(1, 1)
end
end,
setBackgroundColor = function(_, color)
bg=color
for i=1, #allscreens do
allscreens[i].setBackgroundColor(aprox(color))
end
end,
setTextColor = function(_, color)
fg=color
for i=1, #allscreens do
allscreens[i].setTextColor(aprox(color))
end
end,
getBackgroundColor = function()
return bg
end,
getTextColor = function()
return fg
end,
enable=function()
for i=1, #allscreens do
allscreens[i].clear()
allscreens[i].setCursorPos(1, 1)
end
end,
disable=function() end
},
architecture="cct",
getNvram = function() return getFile("/nvram.dat") end,
setNvram = function(_, text)
local h = apis.fs.open("/nvram.dat", "w")
h.write(text)
h.close()
end,
firmware=apis,
status="running",
beep=function() end
}
apis.term.setBackgroundColor(0x8000)
apis.term.setTextColor(0x1000)
apis.term.clear()
apis.term.setCursorPos(1, 1)
local kernelCoro = coroutine.create(function()
--pf
---@diagnostic disable-next-line: param-type-mismatch
local ok, err = xpcall(Kernel, debug.traceback, EFI)
if not ok then
error(err)
else
apis.os.shutdown()
end
end)
function EFI.resumeWithTimeout(co, timeout, ...)
local startTime = EFI.getEpochMs()
debug.sethook(co, function()
if EFI.getEpochMs() > startTime + timeout then
return coroutine.yield("timeout")
end
end, "", 1000)
local ret = {coroutine.resume(co, ...)}
if ret[1] and ret[2] == "timeout" then
return "timeout"
elseif ret[1] == false then
return "error", ret[2]
else
debug.sethook(co)
return "success", table.unpack(ret, 2)
end
end
EFI.screenCtl:print("Loaded in " .. tostring(apis.os.clock()) .. " seconds.\n")
--p
while true do
local status, err = EFI.resumeWithTimeout(kernelCoro, 50)
apis.os.queueEvent("NoSleep")
local exit = false
while not exit do
local event = {coroutine.yield()}
if event[1] == "key" then
queueEvent(table.unpack(event))
queueEvent("keyPressed", 1, event[2])
if acekeys[event[2]] then
queueEvent("keyTyped", 1, acekeys[event[2]])
end
elseif event[1] == "char" then
queueEvent(table.unpack(event))
queueEvent("keyTyped", 1, event[2])
elseif event[1] == "key_up" then
queueEvent(table.unpack(event))
queueEvent("keyReleased", 1, event[2])
elseif event[1] == "NoSleep" then
exit = true
else
queueEvent(table.unpack(event))
end
end
while #callAsyncQueue>0 do
local bundle = table.remove(callAsyncQueue, 1)
local ret = {xpcall(bundle[2], debug.traceback, table.unpack(bundle, 3))}
if not ret[1] then
callAsyncReturn[bundle[1]]={false, ret[2]}
else
callAsyncReturn[bundle[1]]={true, table.unpack(ret,2)}
end
end
if status == "error" or coroutine.status(kernelCoro) == "dead" then
if EFI.status=="reboot" then
apis.os.reboot()
elseif EFI.status=="shutdown" then
apis.os.shutdown()
end
displaySuperBadError("Kernel error: " .. tostring(err))
coroutine.yield("key")
elseif status == "success" then
if EFI.status=="reboot" then
apis.os.reboot()
elseif EFI.status=="shutdown" then
apis.os.shutdown()
end
displaySuperBadError("Kernel error: Attempted to yield main thread\n"..debug.traceback(kernelCoro, "Attempted to yield main thread"))
coroutine.yield("key")
end
initFs:refresh()
end
end, debug.traceback)
if not ok then displaySuperBadError("Fatal error during boot: " .. err) end
while true do coroutine.yield("key") end
@@ -1 +0,0 @@
print("Hyperion OS PUC bootloader")
+10 -20
View File
@@ -8,8 +8,8 @@ local disks=EFI.disks
local arch=EFI.architecture local arch=EFI.architecture
local kernel = {} local kernel = {}
kernel.LOG_Text="" kernel.LOG_Text=""
kernel.version="HyperionOS V1.2.5" kernel.version="HyperionOS V1.2.4"
kernel.tag="1.2.5" kernel.tag="1.2.4"
kernel.process = "Kernel" kernel.process = "Kernel"
kernel.users={[0]="root",[1000]="User"} kernel.users={[0]="root",[1000]="User"}
kernel.hostname = "hyperion" kernel.hostname = "hyperion"
@@ -74,7 +74,7 @@ function kernel.PANIC(msg)
break break
end end
end end
EFI.status="reboot" EFI.reboot=true
error("KERNEL PANIC") error("KERNEL PANIC")
end end
kernel.panic=kernel.PANIC kernel.panic=kernel.PANIC
@@ -179,6 +179,7 @@ if not root then
if event[1]=="keyTyped" then if event[1]=="keyTyped" then
if tonumber(event[3]) then if tonumber(event[3]) then
if canadates[tonumber(event[3])] then if canadates[tonumber(event[3])] then
ifs.writeAllText("/boot/fstab", "U "..canadates[tonumber(event[3])]..";/\n"..fstab)
fstab="U "..canadates[tonumber(event[3])]..";/\n"..fstab fstab="U "..canadates[tonumber(event[3])]..";/\n"..fstab
ifs.mount(canadates[tonumber(event[3])], "/") ifs.mount(canadates[tonumber(event[3])], "/")
break break
@@ -357,13 +358,8 @@ kernel.loadingModule="kernel"
kernel.perTaskHooks={} kernel.perTaskHooks={}
kernel.mainHooks={} kernel.mainHooks={}
kernel.runhooks={} kernel.runhooks={}
local loadedmodules={}
function kernel.getLoadedModules() -- args {taskobj}
return table.deepcopy(loadedmodules)
end
-- args {taskobj, pid}
function kernel.execPerTask(func, prior) function kernel.execPerTask(func, prior)
if not kernel.perTaskHooks[prior] then kernel.perTaskHooks[prior]={} end if not kernel.perTaskHooks[prior] then kernel.perTaskHooks[prior]={} end
kernel.perTaskHooks[prior][#kernel.perTaskHooks[prior]+1] = func kernel.perTaskHooks[prior][#kernel.perTaskHooks[prior]+1] = func
@@ -435,7 +431,7 @@ kernel.syscalls["getHostname"]=function() return kernel.hostname end
kernel.syscalls["getHost"]=function() return kernel.apis._HOST end kernel.syscalls["getHost"]=function() return kernel.apis._HOST end
kernel.syscalls["version"]=function() return kernel.version 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["setHostname"]=function(name) if kernel.uid~=0 then error("Permission denied") end kernel.hostname=name end
kernel.syscalls["arch"]=function() return kernel.arch end kernel.syscalls["arch"]=function() return arch end
kernel.syscalls["sysdump"]=function() kernel.syscalls["sysdump"]=function()
local rv={} local rv={}
for i,v in pairs(kernel.syscalls) do for i,v in pairs(kernel.syscalls) do
@@ -464,25 +460,22 @@ kernel.syscalls["saveLog"]=function()
end end
end end
ifs.writeAllText("/boot/fstab", fstab)
kernel.saveLog() kernel.saveLog()
kernel.log("Running modules") kernel.log("Running modules")
for _,p in ipairs(modules) do for _,p in ipairs(modules) do
for _,v in ipairs(p) do for _,v in ipairs(p) do
kernel.loadingModule=v kernel.loadingModule=v
EFI:yield()
if not kernel.denied[v] then if not kernel.denied[v] then
if kernel.config.showModLoad then kernel.log("Loading module "..v, "DBUG", 0x00FFFF) end if kernel.config.showModLoad then kernel.log("Loading module "..v, "DBUG", 0x00FFFF) end
local code=ifs.readAllText("/lib/modules/"..v) local code=ifs.readAllText("/lib/modules/"..v)
if not code then if not code then
kernel.panic("Failed to read module "..v) kernel.panic("Failed to read module "..v)
end end
local func,err=load(code,"@"..v,"t",_G) local func,err=load(code,"@"..v)
if not func then kernel.panic("ModuLoadErr: "..tostring(err)) end if not func then kernel.panic("ModuLoadErr: "..tostring(err)) end
local status, err = xpcall(func,debug.traceback, kernel) local status, err = xpcall(func,debug.traceback, kernel)
if not status then kernel.panic("ModuRunErr: "..tostring(err)) end if not status then kernel.panic("ModuRunErr: "..tostring(err)) end
if kernel.config.showModLoad then kernel.log("Loaded module "..v, "DBUG", 0x00FFFF) 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 if kernel.config.moreLogsaves then kernel.saveLog() end
else else
if kernel.config.showModLoad then kernel.log("Denied module "..v, "DBUG", 0xFF0000) end if kernel.config.showModLoad then kernel.log("Denied module "..v, "DBUG", 0xFF0000) end
@@ -509,13 +502,10 @@ if kernel.status=="panic" then
kernel.panic(kernel.reason) kernel.panic(kernel.reason)
end end
if kernel.status=="reboot" then if kernel.status=="reboot" then
EFI.status="reboot" EFI.reboot=true
return true return true
elseif kernel.status=="halt" then elseif kernel.status=="halt" then
kernel.log("System halted.") kernel.log("System halted.")
kernel.saveLog() kernel.saveLog()
while true do EFI:yield() end while true do end
else end
EFI.status="shutdown"
return true
end
+1 -1
View File
@@ -4,7 +4,7 @@
-- This file is auto-generated during the build process. -- This file is auto-generated during the build process.
-- DEFAULT BOOT CONFIGURATION FILE -- DEFAULT BOOT CONFIGURATION FILE
return { return {
initPath = "/usr/lib/sysinit/sysinit", initPath = "/sbin/init",
maxOpenFiles = 128, maxOpenFiles = 128,
maxFilesPerTask = 16, maxFilesPerTask = 16,
preempt = true, preempt = true,
@@ -2,16 +2,6 @@
--- @diagnostic disable: duplicate-set-field --- @diagnostic disable: duplicate-set-field
local kernel = ... local kernel = ...
kernel.allowGlobalOverwrites = true kernel.allowGlobalOverwrites = true
local oldtype = type
local oldgetmetatable = getmetatable
function math.round(x)
if x>=0 then
return math.floor(x+0.5)
else
return math.ceil(x-0.5)
end
end
function string.hasSuffix(str, suffix) function string.hasSuffix(str, suffix)
return string.sub(str, #suffix + 1) == suffix return string.sub(str, #suffix + 1) == suffix
@@ -80,10 +70,6 @@ function table.hasVal(tabl, query)
return false return false
end end
function table.readOnly(tabl, typ)
return setmetatable({},{__index=tabl,__newindex=function()error("Table is read-only")end,__usermeta=false,__type=typ})
end
local function serialize(tbl, seen) local function serialize(tbl, seen)
seen = seen or {} seen = seen or {}
@@ -114,8 +100,6 @@ local function serialize(tbl, seen)
output = output .. "\"" .. tostring(v) .. "\"" output = output .. "\"" .. tostring(v) .. "\""
elseif type(v) == "thread" then elseif type(v) == "thread" then
output = output .. "\"" .. tostring(v) .. "\"" output = output .. "\"" .. tostring(v) .. "\""
elseif oldgetmetatable(v) and oldgetmetatable(v).__tostring then
output = output .. tostring(v)
else else
error("serialization of type \"" .. type(v) .. "\" is not supported") error("serialization of type \"" .. type(v) .. "\" is not supported")
end end
@@ -127,6 +111,8 @@ local function serialize(tbl, seen)
return output return output
end end
local oldtype = type
local oldgetmetatable = getmetatable
function type(object, trueType) function type(object, trueType)
if trueType then return oldtype(object) end if trueType then return oldtype(object) end
if oldtype(object) ~= "table" then if oldtype(object) ~= "table" then
@@ -145,7 +131,7 @@ end
function getmetatable(object) function getmetatable(object)
if oldtype(object) ~= "table" then return end if oldtype(object) ~= "table" then return end
if oldtype(oldgetmetatable(object)) == "table" then if oldtype(oldgetmetatable(object)) == "table" then
if oldgetmetatable(object).__usermeta then if oldgetmetatable(object).__isuserdata then
if oldtype(oldgetmetatable(object).__usermeta) == "function" then if oldtype(oldgetmetatable(object).__usermeta) == "function" then
return oldgetmetatable(object).__usermeta() return oldgetmetatable(object).__usermeta()
else else
@@ -265,6 +251,8 @@ local function makeSyscallProxy()
local backing = {} local backing = {}
return setmetatable(backing, { return setmetatable(backing, {
__index = function(self, name) __index = function(self, name)
local raw = rawget(self, name)
if raw ~= nil then return raw end
return function(...) return function(...)
local res = table.pack(coroutine.yield("syscall", name, ...)) local res = table.pack(coroutine.yield("syscall", name, ...))
if res[1] then if res[1] then
@@ -275,7 +263,7 @@ local function makeSyscallProxy()
end end
end, end,
__newindex = function(self, k, v) __newindex = function(self, k, v)
error("Table is read-only") rawset(self, k, v)
end, end,
__metatable=false __metatable=false
}) })
@@ -283,5 +271,6 @@ end
syscall = makeSyscallProxy() syscall = makeSyscallProxy()
table.serialize = serialize _makeSyscallProxy = makeSyscallProxy
table.serialize = serialize
@@ -299,7 +299,6 @@ local function namei(path, noFollow, symDepth)
if not target or target == "" then if not target or target == "" then
error("ENOENT: empty symlink target") error("ENOENT: empty symlink target")
end end
if kernel.config.logSymlinkTraverse then kernel.log(curPath .. " > " .. target) end
local symIsAbs, symTokens = tokenizePath(target) local symIsAbs, symTokens = tokenizePath(target)
@@ -694,7 +693,7 @@ function vfs.open(path, mode)
if disk:type(diskPath) ~= "directory" then if disk:type(diskPath) ~= "directory" then
handle = disk:open(diskPath, mode) handle = disk:open(diskPath, mode)
if type(handle, true) ~= "table" then if type(handle, true) ~= "table" then
error("ENFILE".." KERR="..type(handle,true)) error("ENFILE")
end end
end end
@@ -973,9 +972,6 @@ function vfs.symlink(target, linkPath)
if type(target) ~= "string" or type(linkPath) ~= "string" then error("EINVAL") end if type(target) ~= "string" or type(linkPath) ~= "string" then error("EINVAL") end
local norm = normalizePath(linkPath) local norm = normalizePath(linkPath)
local parent = norm:match("^(.*)/[^/]+$") or "/" local parent = norm:match("^(.*)/[^/]+$") or "/"
if not vfs.exists(parent) then
vfs.mkdir(parent)
end
local disk = resolveMount(linkPath) local disk = resolveMount(linkPath)
if disk:isReadOnly() then error("ERDONLY") end if disk:isReadOnly() then error("ERDONLY") end
if parent == "" then parent = "/" end if parent == "" then parent = "/" end
@@ -1020,7 +1016,7 @@ function vfs.access(path, mode)
return true return true
end end
local function updateMeta(path, fn, noFollow, nullify) local function updateMeta(path, fn, noFollow)
local real = namei(path, noFollow) local real = namei(path, noFollow)
local norm = real local norm = real
local parent = norm:match("^(.*)/[^/]+$") or "/" local parent = norm:match("^(.*)/[^/]+$") or "/"
@@ -1045,13 +1041,9 @@ local function updateMeta(path, fn, noFollow, nullify)
if uf.close then uf.close() end if uf.close then uf.close() end
existing = parseMetafile(raw) existing = parseMetafile(raw)
end end
if not nullify then local entry = existing[name] or { etype=0, owner=0, group=0, perms=63, cmeta="" }
local entry = existing[name] or { etype=0, owner=0, group=0, perms=63, cmeta="" } fn(entry)
fn(entry) existing[name] = 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 local f = disk:open(mp, "w"); f.write(makeMetafile(existing)); if f.close then f.close() end
end end
@@ -1062,7 +1054,7 @@ function vfs.chmod(path, perms)
local meta = getFileMeta(path) local meta = getFileMeta(path)
local euid = (kernel.currentTask and (kernel.currentTask.euid or kernel.currentTask.uid)) or kernel.uid 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 if euid ~= 0 and euid ~= meta.owner then error("EACCES") end
updateMeta(path, function(e) e.perms = perms end, nil, not perms) updateMeta(path, function(e) e.perms = perms end)
end end
function vfs.fchmod(fd, perms) function vfs.fchmod(fd, perms)
@@ -1166,27 +1158,7 @@ function vfs.devlst(fd)
return table.keys(kernel.currentTask.fd[fd].handle) return table.keys(kernel.currentTask.fd[fd].handle)
end end
function vfs.getOpenFds()
local out={}
for i,v in ipairs(kernel.currentTask.fd) do
out[i]=v.path
end
return out
end
function vfs.fsinfo()
local out={mounts={},disks={}}
for i,v in pairs(vfs.mounts) do
out.mounts[i]=v
end
for i,v in pairs(vfs.disks) do
out.disks[i]={size=vfs.disks[i].spaceTotal(),used=vfs.disks[i].spaceUsed(),label=vfs.disks[i].getLabel(),readOnly=vfs.disks[i].isReadOnly(),isVirt=vfs.disks[i].isvirt,address=vfs.disks[i].addressz}
end
return out
end
vfs.resolveMount = resolveMount vfs.resolveMount = resolveMount
vfs.updateMeta = updateMeta
local sys = kernel.syscalls local sys = kernel.syscalls
sys["open"] = vfs.open sys["open"] = vfs.open
@@ -1226,7 +1198,5 @@ sys["fget_suid"] = function(fd)
local fobj = kernel.currentTask and kernel.currentTask.fd[fd] local fobj = kernel.currentTask and kernel.currentTask.fd[fd]
return fobj and fobj.suid_owner or nil return fobj and fobj.suid_owner or nil
end end
sys["getOpenFds"]= vfs.getOpenFds
sys["fsinfo"] = vfs.fsinfo
kernel.log("VFS module loaded") kernel.log("VFS module loaded")
@@ -7,12 +7,8 @@ kernel.searchpaths = {
} }
kernel.reqcache = cache kernel.reqcache = cache
local function wrap(lib)
return setmetatable({},{__index=lib,__newindex=function()error("Table is read-only")end,__usermeta=false,__call=function(s,...) return lib.new(...) end})
end
local function require(module, ...) local function require(module, ...)
if cache[module] then return wrap(cache[module].ret) end if cache[module] then return cache[module].ret end
local args = {...} local args = {...}
for _, path in ipairs(kernel.searchpaths) do for _, path in ipairs(kernel.searchpaths) do
local filepath = path:gsub("?", module) local filepath = path:gsub("?", module)
@@ -40,8 +36,8 @@ local function require(module, ...)
if not ok then if not ok then
error("Error running module "..module..": "..tostring(ret)) error("Error running module "..module..": "..tostring(ret))
end end
cache[module] = {ret = ret} cache[module] = {ret = ret, expires = kernel.EFI:getEpochMs() + 120000}
return wrap(ret) return ret
end end
coroutine.yield() coroutine.yield()
end end
@@ -239,7 +239,6 @@ if kernel.EFI.getEEPROM then
write=function(data) write=function(data)
if firstwrite then if firstwrite then
kernel.EFI:setEEPROM(data) kernel.EFI:setEEPROM(data)
firstwrite=false
else else
kernel.EFI:setEEPROM(kernel.EFI:getEEPROM()..data) kernel.EFI:setEEPROM(kernel.EFI:getEEPROM()..data)
end end
@@ -277,7 +276,6 @@ if kernel.EFI.getNvram then
write=function(data) write=function(data)
if firstwrite then if firstwrite then
kernel.EFI:setNvram(data) kernel.EFI:setNvram(data)
firstwrite=false
else else
kernel.EFI:setNvram(kernel.EFI:getNvram()..data) kernel.EFI:setNvram(kernel.EFI:getNvram()..data)
end end
@@ -103,7 +103,7 @@ local function newtaskproxy(task)
children[tostring(v.pid)]="/proc/"..tostring(v.pid) children[tostring(v.pid)]="/proc/"..tostring(v.pid)
end end
return { return {
[".meta"]=strFile(buildMeta({cwd=task.cwd,parent="/proc/"..tostring(task.parent.pid),root=task.root or "/"})), [".meta"]=strFile(buildMeta({cwd=task.cwd,parent="/proc/"..tostring(task.parent.pid)})),
uid=strFile(task.uid), uid=strFile(task.uid),
comm=strFile(task.name), comm=strFile(task.name),
fd={ fd={
@@ -115,9 +115,7 @@ local function newtaskproxy(task)
children={ children={
[".meta"]=strFile(buildMeta(children)) [".meta"]=strFile(buildMeta(children))
}, },
pid=strFile(task.pid), pid=strFile(task.pid)
ivs=strFile(task.ivs),
vs=strFile(task.vs)
} }
end end
@@ -1,3 +0,0 @@
--:Minify:--
local kernel = ...
@@ -1,82 +0,0 @@
--:Minify:--
local kernel = ...
local proxy = {}
local data = {}
proxy.address = "devfs0000"
proxy.isvirt = true
proxy.isReadOnly = function() return false end
proxy.spaceUsed = function() return 0 end
proxy.spaceTotal = function() return 0 end
proxy.makeDirectory = function() error("EACCES") end
proxy.remove = function() error("EACCES") end
proxy.setLabel = function() error("EACCES") end
proxy.getLabel = function() return "devfs" end
proxy.attributes = function(path) return {
size = 0,
modified = 0,
created = 0
} end
function proxy:open(path, mode)
local steps = kernel.vfs.splitPath(path)
local step = data
for i=1, #steps-1 do
local dat = step[steps[i]]
if type(dat) ~= "table" then error("ENFILE") end
step=dat
end
if type(step[steps[#steps]]) == "function" then
return step[steps[#steps]]("open", mode)
end
error("ENFILE")
end
function proxy:type(path, mode)
local steps = kernel.vfs.splitPath(path)
local step = data
if #steps == 0 then
return "directory"
end
for i=1, #steps-1 do
local dat = step[steps[i]]
if type(dat) ~= "table" then error("ENFILE") end
step=dat
end
if type(step[steps[#steps]]) == "function" then
return step[steps[#steps]]("type", mode)
end
if type(step[steps[#steps]]) == "table" then
return "directory"
end
error("ENOENT")
end
function proxy:list(path)
local steps = kernel.vfs.splitPath(path)
local step = data
if #steps == 0 then
return table.keys(data)
end
for i=1, #steps-1 do
local dat = step[steps[i]]
if type(dat) ~= "table" then error("ENOENT") end
step=dat
end
if type(step[steps[#steps]]) == "table" then
return table.keys(step[steps[#steps]])
end
error("ENOENT")
end
function proxy:fileExists(path)
local ok = pcall(function()
return self:type(path)
end)
return ok
end
kernel.sysfs={}
kernel.sysfs.proxy=proxy
kernel.disks["sysfs0000"]=proxy
@@ -1,283 +1,102 @@
--:Minify:-- --:Minify:--
local kernel = ... local kernel = ...
local os = os
if not kernel.config.tmpToDisk then if not kernel.config.tmpToDisk then
local proxy = {} local proxy = {}
local data = {} 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.address = "tmpfs0000"
proxy.isvirt = true proxy.isvirt = true
proxy.isReadOnly = function() proxy.isReadOnly = function() return false end
return false
end
proxy.spaceUsed = function() proxy.spaceUsed = function() return 0 end
local function size(step) proxy.spaceTotal = function() return 0 end
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) proxy.makeDirectory = function(_, path)
local steps = kernel.vfs.splitPath(path) local steps = kernel.vfs.splitPath(path)
local step = data local step = data
local current = "" for i=1,#steps do
for i = 1, #steps do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
if not step[steps[i]] then if not step[steps[i]] then
step[steps[i]] = {} step[steps[i]] = {}
touch(current)
elseif type(step[steps[i]]) ~= "table" then elseif type(step[steps[i]]) ~= "table" then
error("ENOTDIR") error("ENOTDIR")
end end
step = step[steps[i]] step = step[steps[i]]
end end
end end
proxy.remove = function(_, path) proxy.remove = function(_, path)
local steps = kernel.vfs.splitPath(path) local steps = kernel.vfs.splitPath(path)
if #steps == 0 then
error("EACCES")
end
local step = data local step = data
local current = "" for i=1,#steps-1 do
for i = 1, #steps - 1 do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
step = step[steps[i]] step = step[steps[i]]
if not step then if not step then error("ENOENT") end
error("ENOENT")
end
if type(step) ~= "table" then
error("ENOTDIR")
end
end end
step[steps[#steps]] = nil
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 end
proxy.setLabel = function(_, label) proxy.setLabel = function(_, label) end
end proxy.getLabel = function() return "tmpfs" end
proxy.getLabel = function()
return "tmpfs"
end
proxy.attributes = function(_, path) proxy.attributes = function(_, path)
local steps = kernel.vfs.splitPath(path) local steps = kernel.vfs.splitPath(path)
local step = data local step = data
local current = "" for i=1,#steps do
for i = 1, #steps do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
step = step[steps[i]] step = step[steps[i]]
if step == nil then if not step then error("ENOENT") end
error("ENOENT")
end
end end
local time = getTimestamp(current)
return { return {
size = type(step) == "string" and #step or 0, size = type(step) == "string" and #step or 0,
modified = time.modified, modified = 0,
created = time.created, created = 0,
} }
end end
function proxy:open(path, mode) function proxy:open(path, mode)
local steps = kernel.vfs.splitPath(path) local steps = kernel.vfs.splitPath(path)
if #steps == 0 then
error("EISDIR")
end
local step = data local step = data
local current = "" for i=1,#steps-1 do
for i = 1, #steps - 1 do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
if not step[steps[i]] then if not step[steps[i]] then
if mode == "w" then if mode == "w" then step[steps[i]] = {} else error("ENOENT") end
step[steps[i]] = {}
touch(current)
else
error("ENOENT")
end
elseif type(step[steps[i]]) ~= "table" then elseif type(step[steps[i]]) ~= "table" then
error("ENOTDIR") error("ENOTDIR")
end end
step = step[steps[i]] step = step[steps[i]]
end end
local filename = steps[#steps] local filename = steps[#steps]
local filepath = current == "" and filename
or current .. "/" .. filename
if mode == "r" then if mode == "r" then
if type(step[filename]) ~= "string" then if type(step[filename]) ~= "string" then error("ENOENT") end
if type(step[filename]) == "table" then
error("EISDIR")
end
error("ENOENT")
end
local content = step[filename] local content = step[filename]
local pos = 1 local pos = 1
return { return {
read = function(amount) read = function(amount)
amount = amount or #content amount = amount or #content
local chunk = content:sub(pos, pos + amount - 1) local chunk = content:sub(pos, pos+amount-1)
pos = pos + #chunk pos = pos + #chunk
if chunk == "" then
return nil
end
return chunk return chunk
end, end,
close = function() close = function() end,
end,
} }
elseif mode == "w" then elseif mode == "w" then
if type(step[filename]) == "table" then step[filename] = ""
error("EISDIR")
end
local buf = {} local buf = {}
local closed = false
return { return {
write = function(str) write = function(str)
if closed then buf[#buf + 1] = str
error("EBADF")
end
buf[#buf + 1] = tostring(str)
end, end,
close = function() close = function()
if closed then
return
end
closed = true
local existed = type(step[filename]) == "string"
step[filename] = table.concat(buf) step[filename] = table.concat(buf)
if not existed then
local time = now()
timestamps[filepath] = {
created = time,
modified = time,
}
else
touch(filepath)
end
end, end,
} }
elseif mode == "a" then elseif mode == "a" then
if type(step[filename]) == "table" then if type(step[filename]) ~= "string" then step[filename] = "" end
error("EISDIR")
end
local buf = {
type(step[filename]) == "string" and step[filename] or ""
}
local closed = false
return { return {
write = function(str) write = function(str)
if closed then step[filename] = step[filename] .. str
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, end,
close = function() end,
} }
else else
error("EACCES") error("EACCES")
end end
@@ -286,57 +105,25 @@ if not kernel.config.tmpToDisk then
function proxy:type(path) function proxy:type(path)
local steps = kernel.vfs.splitPath(path) local steps = kernel.vfs.splitPath(path)
local step = data local step = data
if #steps == 0 then return "directory" end
if #steps == 0 then for i=1,#steps do
return "directory"
end
for i = 1, #steps do
if type(step) ~= "table" then
return false
end
step = step[steps[i]] step = step[steps[i]]
if step == nil then if not step then return false end
return false
end
end
if type(step) == "table" then
return "directory"
end
if type(step) == "string" then
return "file"
end end
if type(step) == "table" then return "directory" end
if type(step) == "string" then return "file" end
end end
function proxy:list(path) function proxy:list(path)
local steps = kernel.vfs.splitPath(path) local steps = kernel.vfs.splitPath(path)
local step = data local step = data
local current = "" for i=1,#steps do
for i = 1, #steps do
current = current == "" and steps[i]
or current .. "/" .. steps[i]
if type(step) ~= "table" then
error("ENOTDIR")
end
step = step[steps[i]] step = step[steps[i]]
if step == nil then if not step then error("ENOENT") end
error("ENOENT")
end
end end
if type(step) ~= "table" then error("ENOTDIR") end
if type(step) ~= "table" then
error("ENOTDIR")
end
local keys = {} local keys = {}
for k in pairs(step) do for k,_ in pairs(step) do table.insert(keys, k) end
keys[#keys + 1] = k
end
return keys return keys
end end
@@ -346,11 +133,9 @@ if not kernel.config.tmpToDisk then
end end
kernel.disks["tmpfs0000"] = proxy kernel.disks["tmpfs0000"] = proxy
kernel.tmpfs={data=data,proxy=proxy}
else else
kernel.log("tmpToDisk enabled, skipping tmpfs module") kernel.log("tmpToDisk enabled, skipping tmpfs module")
kernel.log("tmpfs0000 will passthrough to /tmp on the disk") kernel.log("tmpfs0000 will passthrough to /tmp on the disk")
kernel.runWhenLoaded(function() kernel.runWhenLoaded(function()
kernel.vfs.remove("/tmp") kernel.vfs.remove("/tmp")
kernel.vfs.mkdir("/tmp") kernel.vfs.mkdir("/tmp")
@@ -37,7 +37,7 @@ kernel.execPerTask(function(task)
if task.sigq and #task.sigq ~= 0 and task.sigh then if task.sigq and #task.sigq ~= 0 and task.sigh then
local coro = coroutine.create(task.sigh) local coro = coroutine.create(task.sigh)
local status,err=coroutine.resume(coro, table.remove(task.sigq, 1)) local status,err=coroutine.resume(coro, table.remove(task.sigq, 1))
kernel.EFI:yield() EFI:yeild()
if status=="error" or status==false then if status=="error" or status==false then
task.sigd.error=err or "Unknown" task.sigd.error=err or "Unknown"
task.sigd.active=false task.sigd.active=false
@@ -160,19 +160,7 @@ function socket.recv(fd, amount)
return nil, "EOPNOTSUPP" return nil, "EOPNOTSUPP"
end end
local ret = fdo.handle.read(amount) return 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 end
function socket.sockshutdown(fd) function socket.sockshutdown(fd)
@@ -2,5 +2,3 @@
local kernel=... local kernel=...
kernel.unixSockets={} kernel.unixSockets={}
local socket=kernel.socket local socket=kernel.socket
--socket.registerProtocal()
@@ -58,12 +58,10 @@ kernel._U.load = function(a,b,c,d) return origLoad(a,b,c,d or kernel._U) end
function kernel.freshUserEnv() function kernel.freshUserEnv()
local locals = {} local locals = {}
locals.syscall = _makeSyscallProxy()
local env = setmetatable(locals, { local env = setmetatable(locals, {
__index = kernel._U, __index = kernel._U,
__pairs = function(self)
return pairs(kernel._U)
end,
__newindex = function(_, k, v) rawset(locals, k, v) end, __newindex = function(_, k, v) rawset(locals, k, v) end,
__metatable=false __metatable=false
}) })
@@ -33,7 +33,7 @@ local function createVt(id, width, height)
end end
end end
function vt.obj.write(content) function vt.obj:write(content)
local x, y = vt.cursorX, vt.cursorY local x, y = vt.cursorX, vt.cursorY
if x>vt.width then return end if x>vt.width then return end
if y>vt.height then return end if y>vt.height then return end
@@ -79,36 +79,36 @@ local function createVt(id, width, height)
vt.cursorX, vt.cursorY = x, y vt.cursorX, vt.cursorY = x, y
end end
function vt.obj.spos(x, y) function vt.obj:spos(x, y)
vt.cursorX = tonumber(x) vt.cursorX = tonumber(x)
vt.cursorY = tonumber(y) vt.cursorY = tonumber(y)
end end
function vt.obj.gpos() function vt.obj:gpos()
return vt.cursorX, vt.cursorY return tostring(vt.cursorX)..";"..tostring(vt.cursorY)
end end
function vt.obj.sfgc(color) function vt.obj:sfgc(color)
vt.fgColor = tonumber(color) vt.fgColor = tonumber(color)
end end
function vt.obj.sbgc(color) function vt.obj:sbgc(color)
vt.bgColor = tonumber(color) vt.bgColor = tonumber(color)
end end
function vt.obj.gfgc() function vt.obj:gfgc()
return vt.fgColor return vt.fgColor
end end
function vt.obj.gbgc() function vt.obj:gbgc()
return vt.bgColor return vt.bgColor
end end
function vt.obj.gplt() function vt.obj:gplt()
return 24 return 24
end end
function vt.obj.clear() function vt.obj:clear()
for y = 1, vt.height do for y = 1, vt.height do
for x = 1, vt.width do for x = 1, vt.width do
vt.buffer[y][x] = {char = " ", fgColor = vt.fgColor, bgColor = vt.bgColor} vt.buffer[y][x] = {char = " ", fgColor = vt.fgColor, bgColor = vt.bgColor}
@@ -117,12 +117,12 @@ local function createVt(id, width, height)
vt.cursorX, vt.cursorY = 1, 1 vt.cursorX, vt.cursorY = 1, 1
end end
function vt.obj.isvirt() function vt.obj:isvirt()
return true return true
end end
function vt.obj.gfx() function vt.obj:gctrl()
return serializeBool(vt.ctrl)..";"..serializeBool(vt.alt)
end end
return vt return vt
@@ -10,62 +10,26 @@ local function bit_is_set(num, bit)
return math.floor(num / (2 ^ bit)) % 2 == 1 return math.floor(num / (2 ^ bit)) % 2 == 1
end end
local function loadExecutable(path) local function loadExecutable(path)
kernel.vfs.access(path, "rx") 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 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) 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 env = kernel.freshUserEnv()
local func, err = load(data, "@" .. path, "t", env) 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 local meta = kernel.vfs.lstat(path)
kernel.log( local suid_set = bit_is_set(meta.perms, 6)
"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)
local caller_uid = kernel.currentTask and kernel.currentTask.uid or kernel.uid local caller_uid = kernel.currentTask and kernel.currentTask.uid or kernel.uid
local euid = suid_set and meta.owner or caller_uid local euid = suid_set and meta.owner or caller_uid
return func, euid, suid_set return func, euid, suid_set
end end
local function createTask(func, name, envars, args, tgid, real_uid, eff_uid, clearFds) local function createTask(func, name, envars, args, tgid, real_uid, eff_uid, clearFds)
local id = nextpid local id = nextpid
nextpid = nextpid + 1 nextpid = nextpid + 1
@@ -144,7 +108,7 @@ function sys.spawn(func, name, envars, args, tgid, clearFds)
end end
function sys.execspawn(path, name, envars, args, tgid, keepFds) function sys.execspawn(path, name, envars, args, tgid, keepFds)
local func, euid, suid_active = loadExecutable(path) local func, euid, suid_active = loadExecutable(path, kernel._U)
local caller = kernel.currentTask local caller = kernel.currentTask
local real_uid = caller and caller.uid or kernel.uid local real_uid = caller and caller.uid or kernel.uid
@@ -160,26 +124,21 @@ function sys.execspawn(path, name, envars, args, tgid, keepFds)
return createTask(func, name or path, envars, args, tgid, real_uid, euid, not keepFds) return createTask(func, name or path, envars, args, tgid, real_uid, euid, not keepFds)
end end
function sys.exec(path, args, envars, clearFds) function sys.exec(path, args, envars)
local task = kernel.currentTask local task = kernel.currentTask
local func, euid, _ = loadExecutable(path) local func, euid, _ = loadExecutable(path, kernel._U)
-- no idea why this is here? -- no idea why this is here?
-- Figured it out it is to close fds on su --if task.fd then
if clearFds then -- for fd, _ in pairs(task.fd) do
if task.fd then -- if fd > 2 then pcall(kernel.vfs.close, fd) end
for fd, _ in pairs(task.fd) do -- end
if fd > 2 then pcall(kernel.vfs.close, fd) end --end
end
end
end
task.euid = euid task.euid = euid
task.args = args or {} task.args = args or {}
task.envars = envars or task.envars or {} task.envars = envars or task.envars or {}
task.name = path task.name = path
task.ivs = 0
task.vs = 0
task.coro = coroutine.create(function() task.coro = coroutine.create(function()
local ok, err = xpcall(func, debug.traceback, table.unpack(task.args)) local ok, err = xpcall(func, debug.traceback, table.unpack(task.args))
@@ -289,7 +248,7 @@ function sys.stop(pid)
end end
end end
function sys.cont(pid) function sys.continue(pid)
local task = tasks[tostring(pid)] local task = tasks[tostring(pid)]
if not task then if not task then
return false, "Task does not exist" return false, "Task does not exist"
@@ -432,7 +391,7 @@ sysc["getTask"] = sys.getTask
sysc["collect"] = sys.collect sysc["collect"] = sys.collect
sysc["kill"] = sys.kill sysc["kill"] = sys.kill
sysc["stop"] = sys.stop sysc["stop"] = sys.stop
sysc["continue"] = sys.cont sysc["continue"] = sys.continue
sysc["getpid"] = sys.getpid sysc["getpid"] = sys.getpid
sysc["getppid"] = sys.getppid sysc["getppid"] = sys.getppid
sysc["getTasks"] = sys.getTasks sysc["getTasks"] = sys.getTasks
@@ -1,7 +1,7 @@
--:Minify:-- --:Minify:--
local kernel=... local kernel=...
kernel.debug=debug local debug=debug
kernel._G.debug={ kernel._G.debug={
getinfo=kernel.debug.getinfo, getinfo=debug.getinfo,
traceback=kernel.debug.traceback traceback=debug.traceback
} }
@@ -14,22 +14,11 @@ local data = kernel.vfs.read(handle, 1024 * 1024 * 4)
if not handle then kernel.panic("Failed to read "..kernel.config.initPath) end if not handle then kernel.panic("Failed to read "..kernel.config.initPath) end
kernel.vfs.close(handle) kernel.vfs.close(handle)
local initFunc, err = load(data, "@init", "t", kernel._U) local initFunc, err = load(data, "@sysinit", "t", kernel._U)
if not initFunc then kernel.PANIC("Failed to load init system: " .. err) end if not initFunc then kernel.PANIC("Failed to load init system: " .. err) end
kernel.tasks["1"] = { kernel.tasks["1"] = {
coro = coroutine.create(function() coro = coroutine.create(function()
for i,v in pairs(kernel.processes) do
kernel.log("Spawning kernel task "..i)
syscall.spawn(function()
local status, err = pcall(v)
if not status then
kernel.log("Error executing kernel task '" .. i .. "': " .. err, "ERROR", 0xFF0000)
else
kernel.log("Successfully executed kernel task: " .. i)
end
end, i, nil,nil,nil,true)
end
local ok, err = xpcall(initFunc, debug.traceback, kernel) local ok, err = xpcall(initFunc, debug.traceback, kernel)
if not ok then if not ok then
kernel.panic("Init system crashed: " .. tostring(err)) kernel.panic("Init system crashed: " .. tostring(err))
@@ -39,7 +28,7 @@ kernel.tasks["1"] = {
kernel.saveLog() kernel.saveLog()
end), end),
name = "init", name = "sysinit",
status = "R", status = "R",
pid = 1, pid = 1,
tgid = 1, tgid = 1,
@@ -2,11 +2,11 @@
local kernel = ... local kernel = ...
kernel.processes.kgc = function() kernel.processes.kgc = function()
while true do while true do
--for i,v in pairs(kernel.reqcache) do for i,v in pairs(kernel.reqcache) do
-- if v.expires and kernel.EFI:getEpochMs() > v.expires then if v.expires and kernel.EFI:getEpochMs() > v.expires then
-- kernel.reqcache[i] = nil kernel.reqcache[i] = nil
-- end end
--end end
sleep(5) sleep(5)
end end
end end
@@ -1,10 +1,7 @@
--:Minify:-- --:Minify:--
local kernel = ... local kernel = ...
if kernel.firstBoot or kernel.config.resetPerms then if kernel.firstBoot then
if kernel.config.resetPerms then
kernel.log("resetPerms is active, disable it in /boot/boot.cfg", "WARN", 0xFFFF00)
end
kernel.log("Seeding filesystem permissions...") kernel.log("Seeding filesystem permissions...")
local P = kernel.vfs.P local P = kernel.vfs.P
@@ -21,23 +18,20 @@ if kernel.firstBoot or kernel.config.resetPerms then
local function seed(root, data) local function seed(root, data)
for i=1,#data do for i=1,#data do
local entry=data[i] local entry=data[1]
if kernel.vfs.exists(root..entry[1]) then kernel.vfs.chmod(root..entry[1],entry[2],entry[3])
kernel.vfs.updateMeta(root..entry[1],function(e) kernel.vfs.chown(root..entry[1],entry[4])
e.perms=entry[4]
e.group=entry[3]
e.owner=entry[2]
end)
end
end end
end end
seed("/", { seed("/", {
{"bin", 0, 0, RWX_RX_RX}, {"bin", 0, 0, RWX_RX_RX},
{"boot", 0, 0, RWX_RX_RX}, {"boot", 0, 0, RWX_RX_RX},
{"dev", 0, 0, RWXRWXRWX},
{"etc", 0, 0, RWX_RX_RX}, {"etc", 0, 0, RWX_RX_RX},
{"home", 0, 0, RWX_RX_RX}, {"home", 0, 0, RWX_RX_RX},
{"lib", 0, 0, RWX_RX_RX}, {"lib", 0, 0, RWX_RX_RX},
{"proc", 0, 0, RWXRWXRWX},
{"root", 0, 0, RW____ }, {"root", 0, 0, RW____ },
{"sbin", 0, 0, RWX_RX_RX}, {"sbin", 0, 0, RWX_RX_RX},
{"tmp", 0, 0, RWXRWXRWX}, {"tmp", 0, 0, RWXRWXRWX},
+1 -1
View File
@@ -1 +1 @@
1.2.5 1.5.0
-1
View File
@@ -1 +0,0 @@
Hyperion
-2
View File
@@ -1,2 +0,0 @@
Hyperion-kernel
Hyperion-core
-1
View File
@@ -1 +0,0 @@
HyperionOS install package-group
-1
View File
@@ -1 +0,0 @@
1.2.5
-1
View File
@@ -1 +0,0 @@
Hyperion
-10
View File
@@ -1,10 +0,0 @@
Hyperion-kernel
Hyperion-core
coreutils
spm
sysinit
hysh
lua
micro
Hypersplash
math
-1
View File
@@ -1 +0,0 @@
HyperionOS install package-group
-1
View File
@@ -1 +0,0 @@
1.2.5
-1
View File
@@ -1 +0,0 @@
Hyperion
-6
View File
@@ -1,6 +0,0 @@
Hyperion-kernel
Hyperion-core
coreutils
hysh
lua
wget
-1
View File
@@ -1 +0,0 @@
HyperionOS install package-group
-1
View File
@@ -1 +0,0 @@
1.2.5
+1 -1
View File
@@ -58,7 +58,7 @@ syscall.setEnviron("HOME", homedir)
syscall.setEnviron("USER", username) syscall.setEnviron("USER", username)
syscall.setEnviron("SHELL", shell) syscall.setEnviron("SHELL", shell)
local ok, err = pcall(syscall.exec, shell, nil, nil, true) local ok, err = pcall(syscall.exec, shell)
if not ok then if not ok then
print("su: cannot exec shell '" .. shell .. "': " .. tostring(err)) print("su: cannot exec shell '" .. shell .. "': " .. tostring(err))
syscall.exit(1) syscall.exit(1)
File renamed without changes.
+40
View File
@@ -0,0 +1,40 @@
--:Minify:--
local lib = {}
function lib.frame(frame)
local handle = {}
function handle.setPixel(x,y,color24)
end
function handle.getPixel(x,y)
end
function handle.setPixels(x,y,framebuffer)
end
function handle.getPixels(x,y,w,h)
end
function handle.frame(x,y,w,h,writeonly)
end
function handle.framectl(id,x,y,w,h,writeonly)
end
function handle.drawframe()
end
function handle.line()
end
return handle
end
@@ -143,7 +143,7 @@ function Font:print(x, y, text, r, g, b)
local glyph = self._glyphs[code] local glyph = self._glyphs[code]
if glyph then if glyph then
local buf = getGlyphBuffer(glyph, r, g, b) local buf = getGlyphBuffer(glyph, r, g, b)
screen.writeData(cur, y, buf, glyph.width) screen.drawPixels(cur, y, buf, glyph.width, glyph.height)
cur = cur + glyph.width + spacing cur = cur + glyph.width + spacing
end end
end end
+1
View File
@@ -0,0 +1 @@
package providing kernel support for framebuffers and graphics
+256
View File
@@ -0,0 +1,256 @@
#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
+350
View File
@@ -0,0 +1,350 @@
term.setGraphicsMode(2)
local w,h = term.getSize(2)
local fb={}
for i=1, h do
fb[i]={}
for x=1, w do
fb[i][x]=0
end
end
local function setPixel(x,y,c)
--local old=fb[y]
--fb[y]=string.sub(old,1,x-1)..string.char(c)..string.sub(old,x+1)
fb[y][x]=c
end
local function setPixels(x,y,frame)
local w,h = #fb[1], #fb
for i=1, #frame do
for j=1, #frame[i] do
fb[y+i-1][x+j-1]=frame[i][j]
end
end
end
local function getPixel(x,y)
return fb[y][x]
end
local function getPixels(x,y,w,h)
local ret={}
for i=y, y+h do
ret[#ret+1] = {table.unpack(fb[i], x, x+w)}
end
return ret
end
local colors = {
[0]=0x000000,
0x0b0b0b,
0x222222,
0x444444,
0x555555,
0x777777,
0x888888,
0xaaaaaa,
0xbbbbbb,
0xdddddd,
0xeeeeee,
0x00000b,
0x000022,
0x000044,
0x000055,
0x000077,
0x000088,
0x0000aa,
0x0000bb,
0x0000dd,
0x0000ee,
0x000b00,
0x002200,
0x004400,
0x005500,
0x007700,
0x008800,
0x00aa00,
0x00bb00,
0x00dd00,
0x00ee00,
0x0b0000,
0x220000,
0x440000,
0x550000,
0x770000,
0x880000,
0xaa0000,
0xbb0000,
0xdd0000,
0xee0000,
0x000033,
0x000066,
0x000099,
0x0000cc,
0x0000ff,
0x003300,
0x003333,
0x003366,
0x003399,
0x0033cc,
0x0033ff,
0x006600,
0x006633,
0x006666,
0x006699,
0x0066cc,
0x0066ff,
0x009900,
0x009933,
0x009966,
0x009999,
0x0099cc,
0x0099ff,
0x00cc00,
0x00cc33,
0x00cc66,
0x00cc99,
0x00cccc,
0x00ccff,
0x00ff00,
0x00ff33,
0x00ff66,
0x00ff99,
0x00ffcc,
0x00ffff,
0x330000,
0x330033,
0x330066,
0x330099,
0x3300cc,
0x3300ff,
0x333300,
0x333333,
0x333366,
0x333399,
0x3333cc,
0x3333ff,
0x336600,
0x336633,
0x336666,
0x336699,
0x3366cc,
0x3366ff,
0x339900,
0x339933,
0x339966,
0x339999,
0x3399cc,
0x3399ff,
0x33cc00,
0x33cc33,
0x33cc66,
0x33cc99,
0x33cccc,
0x33ccff,
0x33ff00,
0x33ff33,
0x33ff66,
0x33ff99,
0x33ffcc,
0x33ffff,
0x660000,
0x660033,
0x660066,
0x660099,
0x6600cc,
0x6600ff,
0x663300,
0x663333,
0x663366,
0x663399,
0x6633cc,
0x6633ff,
0x666600,
0x666633,
0x666666,
0x666699,
0x6666cc,
0x6666ff,
0x669900,
0x669933,
0x669966,
0x669999,
0x6699cc,
0x6699ff,
0x66cc00,
0x66cc33,
0x66cc66,
0x66cc99,
0x66cccc,
0x66ccff,
0x66ff00,
0x66ff33,
0x66ff66,
0x66ff99,
0x66ffcc,
0x66ffff,
0x990000,
0x990033,
0x990066,
0x990099,
0x9900cc,
0x9900ff,
0x993300,
0x993333,
0x993366,
0x993399,
0x9933cc,
0x9933ff,
0x996600,
0x996633,
0x996666,
0x996699,
0x9966cc,
0x9966ff,
0x999900,
0x999933,
0x999966,
0x999999,
0x9999cc,
0x9999ff,
0x99cc00,
0x99cc33,
0x99cc66,
0x99cc99,
0x99cccc,
0x99ccff,
0x99ff00,
0x99ff33,
0x99ff66,
0x99ff99,
0x99ffcc,
0x99ffff,
0xcc0000,
0xcc0033,
0xcc0066,
0xcc0099,
0xcc00cc,
0xcc00ff,
0xcc3300,
0xcc3333,
0xcc3366,
0xcc3399,
0xcc33cc,
0xcc33ff,
0xcc6600,
0xcc6633,
0xcc6666,
0xcc6699,
0xcc66cc,
0xcc66ff,
0xcc9900,
0xcc9933,
0xcc9966,
0xcc9999,
0xcc99cc,
0xcc99ff,
0xcccc00,
0xcccc33,
0xcccc66,
0xcccc99,
0xcccccc,
0xccccff,
0xccff00,
0xccff33,
0xccff66,
0xccff99,
0xccffcc,
0xccffff,
0xff0000,
0xff0033,
0xff0066,
0xff0099,
0xff00cc,
0xff00ff,
0xff3300,
0xff3333,
0xff3366,
0xff3399,
0xff33cc,
0xff33ff,
0xff6600,
0xff6633,
0xff6666,
0xff6699,
0xff66cc,
0xff66ff,
0xff9900,
0xff9933,
0xff9966,
0xff9999,
0xff99cc,
0xff99ff,
0xffcc00,
0xffcc33,
0xffcc66,
0xffcc99,
0xffcccc,
0xffccff,
0xffff00,
0xffff33,
0xffff66,
0xffff99,
0xffffcc,
0xffffff,
}
for i=0,255 do
term.setPaletteColor(i,colors[i])
end
term.drawPixels(0,0,fb)
for i=0,255 do
for y=1+i, h-i do
for x=1+i, w-i do
setPixel(x,y,i)
end
end
term.drawPixels(1,1,fb)
os.queueEvent("nosleep")
os.pullEvent()
end
for i=1, 1000 do
pcall(function()
setPixels(math.random(1,w),math.random(1,h),getPixels(math.random(1,w),math.random(1,h),math.random(1,w),math.random(1,h)))
end)
term.drawPixels(1,1,fb)
os.queueEvent("nosleep")
os.pullEvent()
end
setPixels(1,1,getPixels(w-50,h-50,50,50))
term.drawPixels(0,0,fb)
local i=0
for x=1, 16*4, 4 do
for y=1, 16*4, 4 do
setPixel(x,y,i)
setPixel(x+1,y,i)
setPixel(x+2,y,i)
setPixel(x+3,y,i)
setPixel(x,y+1,i)
setPixel(x+1,y+1,i)
setPixel(x+2,y+1,i)
setPixel(x+3,y+1,i)
setPixel(x,y+2,i)
setPixel(x+1,y+2,i)
setPixel(x+2,y+2,i)
setPixel(x+3,y+2,i)
setPixel(x,y+3,i)
setPixel(x+1,y+3,i)
setPixel(x+2,y+3,i)
setPixel(x+3,y+3,i)
i=i+1
end
end
term.drawPixels(0,0,fb)
sleep(5)
term.setGraphicsMode(false)
File renamed without changes.
+16 -124
View File
@@ -6,7 +6,6 @@ syscall.open("/dev/tty/1","w") --stdout (Device 1)
syscall.open("/dev/null","w") --stderr (device 2) syscall.open("/dev/null","w") --stderr (device 2)
local fs = require("fs") local fs = require("fs")
local gfx = syscall.devctl(1,"gfx")
syscall.devctl(1,"clear") syscall.devctl(1,"clear")
syscall.devctl(1,"sfgc",0xFFFFFF) syscall.devctl(1,"sfgc",0xFFFFFF)
@@ -156,18 +155,17 @@ local function copyfile(src, dst)
return true return true
end end
local function rmtree(path, p) local function rmtree(path)
local t = syscall.type(path) local t = syscall.type(path)
if t == "directory" then if t == "directory" then
local ok, list = pcall(syscall.listdir, path) local ok, list = pcall(syscall.listdir, path)
if ok then if ok then
for _, e in ipairs(list) do for _, e in ipairs(list) do
rmtree(path:gsub("/$","").."/"..e, p) rmtree(path:gsub("/$","").."/"..e)
end end
end end
end end
if t then pcall(syscall.remove, path) end if t then pcall(syscall.remove, path) end
if p then print(path) end
end end
local function copytree(src, dst) local function copytree(src, dst)
@@ -244,7 +242,6 @@ builtinCmds.clear = function()
syscall.devctl(1,"clear") syscall.devctl(1,"clear")
syscall.devctl(1,"sfgc",0xFFFFFF) syscall.devctl(1,"sfgc",0xFFFFFF)
syscall.devctl(1,"spos",1,1) syscall.devctl(1,"spos",1,1)
if gfx then local w,h=gfx.size() gfx.box(0,0,w+5,h+5,0,true) end
end end
builtinCmds.whoami = function() builtinCmds.whoami = function()
@@ -335,7 +332,7 @@ builtinCmds.mkdir = function(...)
end end
builtinCmds.rm = function(...) builtinCmds.rm = function(...)
local opts, args = parseargs({...}, "rRfv") local opts, args = parseargs({...}, "rRf")
if #args == 0 then print("rm: missing operand"); return end if #args == 0 then print("rm: missing operand"); return end
local recursive = opts.r or opts.R local recursive = opts.r or opts.R
for _, a in ipairs(args) do for _, a in ipairs(args) do
@@ -345,11 +342,10 @@ builtinCmds.rm = function(...)
if not opts.f then print("rm: cannot remove '"..a.."': No such file or directory") end if not opts.f then print("rm: cannot remove '"..a.."': No such file or directory") end
elseif t == "directory" then elseif t == "directory" then
if not recursive then print("rm: cannot remove '"..a.."': Is a directory") if not recursive then print("rm: cannot remove '"..a.."': Is a directory")
else rmtree(path, opts.v) end else rmtree(path) end
else else
local ok, err = pcall(syscall.remove, path) local ok, err = pcall(syscall.remove, path)
if not ok then print("rm: cannot remove '"..a.."': "..tostring(err)) end if not ok then print("rm: cannot remove '"..a.."': "..tostring(err)) end
if opts.v then print("Removed: "..path) end
end end
end end
end end
@@ -824,11 +820,10 @@ builtinCmds.df = function(...)
end end
local function fmt(n) return opts.h and hfmt(n) or tostring(n) end local function fmt(n) return opts.h and hfmt(n) or tostring(n) end
print(string.format("%-20s %10s %10s %10s %6s %-s","Filesystem","Size","Used","Avail","Use%","Mounted on")) print(string.format("%-20s %10s %10s %10s %6s %-s","Filesystem","Size","Used","Avail","Use%","Mounted on"))
local fsinfo = syscall.fsinfo() local mounts = {{"$","/"}, {"devfs0000","/dev/"}, {"tmpfs0000","/tmp/"}}
for id, obj in pairs(fsinfo.disks) do for _, m in ipairs(mounts) do
local use = ((obj.size/obj.used)-1)*100 local id, mp = m[1], m[2]
local avail = obj.size-obj.used print(string.format("%-20s %10s %10s %10s %6s %-s", id, "?", "?", "?", "?%", mp))
print(string.format("%-20s %10s %10s %10s %6s %-s", id, tostring(obj.size), tostring(obj.used), avail, tostring(use).."%", fsinfo.mounts[id] or ""))
end end
end end
@@ -890,74 +885,6 @@ local function listCommands(prefix)
return results return results
end 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) local function commonPrefix(list)
if #list == 0 then return "" end if #list == 0 then return "" end
local pre = list[1] local pre = list[1]
@@ -1089,8 +1016,6 @@ local function getUserInput()
local cursorPos = 1 local cursorPos = 1
local history = 0 local history = 0
local dirty = true local dirty = true
local contentChanged = true
local ghostText = ""
local function getGhostSuffix() local function getGhostSuffix()
if #input == 0 then return "" end if #input == 0 then return "" end
@@ -1099,22 +1024,22 @@ local function getUserInput()
local candidates local candidates
if isFirst then if isFirst then
if partialDir then if partialDir then
local dir = partialDir:sub(1,1) == "/" and partialDir or (currentDir().."/"..partialDir) local dir = partialDir:sub(1,1) == "/" and partialDir or (syscall.getcwd().."/"..partialDir)
candidates = filterByPrefix(cachedDirList(dir), partialBase) candidates = listDir(dir, partialBase)
for i, c in ipairs(candidates) do candidates[i] = partialDir..c end for i, c in ipairs(candidates) do candidates[i] = partialDir..c end
else else
candidates = filterByPrefix(cachedCommandNames(), partialBase) candidates = listCommands(partialBase)
end end
else else
local dir, base local dir, base
if partialDir then if partialDir then
dir = partialDir:sub(1,1) == "/" and partialDir or (currentDir().."/"..partialDir) dir = partialDir:sub(1,1) == "/" and partialDir or (syscall.getcwd().."/"..partialDir)
base = partialBase base = partialBase
else else
dir = currentDir() dir = syscall.getcwd()
base = partialBase base = partialBase
end end
candidates = filterByPrefix(cachedDirList(dir), base) candidates = listDir(dir, base)
if partialDir then if partialDir then
for i, c in ipairs(candidates) do candidates[i] = partialDir..c end for i, c in ipairs(candidates) do candidates[i] = partialDir..c end
end end
@@ -1141,11 +1066,7 @@ local function getUserInput()
syscall.devctl(1,"sfgc",0xFFFFFF); syscall.devctl(1,"sbgc",0x000000) syscall.devctl(1,"sfgc",0xFFFFFF); syscall.devctl(1,"sbgc",0x000000)
local after = string.sub(input, cursorPos+1) local after = string.sub(input, cursorPos+1)
syscall.write(1, after) syscall.write(1, after)
if contentChanged then local ghost = getGhostSuffix()
ghostText = getGhostSuffix()
contentChanged = false
end
local ghost = ghostText
if #ghost > 0 then if #ghost > 0 then
syscall.devctl(1,"sfgc",0x6D00FF) syscall.devctl(1,"sfgc",0x6D00FF)
syscall.write(1, ghost) syscall.write(1, ghost)
@@ -1156,27 +1077,8 @@ local function getUserInput()
end end
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 while true do
local key = syscall.read(0) local key = syscall.read(0)
local beforeInput, beforeCursor = input, cursorPos
if key and key ~= "" then if key and key ~= "" then
if key=="" then if cursorPos>1 then cursorPos=cursorPos-1;dirty=true end 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 elseif key=="" then if cursorPos<=#input then cursorPos=cursorPos+1;dirty=true end
@@ -1205,7 +1107,6 @@ local function getUserInput()
local newInput, newCursor, needsRedraw = doTabComplete(input, cursorPos) local newInput, newCursor, needsRedraw = doTabComplete(input, cursorPos)
if needsRedraw then if needsRedraw then
input = newInput; cursorPos = newCursor input = newInput; cursorPos = newCursor
contentChanged = true
local px,py = syscall.devctl(1, "gpos") local px,py = syscall.devctl(1, "gpos")
if px > 1 then if px > 1 then
syscall.devctl(1,"spos",1,py) syscall.devctl(1,"spos",1,py)
@@ -1234,16 +1135,10 @@ local function getUserInput()
input=string.sub(input,1,cursorPos-1)..key..string.sub(input,cursorPos) input=string.sub(input,1,cursorPos-1)..key..string.sub(input,cursorPos)
cursorPos=cursorPos+1;dirty=true cursorPos=cursorPos+1;dirty=true
end end
else
sleep(0.02)
end end
if input ~= beforeInput or cursorPos ~= beforeCursor then contentChanged = true end
local curBlink = ((math.floor(syscall.getUptime()/500)%2)==0) local curBlink = ((math.floor(syscall.getUptime()/500)%2)==0)
if curBlink~=blinkState then blinkState=curBlink;dirty=true end if curBlink~=blinkState then blinkState=curBlink;dirty=true end
if dirty then if dirty then redraw();dirty=false end
if contentChanged then redraw() else redrawCursorOnly() end
dirty=false
end
end end
end end
@@ -1323,14 +1218,12 @@ local function runCommand(command)
while true do while true do
local exited, code = syscall.collect(proc) local exited, code = syscall.collect(proc)
if exited then if exited then
if gfx then gfx.setMode(false) end
if code then print("\nTask exited with code:\n"..tostring(code)) end if code then print("\nTask exited with code:\n"..tostring(code)) end
return return
end end
if terminate then if terminate then
local ok2 = syscall.kill(proc, true) local ok2 = syscall.kill(proc, true)
if ok2 then if ok2 then
if gfx then gfx.setMode(false) end
syscall.devctl(1,"sbgc",16); syscall.devctl(1,"sfgc",0xFF0000) syscall.devctl(1,"sbgc",16); syscall.devctl(1,"sfgc",0xFF0000)
print("\nProgram Terminated."); syscall.devctl(1,"sfgc",0xFFFFFF) print("\nProgram Terminated."); syscall.devctl(1,"sfgc",0xFFFFFF)
end end
@@ -1347,7 +1240,6 @@ while true do
table.insert(commandHistory, command) table.insert(commandHistory, command)
end end
runCommand(command) runCommand(command)
invalidateCaches()
end end
end end
File renamed without changes.
+1
View File
@@ -0,0 +1 @@
Hyperion os live installer
File renamed without changes.
-434
View File
@@ -1,434 +0,0 @@
--: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
@@ -1 +0,0 @@
rootkit
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more