116 Commits
Author SHA1 Message Date
Astronand 0a3803ba31 Merge pull request 'The 1.2.5 update' (#29) from 1.2-dev into main
Reviewed-on: #29
2026-11-04 14:22:51 -05:00
Astronand 56d8fb2016 bump version 2026-11-04 14:21:55 -05:00
Astronand ef4b856ee6 NC firmware update (thanks spsf). opencomputers now uses mutiple gpus to speed up rendering and now has net drivers. currently working on kernel memory protections to prevent malicious kernel drivers. spm does not work on opencomputers, this is a known issue i am working on fixing it :D sorry for the slow development. 2026-11-04 14:19:15 -05:00
Astronand 2ba903c385 Merge pull request 'made install packages and fixed spm del err' (#28) from 1.2-dev into main
Reviewed-on: #28
2026-10-06 14:23:49 -04:00
Astronand fbaafc7cff made install packages and fixed spm del err 2026-10-06 14:23:16 -04:00
Astronand 91ff59b60c Merge pull request 'init system changes' (#27) from 1.2-dev into main
Reviewed-on: #27
2026-10-06 10:06:08 -04:00
Astronand 8edf246e02 init system changes 2026-10-06 10:05:04 -04:00
Astronand 171927c4bb Merge pull request 'i forgot to build the pkgs' (#26) from 1.2-dev into main
Reviewed-on: #26
2026-10-04 20:00:20 -04:00
Astronand 6b4cc974b0 i forgot to build the pkgs 2026-10-04 20:00:09 -04:00
Astronand 8a861ca725 Merge pull request 'GFX update :D' (#25) from 1.2-dev into main
Reviewed-on: #25
2026-10-04 19:51:35 -04:00
Astronand c1b4ef2644 GFX update :D 2026-10-04 19:45:35 -04:00
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 05ca0f10a2 forgot var def 2026-08-25 21:16:48 -04:00
Astronand 125baaebf5 oc firmware 1.0 2026-08-25 21:16:16 -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 faf4f27987 update 2026-08-23 21:51:56 -04:00
Astronand d70328c224 updated kernel and working on oc tty impl 2026-08-23 21:51:19 -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 d4f74e950c testing update 2026-08-21 07:35:11 -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 3b86113425 UPDATE HYPERVISOR 2026-08-15 22:40:25 -04:00
Astronand bb28d24674 update hypervisor 2026-08-15 22:38:35 -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 4ed82a23a1 fix spm files 2026-08-14 21:12:49 -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 10aa0c62ff spm works maybe? 2026-08-14 20:44:11 -04:00
Astronand 56646625c0 update 2026-07-28 20:13:50 -04:00
Astronand 49c9e5e37c finished http implementation working on spm and liveboot env 2026-07-23 14:33:16 -04:00
Astronand f7b64c11b7 added seperate input and working on http / sockets 2026-05-27 17:01:26 -04:00
Astronand 59e09a5995 Update LICENSE 2026-03-26 10:34:00 -04:00
Astronand ab0a10105c formating better for spm packages 2026-03-26 08:12:37 -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 22b5021e9d fixed boot crash 2026-03-21 01:10:47 -04:00
Astronand 462c74686a fixed the installer 2026-03-21 01:04:27 -04:00
Astronand 0072547beb updated package list 2026-03-21 00:59:46 -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 7deefc83ca made newer installer that does not require tar stuff 2026-03-21 00:54:39 -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 df62414229 made system use full salt+pepper 2026-03-19 14:10:17 -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 055dd4e606 fixed again 2026-03-19 12:10:31 -04:00
Astronand 5755dd9cbe fixed 2026-03-19 11:32:48 -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 8e11faf9ec updated again 2026-03-19 11:23:24 -04:00
Astronand 0ea42f9454 Updated installer 2026-03-19 11:21:08 -04:00
Astronand d0f26a937f made installer 2026-03-19 11:16:05 -04:00
Astronand 9b338328f0 made unified colors and stuff 2026-03-19 08:33:47 -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 4f9eebade2 update tar 2026-03-12 20:54:27 -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
Astronand d08935b68a remove gotos 2026-03-12 19:31:37 -04:00
Astronand 45b46cf3c4 Merge pull request 'main' (#10) from main into 1.2-dev
Reviewed-on: #10
2026-03-12 19:27:44 -04:00
Astronand aeea68bc9b Update install/data/tarbad 2026-03-12 12:12:48 -04:00
Astronand f983b13d56 Update install/installcc.lua
make it use right stuff
2026-03-12 12:10:37 -04:00
Astronand 03c5b106c4 Update Src/Hyperion-kernel/boot/kernel.lua 2026-03-12 11:59:35 -04:00
Astronand 08323e00ff Update install/data/tarbad 2026-03-12 11:56:58 -04:00
Astronand 5e3cdbe40c Update install/installcc.lua 2026-03-12 11:51:55 -04:00
Astronand 8762b8f022 Merge pull request '1.2-dev' (#9) from 1.2-dev into main
Reviewed-on: #9
2026-03-11 10:37:44 -04:00
Astronand 677b2cccec user login fixed 2026-03-11 10:37:13 -04:00
Astronand a5e8624368 forgot to edit login 2026-03-11 08:54:47 -04:00
Astronand bbda3b3937 fixed elevate VULN 2026-03-11 08:52:41 -04:00
Astronand 585d39bec2 Merge pull request '1.2-dev' (#8) from 1.2-dev into main
Reviewed-on: #8
2026-03-11 08:23:21 -04:00
Astronand b08b14763a i am a we bit stupid (fixed cct bug) 2026-03-11 08:22:53 -04:00
Astronand de6696003b fix capitaization part 2 2026-03-11 07:26:38 -04:00
Astronand 9220281365 fix capitalization part 1 2026-03-11 07:25:52 -04:00
Astronand 813ddabd9d fixed disk detection i think 2026-03-10 21:13:52 -04:00
Astronand 5177639d71 Merge pull request 'update build.tar' (#7) from 1.2-dev into main
Reviewed-on: #7
i was dumb
2026-03-10 20:05:26 -04:00
Astronand 528b4f31bd update build.tar 2026-03-10 20:04:53 -04:00
Astronand 60162c7c57 Merge pull request '1.2.4' (#6) from 1.2-dev into main
Reviewed-on: #6
2026-03-10 20:02:20 -04:00
Astronand 18f5c454bb fixed bug where cct drivers are inaccessable 2026-03-10 20:00:21 -04:00
Astronand 849ecb7dd6 made procfs self 2026-03-10 19:41:54 -04:00
Astronand e41bd6bee7 Merge pull request '1.2-dev merge' (#5) from 1.2-dev into main
Reviewed-on: #5
2026-03-10 12:27:08 -04:00
Astronand 359198c1ea Merge branch '1.2-dev' of https://git.astronand.dev/Hyperion/HyperionOS into 1.2-dev 2026-03-10 10:57:27 -04:00
Astronand beebf01223 remove tar during install 2026-03-10 10:57:10 -04:00
Astronand 2d4ea1bbf4 Update README.md 2026-03-10 10:39:01 -04:00
Astronand ea3a7e99a7 Update install/installcc.lua 2026-03-10 10:34:36 -04:00
Astronand be0fe5dc5a install works (i think) 2026-03-10 10:32:32 -04:00
Astronand 12669d9f82 adde /proc fs and working on install 2026-03-10 09:17:21 -04:00
Astronand f12159bfb9 fixed build script 2026-03-09 11:31:31 -04:00
Astronand 1590e1f3f7 more reorganizeing and $PKGCONFIG.ini files added B to ls -lh for "Bytes" 2026-03-09 11:28:09 -04:00
Astronand a69f945b91 did some reorganizing 2026-03-06 09:57:45 -05:00
Astronand 7da67899db finished hyperion manifest :D 2026-03-05 10:36:43 -05:00
Astronand 62e032e4c5 made sysinit in /usr/lib/sysinit and sped up micro added kernel.firstBoot in kernel table 2026-03-05 09:53:30 -05:00
Astronand 6fefa2d9ff cp should not copy perms 2026-03-03 12:25:25 -05:00
Astronand bb354cc706 mv syscallautofill 2026-03-03 11:45:05 -05:00
Astronand fabc061731 made lua not clear screen 2026-03-03 10:06:04 -05:00
Astronand 82c3e2b346 fix ll 2026-03-03 08:57:45 -05:00
Astronand e2e1d5b8a5 making descriptions for syscalls 2026-03-03 08:52:55 -05:00
Astronand 9342b9b2b3 Merge branch '1.2-dev' of https://git.astronand.dev/Hyperion/HyperionOS into 1.2-dev 2026-03-03 08:02:09 -05:00
Astronand 9a7db6c243 syscalls now autocomplete is vsc 2026-03-03 08:02:05 -05:00
Astronand c7545e6947 Update build.py 2026-03-03 07:31:59 -05:00
Astronand b7f52dd17b working on syscall manifest and fixed anther exploit 2026-03-02 22:25:37 -05:00
Astronand eb5bed0f09 fixed asyncsyscall5 2026-03-02 21:58:51 -05:00
Astronand 1827a463eb added ll for ghxx 2026-03-02 21:56:05 -05:00
Astronand b532a63fc6 fixed stupid dumbass mistake i made me dumb 2026-03-02 21:32:56 -05:00
Astronand 4e5a4172bf hopfully fixed it omfg 2026-03-02 21:29:46 -05:00
Astronand 31ce894fda fixed build script 2026-03-02 21:26:50 -05:00
Astronand 16c900de84 fixed ls links, modules writeable 2026-03-02 21:23:35 -05:00
Astronand 413afd96de Merge branch '1.2-dev' of https://git.astronand.dev/Hyperion/HyperionOS into 1.2-dev 2026-03-02 07:27:46 -05:00
Astronand a0a0ac69d4 remove old shell files 2026-03-02 07:27:45 -05:00
spsf 17453983ad Path traversal fixes, 26_tty removal, ctrl+key fixes 2026-03-01 00:21:02 -06:00
Astronand a6550aa069 fixed minify header and build script 2026-02-25 11:41:41 -05:00
Astronand 02e7b3897c fixed tty naming 2026-02-25 09:03:32 -05:00
Astronand 34b89a8e34 fixed build script 2026-02-25 08:04:53 -05:00
Astronand 0eabfebd0f fixed new ghxx exploit 2026-02-25 08:01:28 -05:00
Astronand 5b2e5eac65 added more libs and fixed build script 2026-02-24 17:54:09 -05:00
spsf 415064480a Patch the AsyncSyscall v4 exploit from working 2026-02-24 02:00:37 -06:00
spsf f00453f703 Merge pull request '1.2-dev merge' (#5) from 1.2-dev into main
Reviewed-on: #5
2026-02-24 02:12:36 -05:00
spsf ab1e847d1c Fix exploit with trailing whitespace 2026-02-24 00:48:20 -06:00
spsf 62a03bfe6b Potential windows case insensitive filesystem issue fix 2026-02-24 00:34:59 -06:00
spsf e77a8b3636 AsyncSyscall3 exploit fix 2026-02-24 00:01:39 -06:00
spsf 6bb7f03a3e file permissions fixes 2026-02-23 23:50:37 -06:00
spsf 8798a2f4fe 2 potential vulnerability fixes 2026-02-23 23:26:21 -06:00
361 changed files with 21458 additions and 4680 deletions

No files matched your search

+6 -1
View File
@@ -5,6 +5,11 @@
"syscall", "syscall",
"printf", "printf",
"printInline", "printInline",
"toHex" "toHex",
"userinput"
],
"Lua.diagnostics.disable": [
"need-check-nil",
"param-type-mismatch"
] ]
} }
+198 -14
View File
@@ -1,18 +1,202 @@
MIT License
Copyright (c) 2025 Astronand Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial 1. Definitions.
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT "License" shall mean the terms and conditions for use, reproduction,
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO and distribution as defined by Sections 1 through 9 of this document.
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE "Licensor" shall mean the copyright owner or entity authorized by
USE OR OTHER DEALINGS IN THE SOFTWARE. the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+10 -1
View File
@@ -1,3 +1,4 @@
[![Download on PineStore](https://raster.shields.io/badge/dynamic/json?url=https%3A%2F%2Fpinestore.cc%2Fapi%2Fproject%2F225&query=%24.project.downloads&suffix=%20downloads&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iNzYuOTA0IiBoZWlnaHQ9Ijg5LjI5NSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ieE1pZFlNaWQiIHZlcnNpb249IjEuMSIgdmlld0JveD0iMCAwIDc2OS4wNCA4OTIuOTUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI%2BCiA8ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTQuNzQgLTQuNjgyNikiIGZpbGw9IiM5YWIyZjIiPgogIDxwYXRoIGQ9Im00MTAgODUxYzAtMTIgMjYtMjEgNTgtMjEgMTUgMCAyMiA0IDE3IDktMTQgMTItNzUgMjItNzUgMTJ6Ii8%2BCiAgPHBhdGggZD0ibTU4NSA3NDJjLTEtNDkgNC03MiAxNi04NSAyMi0yNCAzMC02OCAxNi04Ni0xMi0xNC0yNy0zOS00OC03OC0xMC0xOS05LTI2IDQtNDEgMjItMjQgMjEtNjctMi0xNDQtMjEtNjktMzktMTQ0LTQ4LTE5NS00LTI2LTItMzMgMTEtMzMgMzEgMCAxMTIgMzMgMTQxIDU4IDI4IDIzIDgxIDkyIDcxIDkyLTIgMCA1IDI2IDE2IDU3IDI4IDc5IDI5IDIyNCAzIDMwOC0xMCAzMy0xOSA2Mi0xOSA2NS00IDI2LTEzMiAxNTAtMTU1IDE1MC0zIDAtNi0zMC02LTY4eiIvPgogIDxwYXRoIGQ9Im02OCA2NzNjLTcyLTEwOS03MS0yNzggMy00MjMgMzYtNzEgNjItMTAwIDEyOC0xNDAgNDMtMjcgNjUtMzQgMTE4LTM2IDEwMC00IDk4IDExLTE5IDEzNi0zNCAzNy03OCA4OC05NiAxMTMtMjggMzktMzEgNDgtMjEgNjUgMTEgMTcgNiAyNy0zMyA3OS00MCA1My00NCA2Mi0zMiA3OCAxNyAyMyAxOCA1NyAyIDczLTYgNi0xNCAzMS0xNyA1NC02IDQyLTYgNDItMzMgMXoiLz4KIDwvZz4KIDxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0xNC43NCAtNC42ODI2KSIgZmlsbD0iIzU5YTY0ZiI%2BCiAgPHBhdGggZD0ibTM2NSA4MTNjLTUzLTYtMTM5LTMzLTE5Mi02MS02OC0zNS04My02Ny01OC0xMjIgMjYtNTkgNDAtNjcgNzgtNDkgNjggMzMgMTY3IDU4IDI2NiA2OSA1OCA1IDEwNiAxMiAxMDkgMTQgMiAzIDYgMzIgOSA2NSA4IDg1IDAgOTEtMTAxIDkwLTQ0LTEtOTQtNC0xMTEtNnoiLz4KICA8cGF0aCBkPSJtNDEwIDQ1OWMtNjctNy0xNjAtMjktMTk5LTQ4LTI3LTE0LTM0LTM2LTIwLTYzIDIxLTM4IDk3LTEzNiAxNTAtMTkzIDI1LTI3IDU4LTcxIDczLTk3IDI1LTQzIDMxLTQ3IDU0LTQyIDQwIDEwIDQyIDEyIDQyIDUyIDAgMjAgNiA1NyAxNCA4MiAyNCA3MyA1NCAxOTIgNjIgMjM2IDUgMzUgMyA0NS0xNSA2My0yMyAyMy0zNiAyNC0xNjEgMTB6Ii8%2BCiA8L2c%2BCiA8ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTQuNzQgLTQuNjgyNikiIGZpbGw9IiM3ZWNiMjUiPgogIDxwYXRoIGQ9Im01NTggNjc0Yy0yLTItNTEtOS0xMDktMTQtMTAyLTExLTIwNC0zNy0yNjQtNjktMTYtOC0zMi0xNC0zNC0xMi00IDMtMzEtNDgtMzEtNjEgMC01IDIxLTMxIDQ2LTU4IDUxLTU0IDcxLTYwIDEzMC0zNSAxOSA4IDgzIDE5IDE0MiAyNSA1OCA2IDEwNyAxMiAxMDcgMTNzMTUgMjYgMzMgNTZjMjcgNDMgMzIgNjMgMzAgOTktMiAzNS04IDQ3LTI1IDUzLTExIDQtMjMgNi0yNSAzeiIvPgogPC9nPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTE0Ljc0IC00LjY4MjYpIiBmaWxsPSIjZWNlZGVmIj4KICA8cGF0aCBkPSJtMjYwIDg5MGMtMzQtOC03MC00MS03MC02NSAwLTYtOS0yMC0yMC0zMHMtMjAtMjItMjAtMjctMTMtMjEtMzAtMzVjLTM1LTI5LTQxLTgzLTEzLTEyMiAxNS0yMiAxNS0yNi0xLTU2LTE4LTMzLTE4LTMzIDI3LTkxIDI4LTM2IDQyLTYzIDM2LTY4LTIzLTI1IDktNzggMTIwLTE5NyAzNi0zOCA3Mi04MSA4Mi05NiAxMC0xNCAyNS0zMCAzMy0zNSAzNi0yMCA3IDMyLTUzIDk3LTQ4IDUxLTEyNiAxNTAtMTQ5IDE4OS0xMCAxOC05IDI0IDEwIDQwIDIzIDE5IDIzIDE5LTI5IDcxLTUzIDUyLTUzIDUyLTM4IDgyIDE0IDI4IDE0IDMzLTEwIDc2LTMyIDU3LTIzIDgxIDQ2IDEyMCAzNCAxOSA0OSAzMyA0NSA0Mi0xNCAzNyAzNiA3NSA5OCA3NSAyNSAwIDQwLTcgNTQtMjUgMTgtMjMgMjctMjUgOTUtMjUgOTQgMCAxMDItOCA5My04OS02LTUzLTUtNTkgMTQtNjQgMzItOCAyNi02NC0xNS0xMzItMzUtNTgtMzUtNTgtOS04MiAyMS0xOSAyNC0yOSAxOS01Ni0xMC00Ny00NC0xNzUtNjEtMjI3LTgtMjUtMTQtNjItMTQtODMgMC0yNy01LTM5LTE3LTQzLTEwLTMtMjUtOC0zMy0xMC0xMi00LTEyLTYtMS0xNCAyNy0xNiA1NiA1IDY5IDUxIDM1IDExNyA0MyAxNDggNDYgMTcwIDIgMTMgMTEgNTEgMjEgODQgMjEgNzEgMjEgMTIxIDAgMTQ1LTE0IDE1LTEzIDE5IDUgNDMgMTEgMTQgMjAgMzAgMjAgMzVzNyAxNSAxNSAyMmMyMSAxNyAxNiA3NS0xMCAxMDItMTggMTktMjAgMzItMTcgNzkgNCA1MCAyIDU4LTE5IDcyLTEyIDktNTAgMTktODMgMjMtNDUgNS02NSAxMy04MyAzMi0yNiAyOC05MiAzOC0xNTMgMjJ6Ii8%2BCiA8L2c%2BCiA8ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTQuNzQgLTQuNjgyNikiIGZpbGw9IiM3ZTY3NGQiPgogIDxwYXRoIGQ9Im0yNDggODU0Yy0zMC0xNi00Ny01OS0zMC03NiA4LTggMjMtNyA1NCAyIDI0IDcgNjEgMTQgODMgMTcgNTQgNyA1OSAxNSAzNSA0Ni0xOCAyMy0yOSAyNy02OCAyNy0yNi0xLTU5LTctNzQtMTZ6Ii8%2BCiA8L2c%2BCjwvc3ZnPgo%3D&label=PineStore)](https://pinestore.cc/projects/225/hyperionos)
# HyperionOS # HyperionOS
HyperionOS is a modular, hybrid kernel operating system written entirely in Lua. It features a custom task scheduler, virtual filesystem, syscall interface, and separates core functionality from user-space services. HyperionOS is a modular, hybrid kernel operating system written entirely in Lua. It features a custom task scheduler, virtual filesystem, syscall interface, and separates core functionality from user-space services.
@@ -14,8 +15,10 @@ See `building.md`.
- Functionality is split into kernel modules (`.kmod`) - Functionality is split into kernel modules (`.kmod`)
- Task-based lightweight thread/task preemptive scheduler with process isolation and IPC support - Task-based lightweight thread/task preemptive scheduler with process isolation and IPC support
- Virtual filesystem unified interface for disk, RAM, and virtual filesystems - Virtual filesystem
- TTY & Shell - TTY & Shell
- Sockets
-
--- ---
@@ -47,6 +50,12 @@ Add your name to `contributors.md` when your PR is merged.
--- ---
## Information
Trello: https://trello.com/b/8dryrlMi
---
## License ## License
This project is licensed under the MIT License. See the LICENSE file for details. This project is licensed under the MIT License. See the LICENSE file for details.
+2
View File
@@ -0,0 +1,2 @@
Hyperion
Astronand
@@ -0,0 +1,318 @@
--: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
@@ -0,0 +1 @@
Hyperion-firmware-cct
@@ -0,0 +1 @@
firmware for CraftOS PC
+1
View File
@@ -0,0 +1 @@
1.0.0
-33
View File
@@ -1,33 +0,0 @@
local args = {...}
local name = syscall.getTask(syscall.getpid()).name
local fs = require("sys.fs")
if not args[1] then
while true do
local content = syscall.read(0, 1024)
if not content or content == "" then break end
printInline(content)
end
print("")
return
end
for _, arg in ipairs(args) do
local filePath = arg
if filePath:sub(1,1) ~= "/" then
filePath = syscall.getcwd().."/"..filePath
end
if not fs.exists(filePath) then
print(name..": Cannot access '"..arg.."': No such file.")
else
local fd = syscall.open(filePath, "r")
while true do
local content = syscall.read(fd, 1024)
if not content or content == "" then break end
printInline(content)
end
syscall.close(fd)
end
end
print("")
-1
View File
@@ -1 +0,0 @@
syscall.devctl(1,"clear")
-2
View File
@@ -1,2 +0,0 @@
local args = {...}
print(table.concat(args, " "))
-94
View File
@@ -1,94 +0,0 @@
--:Minify:--
syscall.open("/dev/tty/TTY1","r")
syscall.open("/dev/tty/TTY1","w")
syscall.open("/dev/null","r")
syscall.devctl(1,"clear")
syscall.devctl(1,"sfgc",1)
syscall.devctl(1,"spos",1,1)
print("HyperionOS hysh Shell")
local str=""
local stopInput=false
local proc=0
local fs=require("sys.fs")
local timeout=false
syscall.setEnviron("SHELL","simpleshell")
printInline("> ")
syscall.sigcatch(function(sig)
if sig==1 then
syscall.kill(proc)
print("Terminated")
printInline("> ")
stopInput=false
end
end)
while true do
if not stopInput then
local input=syscall.read(0)
if input then
if input=="\b" then
if #str>0 then
str=str:sub(1,#str-1)
printInline("\b")
end
elseif input=="\n" then
print("")
stopInput=true
if str == "" then
printInline("> ")
stopInput=false
else
local path=nil
local split=string.split(str, " ")
if fs.exists("/bin/"..split[1]) then
path="/bin/"..split[1]
elseif fs.exists("/bin/"..split[1]..".lua") then
path="/bin/"..split[1]..".lua"
end
if not path then
print("Program not found")
printInline("> ")
stopInput=false
else
local text = fs.readAllText(path)
local program, err = load(text, path)
if not program then
print(err)
printInline("> ")
end
proc = syscall.spawn(function(...)
syscall.open("/dev/tty/TTY1","r")
syscall.open("/dev/tty/TTY1","w")
syscall.open("/dev/null","w")
program(...)
end, path, nil, {table.unpack(split, 2)})
end
str=""
end
else
str=str..input
printInline(input)
end
timeout=false
else
timeout=true
end
else
local exited, code = syscall.collect(proc)
if exited then
if code then
print("\nTask exited with code:\n"..tostring(code))
end
printInline("> ")
stopInput=false
end
timeout=true
end
if timeout then
if stopInput then
sleep(.5)
else
sleep(.05)
end
end
end
-427
View File
@@ -1,427 +0,0 @@
--:Minify:--
local passed, failed = 0, 0
local function pass(msg) syscall.devctl(1,"sfgc",10); print(" PASS "..msg); syscall.devctl(1,"sfgc",1) end
local function fail(msg) syscall.devctl(1,"sfgc",2); print(" FAIL "..msg); syscall.devctl(1,"sfgc",1) end
local function info(msg) syscall.devctl(1,"sfgc",14); print(" .... "..msg); syscall.devctl(1,"sfgc",1) end
local function head(msg) syscall.devctl(1,"sfgc",4); print("\n"..msg); syscall.devctl(1,"sfgc",1) end
local function check(label, ok, err)
if ok then passed = passed + 1; pass(label)
else failed = failed + 1; fail(label.." - "..tostring(err)) end
end
local function writeFile(path, data)
local ok, fd = pcall(syscall.open, path, "w")
if not ok then return false, fd end
local ok2, err = pcall(syscall.write, fd, data)
pcall(syscall.close, fd)
return ok2, err
end
local function readFile(path)
local ok, fd = pcall(syscall.open, path, "r")
if not ok then return false, fd end
local ok2, data = pcall(syscall.read, fd, 65536)
pcall(syscall.close, fd)
return ok2, data
end
local function rmrf(path)
local t = syscall.type(path)
if t == "directory" then
local ok, entries = pcall(syscall.listdir, path)
if ok then
for _, name in ipairs(entries) do
rmrf(path:gsub("/$","").."/"..name)
end
end
pcall(syscall.remove, path)
elseif t == "file" then
pcall(syscall.remove, path)
end
end
local SCRATCH = "/tmp/looptest_scratch"
local SRC_DIR = SCRATCH.."/src"
local BIND_MNT = SCRATCH.."/bind_mnt"
local IMG_PATH = SCRATCH.."/test.hfs"
local IMG_MNT = SCRATCH.."/img_mnt"
local BIND_LOOP = nil
local IMG_LOOP = nil
rmrf(SCRATCH)
pcall(syscall.mkdir, SCRATCH)
pcall(syscall.mkdir, SRC_DIR)
pcall(syscall.mkdir, BIND_MNT)
pcall(syscall.mkdir, IMG_MNT)
pcall(syscall.mkdir, SRC_DIR.."/subdir")
writeFile(SRC_DIR.."/hello.txt", "hello from hyperion\n")
writeFile(SRC_DIR.."/data.txt", "line1\nline2\nline3\n")
writeFile(SRC_DIR.."/subdir/deep.txt", "deep file\n")
head("[ 1 ] bind mode - losetup on a directory")
do
local ok, id = pcall(syscall.losetup, SRC_DIR)
check("losetup(dir) returns a loop id", ok and type(id) == "string" and id:sub(1,4) == "loop", id)
if ok then
BIND_LOOP = id
info("attached as "..id)
end
end
head("[ 2 ] bind mode - mount and read files")
do
if BIND_LOOP then
local mok = pcall(syscall.mount, BIND_MNT, BIND_LOOP)
check("mount(bind_mnt, "..BIND_LOOP..")", mok, "mount failed")
if mok then
local lok, entries = pcall(syscall.listdir, BIND_MNT)
check("listdir through bind mount", lok and type(entries) == "table", entries)
local rok, data = readFile(BIND_MNT.."/hello.txt")
check("read hello.txt through bind", rok and data == "hello from hyperion\n",
rok and ("got: "..tostring(data):sub(1,40)) or tostring(data))
local rok2, data2 = readFile(BIND_MNT.."/subdir/deep.txt")
check("read subdir/deep.txt through bind", rok2 and data2 == "deep file\n",
rok2 and ("got: "..tostring(data2)) or tostring(data2))
end
else
check("mount (skipped - no loop id)", false, "losetup failed in [1]")
end
end
head("[ 3 ] bind mode - write through loop mount, verify on host")
do
if BIND_LOOP then
local wok, werr = writeFile(BIND_MNT.."/written.txt", "written via loop\n")
check("write new file through bind mount", wok, werr)
local rok, data = readFile(BIND_MNT.."/written.txt")
check("read back through bind mount", rok and data == "written via loop\n",
rok and ("got: "..tostring(data)) or tostring(data))
local rok2, data2 = readFile(SRC_DIR.."/written.txt")
check("file visible on host path (bind is transparent)", rok2 and data2 == "written via loop\n",
rok2 and ("got: "..tostring(data2)) or tostring(data2))
else
check("write (skipped)", false, "bind mount not set up")
end
end
head("[ 4 ] bind mode - lodetach while mounted returns EBUSY")
do
if BIND_LOOP then
local ok = pcall(syscall.lodetach, BIND_LOOP)
check("lodetach while mounted is refused (EBUSY)", not ok, "should have errored")
else
check("lodetach busy check (skipped)", false, "no bind loop")
end
end
head("[ 5 ] bind mode - umount then lodetach")
do
if BIND_LOOP then
local uok = pcall(syscall.umount, BIND_MNT)
check("umount(bind_mnt)", uok, "umount failed")
local dok = pcall(syscall.lodetach, BIND_LOOP)
check("lodetach after umount", dok, "lodetach failed")
if dok then BIND_LOOP = nil end
else
check("umount+lodetach (skipped)", false, "no bind loop")
end
end
head("[ 6 ] loimgcreate - serialise directory to HFS image")
do
local ok, imgStr = pcall(syscall.loimgcreate, SRC_DIR)
check("loimgcreate(srcdir) returns a string", ok and type(imgStr) == "string" and #imgStr > 0, imgStr)
if ok then
info("image size: "..#imgStr.." bytes")
local isBHFS = imgStr:sub(1, 4) == "BHFS"
check("image has BHFS magic header", isBHFS,
"got: "..imgStr:sub(1,4):gsub(".", function(c) return string.format("%02X ", c:byte()) end))
check("image has correct version byte (0x01)", imgStr:byte(5) == 1,
"version byte: "..tostring(imgStr:byte(5)))
check("image contains FILE record (type=0x01)", imgStr:find("\001", 9, true) ~= nil, "no FILE type byte found")
check("image contains DIR record (type=0x02)", imgStr:find("\002", 9, true) ~= nil, "no DIR type byte found")
check("image ends with END record (type=0xFF)", imgStr:byte(#imgStr) == 0xFF,
"last byte: 0x"..string.format("%02X", imgStr:byte(#imgStr)))
local wok, werr = pcall(syscall.loimgwrite, imgStr, IMG_PATH)
check("loimgwrite writes image file", wok, werr)
check("image file exists on disk", syscall.type(IMG_PATH) == "file", "file not found")
end
end
head("[ 7 ] HFS image - losetup attaches image file")
do
if syscall.type(IMG_PATH) == "file" then
local ok, id = pcall(syscall.losetup, IMG_PATH)
check("losetup(image.hfs) returns loop id", ok and type(id) == "string", id)
if ok then
IMG_LOOP = id
info("image attached as "..id)
local lok, devs = pcall(syscall.lolist)
local found = false
if lok then
for lid, info_entry in pairs(devs) do
if lid == id then found = true end
end
end
check("lolist() contains new image device", found, "not found in lolist")
end
else
check("losetup image (skipped - no image file)", false, "image not created in [6]")
end
end
head("[ 8 ] HFS image - mount and read files")
do
if IMG_LOOP then
local mok = pcall(syscall.mount, IMG_MNT, IMG_LOOP)
check("mount(img_mnt, "..IMG_LOOP..")", mok, "mount failed")
if mok then
local lok, entries = pcall(syscall.listdir, IMG_MNT)
check("listdir through image mount returns table", lok and type(entries) == "table", entries)
if lok then
local hasHello = false
local hasSubdir = false
for _, e in ipairs(entries) do
if e == "hello.txt" then hasHello = true end
if e == "subdir" then hasSubdir = true end
end
check("hello.txt visible in image root", hasHello, "not listed")
check("subdir/ visible in image root", hasSubdir, "not listed")
end
local rok, data = readFile(IMG_MNT.."/hello.txt")
check("read hello.txt from image", rok and data == "hello from hyperion\n",
rok and ("got: "..tostring(data):sub(1,40)) or tostring(data))
local rok2, data2 = readFile(IMG_MNT.."/data.txt")
check("read data.txt from image", rok2 and data2 == "line1\nline2\nline3\n",
rok2 and ("got: "..tostring(data2)) or tostring(data2))
end
else
check("image mount read (skipped)", false, "no image loop")
end
end
head("[ 9 ] HFS image - write new files into image mount")
do
if IMG_LOOP then
local wok, werr = writeFile(IMG_MNT.."/newfile.txt", "created inside image\n")
check("write new file into image mount", wok, werr)
local rok, data = readFile(IMG_MNT.."/newfile.txt")
check("read back newly written file", rok and data == "created inside image\n",
rok and ("got: "..tostring(data)) or tostring(data))
local wok2, werr2 = writeFile(IMG_MNT.."/hello.txt", "overwritten\n")
check("overwrite existing file in image", wok2, werr2)
local rok2, data2 = readFile(IMG_MNT.."/hello.txt")
check("overwritten content reads back correctly", rok2 and data2 == "overwritten\n",
rok2 and ("got: "..tostring(data2)) or tostring(data2))
local rok3, orig = readFile(IMG_PATH)
check("disk image file is unchanged after in-memory write",
rok3 and orig and orig:find("/hello%.txt") ~= nil,
rok3 and "filename record missing from image" or tostring(orig))
else
check("image write test (skipped)", false, "image not mounted")
end
end
head("[ 10 ] HFS image - sub-directory traversal")
do
if IMG_LOOP then
local t = syscall.type(IMG_MNT.."/subdir")
check("type(subdir) == 'directory'", t == "directory", "got: "..tostring(t))
local lok, entries = pcall(syscall.listdir, IMG_MNT.."/subdir")
check("listdir(subdir) works", lok and type(entries) == "table", entries)
local rok, data = readFile(IMG_MNT.."/subdir/deep.txt")
check("read subdir/deep.txt from image", rok and data == "deep file\n",
rok and ("got: "..tostring(data)) or tostring(data))
local mok = pcall(syscall.mkdir, IMG_MNT.."/subdir/newdir")
check("mkdir inside image mount", mok, "mkdir failed")
check("new dir has type 'directory'",
syscall.type(IMG_MNT.."/subdir/newdir") == "directory",
"wrong type")
local wok, werr = writeFile(IMG_MNT.."/subdir/newdir/x.txt", "x\n")
check("write file in newly created subdir", wok, werr)
else
check("subdir traversal (skipped)", false, "image not mounted")
end
end
head("[ 11 ] HFS image - lodetach while mounted returns EBUSY")
do
if IMG_LOOP then
local ok = pcall(syscall.lodetach, IMG_LOOP)
check("lodetach image while mounted is refused", not ok, "should have errored EBUSY")
else
check("lodetach busy (skipped)", false, "no image loop")
end
end
head("[ 12 ] HFS image - umount then lodetach")
do
if IMG_LOOP then
local uok = pcall(syscall.umount, IMG_MNT)
check("umount(img_mnt)", uok, "umount failed")
local dok = pcall(syscall.lodetach, IMG_LOOP)
check("lodetach after umount", dok, "lodetach failed")
if dok then
local lok, devs = pcall(syscall.lolist)
local found = false
if lok then
for lid in pairs(devs) do
if lid == IMG_LOOP then found = true end
end
end
check("lolist no longer shows detached device", not found, "still present in lolist")
IMG_LOOP = nil
end
else
check("image umount+lodetach (skipped)", false, "no image loop")
end
end
head("[ 13 ] lolist - reflects attached device count")
do
local ok1, id1 = pcall(syscall.losetup, SRC_DIR)
local ok2, id2 = pcall(syscall.losetup, SRC_DIR)
check("attach first device for lolist test", ok1, id1)
check("attach second device for lolist test", ok2, id2)
if ok1 and ok2 then
local lok, devs = pcall(syscall.lolist)
check("lolist() succeeds", lok, devs)
if lok then
local found1, found2 = false, false
for lid in pairs(devs) do
if lid == id1 then found1 = true end
if lid == id2 then found2 = true end
end
check("lolist contains first device", found1, "missing "..id1)
check("lolist contains second device", found2, "missing "..id2)
local count = 0
for _ in pairs(devs) do count = count + 1 end
info("lolist shows "..count.." device(s)")
end
end
if ok1 then pcall(syscall.lodetach, id1) end
if ok2 then pcall(syscall.lodetach, id2) end
end
head("[ 14 ] losetup - non-existent path returns error")
do
local ok = pcall(syscall.losetup, "/tmp/does_not_exist_xyz_looptest")
check("losetup on missing path errors", not ok, "should have errored")
end
head("[ 15 ] mount - same loop device cannot be mounted twice")
do
local ok, id = pcall(syscall.losetup, SRC_DIR)
check("losetup for double-mount test", ok, id)
if ok then
local m1ok = pcall(syscall.mount, BIND_MNT, id)
check("first mount succeeds", m1ok, "mount failed")
if m1ok then
local m2ok = pcall(syscall.mount, IMG_MNT, id)
check("second mount of same device is refused", not m2ok, "should have errored EBUSY")
pcall(syscall.umount, BIND_MNT)
end
pcall(syscall.lodetach, id)
end
end
head("[ 16 ] loimgcreate - on a regular file returns ENOTDIR")
do
local ok = pcall(syscall.loimgcreate, IMG_PATH)
check("loimgcreate on a file errors (ENOTDIR)", not ok, "should have errored")
end
head("[ 17 ] HFS image - binary round-trip (all byte values)")
do
local bytes = {}
for i = 0, 255 do bytes[i+1] = string.char(i) end
local binData = table.concat(bytes)
local binSrc = SCRATCH.."/binsrc"
pcall(syscall.mkdir, binSrc)
writeFile(binSrc.."/binary.bin", binData)
local ok1, imgStr = pcall(syscall.loimgcreate, binSrc)
check("loimgcreate handles binary content", ok1, imgStr)
if ok1 then
local binImg = SCRATCH.."/binary.hfs"
pcall(syscall.loimgwrite, imgStr, binImg)
local ok2, lid = pcall(syscall.losetup, binImg)
check("losetup on binary image", ok2, lid)
if ok2 then
local mnt = SCRATCH.."/binmnt"
pcall(syscall.mkdir, mnt)
local mok = pcall(syscall.mount, mnt, lid)
check("mount binary image", mok, "mount failed")
if mok then
local rok, readBack = readFile(mnt.."/binary.bin")
check("binary file readable from image", rok, readBack)
check("binary data round-trips without corruption",
rok and readBack == binData,
rok and string.format("length in=%d out=%d", #binData, #(readBack or "")) or tostring(readBack))
pcall(syscall.umount, mnt)
end
pcall(syscall.lodetach, lid)
end
end
end
head("[ 18 ] second-run safety - lolist is empty after full cleanup")
do
local lok, devs = pcall(syscall.lolist)
check("lolist() call succeeds", lok, devs)
if lok then
local count = 0
for _ in pairs(devs) do count = count + 1 end
check("no leftover loop devices after all tests", count == 0,
count.." device(s) still attached: "..
(function()
local ids = {}
for id in pairs(devs) do ids[#ids+1] = id end
return table.concat(ids, ", ")
end)())
end
end
rmrf(SCRATCH)
print("")
syscall.devctl(1, "sfgc", failed == 0 and 10 or 2)
print(string.format("Results: %d passed, %d failed", passed, failed))
syscall.devctl(1, "sfgc", 1)
if failed > 0 then syscall.exit(1) end
-50
View File
@@ -1,50 +0,0 @@
--:Minify:--
print("HyperionOS lua")
local str=""
local stopInput=false
local timeout=false
local luaEnv=setmetatable({},{__index=_ENV})
printInline("> ")
while true do
local input=syscall.read(0)
if input then
if input=="\b" then
if #str>0 then
str=str:sub(1,#str-1)
printInline("\b")
end
elseif input=="\n" then
print("")
stopInput=true
if str == "" then
printInline("> ")
stopInput=false
elseif str == "exit()" then
break
else
local func=load(str,"@Lua","t",luaEnv)
local ok,err = xpcall(func, debug.traceback)
if not ok then
print(err)
end
printInline("\n> ")
str=""
end
str=""
else
str=str..input
printInline(input)
end
timeout=false
else
timeout=true
end
if timeout then
if stopInput then
sleep(.5)
else
sleep(.05)
end
end
end
-23
View File
@@ -1,23 +0,0 @@
local args = {...}
local name = syscall.getTask(syscall.getpid()).name
if #args == 0 then
print(name..": Missing operand.")
return
end
local fs = require("sys.fs")
local newDir = args[1]
if newDir:sub(1, 1) ~= "/" then
newDir = syscall.getcwd().."/"..newDir
end
if newDir:sub(#newDir, #newDir) ~= "/" then
newDir = newDir.."/"
end
if fs.isDir(newDir) then
print(name..": Cannot create directory '"..args[1].."': Directory already exists.")
return
end
fs.mkdir(newDir)
-1
View File
@@ -1 +0,0 @@
print(syscall.getcwd())
-151
View File
@@ -1,151 +0,0 @@
--:Minify:--
local args = { ... }
local target = args[1] or "http://example.com"
local function pass(msg) syscall.devctl(1,"sfgc",10); print(" PASS " .. msg); syscall.devctl(1,"sfgc",1) end
local function fail(msg) syscall.devctl(1,"sfgc",2); print(" FAIL " .. msg); syscall.devctl(1,"sfgc",1) end
local function info(msg) syscall.devctl(1,"sfgc",14); print(" .... " .. msg); syscall.devctl(1,"sfgc",1) end
local function head(msg) syscall.devctl(1,"sfgc",4); print("\n" .. msg); syscall.devctl(1,"sfgc",1) end
local passed, failed = 0, 0
local function check(name, ok, err)
if ok then passed = passed + 1; pass(name)
else failed = failed + 1; fail(name .. " - " .. tostring(err)) end
end
head("[ 1 ] socket() creation")
do
local ok, fd = pcall(syscall.socket, "inet", "stream")
check("socket(inet, stream) returns fd", ok and type(fd) == "number", fd)
if ok then
local cok = pcall(syscall.close, fd)
check("close() on socket fd", cok, "close failed")
end
local ok2, fd2 = pcall(syscall.socket, "unix", "stream")
check("socket(unix, stream) returns fd", ok2 and type(fd2) == "number", fd2)
if ok2 then pcall(syscall.close, fd2) end
local ok3 = pcall(syscall.socket, "ax25", "stream")
check("socket(ax25) returns EAFNOSUPPORT", not ok3, "should have errored")
end
head("[ 2 ] connect() to " .. target)
local sockfd
do
local ok, fd = pcall(syscall.socket, "inet", "stream")
check("socket() before connect", ok, fd)
if ok then
sockfd = fd
local cok, cerr = pcall(syscall.connect, fd, target)
check("connect(" .. target .. ")", cok, cerr)
end
end
head("[ 3 ] send() HTTP GET via socket")
do
if sockfd then
local sok, serr = pcall(syscall.send, sockfd, "")
check("send() does not error", sok, serr)
else
check("send() skipped (no socket)", false, "socket creation failed")
end
end
head("[ 4 ] recv() reads HTTP response")
do
if sockfd then
info("waiting for response (recv blocks up to 10s)...")
local ok, body = pcall(syscall.recv, sockfd, 65536)
check("recv() returns non-empty body", ok and body and #body > 0,
ok and "empty response" or tostring(body))
if ok and body and #body > 0 then
info("received " .. #body .. " bytes")
local preview = body:sub(1, 120):gsub("\r", ""):gsub("\n", " ")
info("preview: " .. preview)
end
pcall(syscall.close, sockfd)
sockfd = nil
else
check("recv() skipped (no socket)", false, "socket creation failed")
end
end
head("[ 5 ] httpget() convenience wrapper")
do
info("GET " .. target .. " ...")
local ok, body = pcall(syscall.httpget, target)
check("httpget() succeeds", ok, body)
if ok then
check("httpget() returns non-empty string", type(body) == "string" and #body > 0, "empty")
if type(body) == "string" and #body > 0 then
info("received " .. #body .. " bytes")
local preview = body:sub(1, 120):gsub("\r", ""):gsub("\n", " ")
info("preview: " .. preview)
local hasHtml = body:lower():find("<html") ~= nil
or body:lower():find("<!doctype") ~= nil
or body:find("{") ~= nil
or body:find("HTTP") ~= nil
check("body looks like HTTP content", hasHtml, "no recognisable content markers")
end
end
end
head("[ 6 ] UNIX socket loopback IPC")
do
local sockPath = "/tmp/socktest.sock"
pcall(syscall.remove, sockPath)
local sok, sfd = pcall(syscall.socket, "unix", "stream")
check("server socket(unix,stream)", sok, sfd)
if sok then
local bok = pcall(syscall.bind, sfd, sockPath)
check("bind(" .. sockPath .. ")", bok, "bind failed")
local lok = pcall(syscall.listen, sfd, 1)
check("listen()", lok, "listen failed")
local cok, cfd = pcall(syscall.socket, "unix", "stream")
check("client socket(unix,stream)", cok, cfd)
if cok then
local connok = pcall(syscall.connect, cfd, sockPath)
check("client connect(" .. sockPath .. ")", connok, "connect failed")
local aok, afd = pcall(syscall.accept, sfd)
check("accept() returns client fd", aok, afd)
if connok and aok then
local sendok = pcall(syscall.send, cfd, "hello hyperion")
check("send() from client", sendok, "send failed")
local rok, data = pcall(syscall.recv, afd, 1024)
check("recv() on server side", rok and data == "hello hyperion",
rok and ("got: " .. tostring(data)) or tostring(data))
local repok = pcall(syscall.send, afd, "hello back")
check("send() reply from server", repok, "send failed")
local rok2, data2 = pcall(syscall.recv, cfd, 1024)
check("recv() reply on client", rok2 and data2 == "hello back",
rok2 and ("got: " .. tostring(data2)) or tostring(data2))
pcall(syscall.close, afd)
end
pcall(syscall.close, cfd)
end
pcall(syscall.close, sfd)
pcall(syscall.remove, sockPath)
end
end
print("")
syscall.devctl(1,"sfgc", failed == 0 and 10 or 2)
print(string.format("Results: %d passed, %d failed", passed, failed))
syscall.devctl(1,"sfgc",1)
if failed > 0 then syscall.exit(1) end
-5
View File
@@ -1,5 +0,0 @@
local syscalls=syscall.sysdump()
for i=1, #syscalls do
print(syscalls[i])
end
print("Total # of syscalls: "..tostring(#syscalls))
-1
View File
@@ -1 +0,0 @@
print((syscall.getUsername() or "Unknown"))
+2
View File
@@ -0,0 +1,2 @@
Hyperion
Astronand
+18
View File
@@ -0,0 +1,18 @@
--:Minify:--
return {
white=0xFFFFFF,
red=0xFF0000,
green=0x00FF00,
blue=0x0000FF,
cyan=0x00FFFF,
yellow=0xFFFF00,
purple=0xFF00FF,
black=0x000000,
gray=0x888888,
lightgrey=0xBBBBBB,
darkgrey=0x444444,
orange=0xFF8800,
mint=0x00FF88,
brown=0xa52a2a,
chocolate=0xd2691e
}
@@ -1,11 +1,6 @@
--:Minify:-- --:Minify:--
local fs={} local fs={}
-- "open" : open
-- "read" : read
-- "write" : write
-- "close" : close
function fs.open(path, mode) function fs.open(path, mode)
local fd=syscall.open(path,mode) local fd=syscall.open(path,mode)
local ret={ local ret={
@@ -140,4 +135,12 @@ function fs.isDir(path)
return syscall.type(path) == "directory" return syscall.type(path) == "directory"
end end
function fs.symlink(target, path)
return syscall.syslink(target, path)
end
function fs.readlink(path)
return syscall.readlink(path)
end
return fs return fs
+182
View File
@@ -0,0 +1,182 @@
--:Minify:--
local http = {}
local syscall = syscall
local function parseUrl(url)
local proto, host, path =
url:match(
"^(https?://)([^/]+)(/.*)$"
)
if not proto then
proto, host =
url:match(
"^(https?://)([^/]+)$"
)
path = "/"
end
if not proto then
return nil, "EINVAL"
end
return host, path
end
local function buildRequest(req)
local host, path = parseUrl(req.url)
if not host then
return nil, path
end
local method =
req.method or "GET"
local body =
req.body or ""
local headers =
table.deepcopy(
req.headers or {}
)
headers.Host =
headers.Host or host
headers.Connection =
headers.Connection or "close"
if body ~= "" then
headers["Content-Length"] =
tostring(#body)
end
local out = {
method ..
" " ..
path ..
" HTTP/1.1"
}
for k, v in pairs(headers) do
out[#out + 1] =
tostring(k) ..
": " ..
tostring(v)
end
out[#out + 1] = ""
out[#out + 1] = body
return table.concat(out, "\r\n")
end
local function parseResponse(response)
local headerBlock, body = response:match("^(.-)\r\n\r\n(.*)$")
if not headerBlock then
return nil, "invalid HTTP response"
end
local headers = {}
-- Parse status line
local statusLine, rest = headerBlock:match("^(.-)\r\n(.*)$")
if not statusLine then
statusLine = headerBlock
rest = ""
end
local version, code, message = statusLine:match("^(HTTP/%d+%.%d+)%s+(%d+)%s+(.*)$")
-- Parse headers
for line in (rest .. "\r\n"):gmatch("(.-)\r\n") do
local key, value = line:match("^([^:]+):%s*(.*)$")
if key then
headers[key:lower()] = value
end
end
return {
code=tonumber(code),
message=message,
headers=headers,
body=body
}
end
function http.request(req)
local raw, err =
buildRequest(req)
if not raw then
return nil, err
end
local fd =
syscall.socket()
if not fd then
return nil, "ESOCKET"
end
local host, path = parseUrl(req.url)
if not host then
syscall.close(fd)
return nil, path
end
local proto = req.url:match("^(https?://)")
local base = proto .. host
local ok, err = syscall.connect(fd, base)
if not ok then
syscall.close(fd)
return nil, err
end
local ok2, err2 = syscall.write(fd, raw)
if not ok2 then
syscall.close(fd)
return nil, err2
end
local out = {}
while true do
local chunk = syscall.read(fd, 4096)
if chunk == "" then
break
end
out[#out+1] = chunk
end
syscall.close(fd)
return parseResponse(table.concat(out))
end
function http.get(url, headers)
return http.request({
url = url,
method = "GET",
headers = headers
})
end
function http.post(url, body, headers)
return http.request({
url = url,
method = "POST",
body = body,
headers = headers
})
end
return http
@@ -1,5 +1,5 @@
local io = {} local io = {}
local fs = require("sys.fs") local fs = require("fs")
function io.open(path, mode) function io.open(path, mode)
return fs.open(path, mode) return fs.open(path, mode)
+1
View File
@@ -0,0 +1 @@
Core library for Hyperion
-6
View File
@@ -1,6 +0,0 @@
local sys = {}
local fs = require("sys.fs")
return sys
-5
View File
@@ -1,5 +0,0 @@
local sys = {}
sys.fs = require("sys.fs")
sys.hpv = require("sys.hpv")
sys.ipc = require("sys.ipc")
return sys
-3
View File
@@ -1,3 +0,0 @@
local ipc = {}
return ipc
-71
View File
@@ -1,71 +0,0 @@
local term = {}
function term.clear()
coroutine.yield("VFS_write", 1, "\27C\25")
end
function term.setCursorPos(x, y)
coroutine.yield("VFS_write", 1, "\27cs"..tostring(y)..";"..tostring(x).."\25")
end
function term.size()
coroutine.yield("VFS_write", 1, "\27ts\25")
local ok, data = coroutine.yield("VFS_read", 0, 16) -- read response
if not ok then error("Failed to get terminal size") end
local x, y = string.match(data, "%R(%d+);(%d+)\25")
return tonumber(x), tonumber(y)
end
function term.getCursorPos()
coroutine.yield("VFS_write", 1, "\27gc\25")
local ok, data = coroutine.yield("VFS_read", 0, 16) -- read response
if not ok then error("Failed to get cursor position") end
local y, x = string.match(data, "%R(%d+);(%d+)\25")
return tonumber(x), tonumber(y)
end
function term.write(data)
coroutine.yield("VFS_write", 1, data)
end
function term.setTextColor(color)
local ok, err = coroutine.yield("VFS_type", 1)
if not ok then error(err) end
if ok ~= "tty" then return end
coroutine.yield("VFS_write", 1, "\27f"..tostring(color).."\25")
end
function term.setBackgroundColor(color)
local ok, err = coroutine.yield("VFS_type", 1)
if not ok then error(err) end
if ok ~= "tty" then return end
coroutine.yield("VFS_write", 1, "\27b"..tostring(color).."\25")
end
function term.isColor()
local ok, err = coroutine.yield("VFS_type", 1)
if not ok then error(err) end
return ok == "tty"
end
function term.scroll(n)
coroutine.yield("VFS_write", 1, "\27S"..tostring(n).."\25")
end
function term.setDefault(color, layer)
if layer then
coroutine.yield("VFS_write", 1, "\27F"..tostring(color).."\25")
else
coroutine.yield("VFS_write", 1, "\27B"..tostring(color).."\25")
end
end
function term.showCursor(show)
if show then
coroutine.yield("VFS_write", 1, "\27sc\25")
else
coroutine.yield("VFS_write", 1, "\27hc\25")
end
end
return term
-46
View File
@@ -1,46 +0,0 @@
--:Minify:--
local kernel=...
local fs=require("sys.fs")
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")
else
kernel.log("Successfully executed kernel task: " .. i, "INFO")
end
end, i)
end
if not fs.exists("/bin/startup") then
fs.mkdir("/bin/startup")
end
local files = fs.list("/bin/startup")
if not files then error("Failed to list /bin/startup") end
for i,v in ipairs(files) do
if v:sub(-4) == ".lua" then
local filepath = "/bin/startup/" .. v
kernel.log("Executing startup script: " .. filepath, "INFO")
local startupFunc, err = load(fs.readAllText(filepath), "@" .. filepath)
if not startupFunc then
kernel.log("Error loading startup script '" .. filepath .. "': " .. err, "ERROR")
else
syscall.spawn(function()
syscall.setuid(1)
local status, err = pcall(startupFunc)
if not status then
kernel.log("Error executing startup script '" .. filepath .. "': " .. err, "ERROR")
else
kernel.log("Successfully executed startup script: " .. filepath, "INFO")
end
end, "startup:" .. v)
end
end
end
while true do
sleep(1)
kernel.saveLog()
end
+1
View File
@@ -0,0 +1 @@
1.0.0
+3
View File
@@ -0,0 +1,3 @@
Hyperion
Astronand
GHXX (Advanced Computers)
@@ -0,0 +1,3 @@
---@diagnostic disable-next-line: undefined-global
local bootdrive=__UEFI.bootDrive
@@ -0,0 +1,146 @@
local comp,disks,autocomplete,ev,ent,data,path,exit,dirty,ls,eb,sb,bp=components,{},false,nil,true,"","",false,true,{},false
local c,gpu=comp:getFirst("computer"),comp:getFirst("gpu")
if gpu then sb=gpu:newBuffer(48,32) end
--c.nvram.data="1/ac/boot.lua"
local function resetScreens()
sb=gpu:newBuffer(64,48)
for typ, obj in comp:list() do
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
if ret[2]=="ENTER_BIOS" then
c.nvram.ENTER_BIOS=true
return true
end
return table.unpack(ret, 2)
end
end
if c.nvram then
path=c.nvram.data or ""
eb=c.nvram.ENTER_BIOS
c.nvram.ENTER_BIOS=false
end
local function drainev()
repeat
ev={c:getMachineEvent()}
if ev[1]=="charTyped" then ent=false end
until not ev[1]
end
if path=="" or eb then drainev() ent=false else
display("Press key to enter boot menu...")
sleep(3)
drainev()
if ent then return boot() end
end
local function proc(key)
if key=="\n" then exit=true
elseif key=="\b" then path=path:sub(1,#path-1) dirty=true
elseif key=="\t" then print("autocomplete")
else path=path..key dirty=true end
end
local function get()
data=""
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
if not ent then
while true do
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
return table.unpack(ret, 2)
end
@@ -0,0 +1,136 @@
local args = {...}
local apis = args[1]
local bootdrive = args[2]
local bootaddr = args[3]
local disks = {}
local internal = {}
local function createDisk(id, hw)
local disk = {
address = id,
isReadOnly = function() return hw.isReadOnly() end
}
function disk:spaceUsed() return hw.spaceUsed() end
function disk:spaceTotal() return hw.spaceTotal() end
function disk:list(path)
if not hw.exists(path) or not hw.isDirectory(path) then
return nil, "not directory"
end
return hw.list(path)
end
function disk:fileExists(path)
return hw.exists(path) and not hw.isDirectory(path)
end
function disk:directoryExists(path)
return hw.exists(path) and hw.isDirectory(path)
end
function disk:type(path)
if not hw.exists(path) then
return nil
elseif hw.isDirectory(path) then
return "directory"
else
return "file"
end
end
function disk:makeDirectory(path)
hw.makeDirectory(path)
end
function disk:remove(path)
if hw.exists(path) then hw.remove(path) end
end
function disk:setLabel(label) hw.setLabel(label) end
function disk:getLabel() return hw.getLabel() end
function disk:attributes(path)
return {
size = hw.size(path),
isDir = hw.isDirectory(path),
isReadOnly = hw.isReadOnly(),
modified = hw.lastModified(path),
created = hw.lastModified(path)
}
end
function disk:open(path, mode)
local fd = hw.open(path, mode)
if not fd then
local dir = path:match("^(.*)/[^/]+$")
if dir and not hw.exists(dir) then
local ok, err = hw.makeDirectory(dir)
if not ok then
return nil, err or "could not create parent directory"
end
end
fd = hw.open(path, mode)
if not fd then
return nil, "file not found or access denied"
end
end
return {
read = function(num) return hw.read(fd, num) end,
readAll = function()
local data = {}
while true do
local chunk = hw.read(fd, math.huge)
if not chunk then break end
data[#data + 1] = chunk
end
return table.concat(data)
end,
write = function(data) return hw.write(fd, data) end,
seek = function(whence, offset)
return hw.seek(fd, whence, offset)
end,
flush = function()
hw.close(fd)
fd = hw.open(path, mode)
end,
close = function()
hw.close(fd)
fd = nil
end
}
end
return disk
end
internal["$"] = createDisk("$", bootdrive)
local function refresh()
disks = {}
for addr in apis.component.list("filesystem") do
if addr ~= bootaddr then
disks[addr] = createDisk(addr, apis.component.proxy(addr))
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,15 @@
--:Minify:--
local kernel=...
kernel.oc={}
kernel.oc.component=kernel.apis.component
kernel.oc.computer=kernel.apis.computer
kernel.log("Installed components:")
for addr, typ in kernel.oc.component.list() do
local dev=kernel.oc.component.proxy(addr)
local tier=""
if dev.getTier then
tier=dev.getTier()
end
kernel.log(" "..addr.." : "..typ..tier)
end
@@ -0,0 +1,23 @@
--:Minify:--
local kernel=...
local component=kernel.oc.component
local function wrap(p)
return function(op, mode)
if op=="type" then
return "device"
elseif op=="open" then
if kernel.uid~=0 then error("EACCES") end
return component.proxy(p)
end
end
end
for addr, typ in kernel.oc.component.list() do
local obj=wrap(addr)
kernel.devfs.data["raw"][addr]=obj
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
@@ -0,0 +1,2 @@
--:Minify:--
local kernel=...
@@ -0,0 +1,177 @@
-- OpenComputers TTY driver
local kernel = ...
local component = kernel.oc.component
local computer = kernel.oc.computer
local plt = {
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
}
local gpus,screens = {},{}
for addr, typ in component.list("gpu") do
if typ == "gpu" then
gpus[#gpus+1]=component.proxy(addr)
end
end
if #gpus>0 then
for addr, typ in component.list("screen") do
if typ == "screen" then
gpus[1].bind(addr)
local w,h = gpus[1].maxResolution()
gpus[1].setResolution(w,h)
screens[addr]={cx=1,cy=1,w=w,h=h,addr=addr,fg=0,bg=0,gpu=nil}
end
end
end
local scrnum = 0
for i,v in pairs(screens) do
scrnum=scrnum+1
end
kernel.log("initialized "..tostring(#gpus).." gpus and "..tostring(scrnum).." screens")
local binds,newid={},0
local curaddr=""
local function scroll(scr, gpu) gpu.copy(1,2,scr.w,scr.h-1,0,-1);gpu.fill(1,scr.h,scr.w,1," ") end
local function write(text, addr)
local g=gpus[1]
local scr=screens[addr]
if not scr then error("NODEV") end
if curaddr~=addr then g.bind(addr); g.setForeground(scr.fg); g.setBackground(scr.bg) end
for i=1,#text do
local char=text:sub(i,i)
if char=="\n" then scr.cx=1;scr.cy=scr.cy+1
elseif char=="\t" then scr.cx=scr.cx+(4-((scr.cx-1)%4))
elseif char=="\b" then if scr.cx>1 then scr.cx=scr.cx-1;g.set(scr.cx,scr.cy," ") end
else g.set(scr.cx,scr.cy,char);scr.cx=scr.cx+1 end
if scr.cx>scr.w then scr.cx=1;scr.cy=scr.cy+1 end
if scr.cy>scr.h then scroll(scr, g);scr.cy=scr.cy-1 end
end
end
local function newtty(addr)
newid=newid+1
kernel.devfs.data["tty"][tostring(newid)]=function(op, mode)
if op=="type" then
return "Terminal"
elseif op=="open" then
local h = {
read=function(amount) end,
write=function(content)
write(content, addr)
end,
size=function()
return screens[addr].w, screens[addr].h
end,
clear=function()
local g=gpus[1]
local scr=screens[addr]
if addr~=curaddr then g.bind(addr) end
g.fill(1,1,scr.w,scr.h," ");
scr.cx,scr.cy=1,1
end,
gpos=function()
return screens[addr].cx, screens[addr].cy
end,
spos=function(x,y)
if not tonumber(x) or not tonumber(y) then error("Invailid arg") end
screens[addr].cx, screens[addr].cy = x,y
end,
sfgc=function(c)
screens[addr].fg=c
end,
sbgc=function(c)
screens[addr].bg=c
end,
gfgc=function()
return screens[addr].fg
end,
gbgc=function()
return screens[addr].bg
end,
isvirt=function()
return false
end,
gplt=function()
return plt
end
}
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
if #gpus>=1 and scrnum>=1 then
for addr,obj in pairs(screens) do
newtty(addr)
end
end
@@ -0,0 +1,122 @@
--:Minify:--
local kernel=...
kernel.oc.keyboards={}
local kbs=kernel.oc.keyboards
local kbidx=0
local keyboard = {}
keyboard.keys = {
back = 0x0E, -- backspace
delete = 0xD3,
down = 0xD0,
enter = 0x1C,
home = 0xC7,
lcontrol = 0x1D,
left = 0xCB,
lmenu = 0x38, -- left Alt
lshift = 0x2A,
pageDown = 0xD1,
rcontrol = 0x9D,
right = 0xCD,
rmenu = 0xB8, -- right Alt
rshift = 0x36,
space = 0x39,
tab = 0x0F,
up = 0xC8,
["end"] = 0xCF,
numpadenter = 0x9C,
}
kernel.oc.keys=keyboard.keys
for i=0, 255 do
kernel.oc.keys[string.char(i)]=i
end
-------------------------------------------------------------------------------
function keyboard.isAltDown(addr)
return kbs[addr].pressedCodes[keyboard.keys.lmenu] or kbs[addr].pressedCodes[keyboard.keys.rmenu]
end
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].pressedCodes[keyboard.keys.lcontrol] or kbs[addr].pressedCodes[keyboard.keys.rcontrol]
end
function keyboard.isKeyDown(addr,charOrCode)
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].pressedCodes[keyboard.keys.lshift] or kbs[addr].pressedCodes[keyboard.keys.rshift]
end
kernel.oc.keyboard=keyboard
local function serializeBool(bool)
if bool then
return "T"
else
return "F"
end
end
for addr, typ in kernel.oc.component.list("keyboard") do
if typ=="keyboard" then
kbidx=kbidx+1
kbs[addr]={pressedChars = {}, pressedCodes = {}, events=kernel.newFifo()}
kernel.devfs.data["input"]["keyboard"..tostring(kbidx)]=function(op,mode)
if op=="type" then
return "Keyboard"
elseif op=="open" then
local h = {
read=function(amount)
amount = amount or 1
local rv=""
for i=1, amount do
local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then
rv=rv..event[1]
else
break
end
end
if rv~="" then return rv end
local task=kernel.currentTask
task.status="D"
task.io=function()
local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then return event[1] end
end
return nil
end,
write=function(content)
end,
gctrl=function()
return serializeBool(keyboard.isControlDown(addr))..";"..serializeBool(keyboard.isAltDown(addr))
end,
isKeyDown=function(char)
return keyboard.isKeyDown(addr,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
end
end
@@ -0,0 +1,99 @@
--:Minify:--
local kernel=...
local keys=kernel.oc.keys
kernel.processes.ocdaemon = function()
local timeout = false
kernel.log("OC daemon started")
local ctrlKeyMap = {
[keys.a]=1, [keys.b]=2, [keys.c]=3,
[keys.d]=4, [keys.e]=5, [keys.f]=6,
[keys.g]=7, [keys.h]=8, [keys.i]=9,
[keys.j]=10, [keys.k]=11, [keys.l]=12,
[keys.m]=13, [keys.n]=14, [keys.o]=15,
[keys.p]=16, [keys.q]=17, [keys.r]=18,
[keys.s]=19, [keys.t]=20, [keys.u]=21,
[keys.v]=22, [keys.w]=23, [keys.x]=24,
[keys.y]=25, [keys.z]=26,
}
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 addr = event[2]
local char = event[3]
local keyCode = event[4]
if eventType == "key_down" then
local keyboard = kernel.oc.keyboards[addr]
if keyboard.ctrl then
local ctrlByte = ctrlKeyMap[keyCode]
if ctrlByte then
if ctrlByte == 3 then
for _, task in ipairs(syscall.getTasks()) do
syscall.sigsend(task, 1)
end
else
keyboard.events.push(string.char(ctrlByte))
end
end
else
local special = specialKeyMap[keyCode]
if special then
keyboard.events.push(special)
elseif char and char > 0 then
keyboard.events.push(kernel.apis.unicode.char(char))
end
end
elseif eventType == "key_up" then
end
timeout = false
else
timeout = true
end
if timeout then
sleep(0.05)
end
end
end
kernel.log("OC daemon queued for execution")
@@ -0,0 +1,146 @@
--:Minify:--
local kernel=...
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
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 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, debug.traceback, task, pid)
if not ok then
kernel.log("[MAIN 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
ret = { coroutine.resume(task.coro, table.unpack(task.syscallReturn)) }
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], debug.traceback, 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
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
end
+1
View File
@@ -0,0 +1 @@
firmware for Advanced Computers
+1
View File
@@ -0,0 +1 @@
1.0.0
@@ -0,0 +1,5 @@
--:Minify:--
local kernel=...
if kernel.arch~="cct" then
kernel.deny("cc-tweaked/31_keyboards.kmod")
end
@@ -0,0 +1,9 @@
--:Minify:--
local kernel=...
local kbs = {kernel.cct.peripheral.find("tm_keyboard")}
kernel.cct.eventhooks["tm_keyboard_char"]=function(...)
end
+2
View File
@@ -0,0 +1,2 @@
Hyperion
Astronand
-316
View File
@@ -1,316 +0,0 @@
-- :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,
getfenv = 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,
setfenv = 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
local eventQueue = {}
local function queueEvent(event, ...)
table.insert(eventQueue, {event, ...})
end
local computer = {
time = function() return apis.os.epoch("utc") end,
clock = function() return apis.os.clock() * 1000 end,
shutdown = apis.os.shutdown,
reboot = apis.os.reboot,
getMachineEvent = function()
if #eventQueue > 0 then
return table.unpack(table.remove(eventQueue, 1))
else
return nil
end
end,
getEEPROM = function() return getFile("/startup.lua") end,
setEEPROM = function(_, text)
local h = apis.fs.open("/startup.lua", "w")
h.write(text)
h.close()
end
}
local icolors = {
[0x1] = 1, -- #000000
[0x2] = 2, -- #FFFFFF
[0x4] = 3, -- #FF0000
[0x8] = 4, -- #00FF00
[0x10] = 5, -- #0000FF
[0x20] = 6, -- #00FFFF
[0x40] = 7, -- #FF00FF
[0x80] = 8, -- #FFFF00
[0x100] = 9, -- #FF6D00
[0x200] = 10, -- #6DFF55
[0x400] = 11, -- #24FFFF
[0x800] = 12, -- #924900
[0x1000] = 13, -- #6D6D55
[0x2000] = 14, -- #DBDBAA
[0x4000] = 15, -- #6D00FF
[0x8000] = 16 -- #B6FF00
}
local colors = {
0x0001, -- #000000
0x0002, -- #FFFFFF
0x0004, -- #FF0000
0x0008, -- #00FF00
0x0010, -- #0000FF
0x0020, -- #00FFFF
0x0040, -- #FF00FF
0x0080, -- #FFFF00
0x0100, -- #FF6D00
0x0200, -- #6DFF55
0x0400, -- #24FFFF
0x0800, -- #924900
0x1000, -- #6D6D55
0x2000, -- #DBDBAA
0x4000, -- #6D00FF
0x8000 -- #B6FF00
}
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, apis, initFs, "cct", "/sbin/init",
{
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(colors[color])
end,
setTextColor = function(_, color)
apis.term.setTextColor(colors[color])
end,
getBackgroundColor = function()
return icolors[apis.term.getBackgroundColor()]
end,
getTextColor = function()
return icolors[apis.term.getTextColor()]
end
}, computer, fs, "$")
if not ok then displaySuperBadError(err) end
end)
function coroutine.resumeWithTimeout(co, timeout, ...)
local startTime = computer.time()
debug.sethook(co, function()
if computer.time() > 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 = coroutine.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
displaySuperBadError("Kernel error: " .. tostring(err))
coroutine.yield("key")
end
end
end, debug.traceback)
if not ok then displaySuperBadError("Fatal error during boot: " .. err) end
while true do coroutine.yield() end
@@ -1,155 +0,0 @@
-- :Minify:--
local apis = ({...})[1]
local BOOT_DRIVE_PATH = apis.BOOT_DRIVE_PATH or "/$"
local fs = apis.fs
local native = apis.peripheral
local peripheral = {}
local sides = {"top", "bottom", "left", "right", "front", "back"}
function peripheral.getType(name)
if native.isPresent(name) then return native.getType(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, "getTypeRemote", name)
end
end
return nil
end
function peripheral.getNames()
local names = {}
for n = 1, #sides do
local side = sides[n]
if native.isPresent(side) then table.insert(names, side) end
if native.hasType(side, "peripheral_hub") then
local hubSides = native.call(side, "getConnectedSides")
for _, hubSide in ipairs(hubSides) do
table.insert(names, hubSide)
end
end
end
return names
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
})
local function refresh()
for id, _ in pairs(disks) do
if not peripheral.getType(id) then disks[id] = nil end
end
for _, name in ipairs(peripheral.getNames()) do
if peripheral.getType(name) == "disk" then
if not disks[name] then
local mount = disk.getMountPath(name)
if mount then
disks[name] = createDisk(name, mount, false, disk)
end
end
end
end
end
local function iter()
refresh()
local combined = {}
for id, obj in pairs(internal) do combined[id] = obj end
for id, obj in pairs(disks) do combined[id] = obj end
return pairs(combined)
end
return {refresh = refresh, list = iter}
@@ -0,0 +1,593 @@
--: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
@@ -58,11 +58,11 @@ function _G.term.native()
term.setCursorPos(1, 1) term.setCursorPos(1, 1)
term.setCursorBlink(true) term.setCursorBlink(true)
term.clear() term.clear()
local file = fs.open(BOOT_DRIVE_PATH.."/boot/cct/boot.lua", "r") local file = fs.open(BOOT_DRIVE_PATH.."/cct/boot.lua", "r")
if file == nil then if file == nil then
term.setCursorBlink(false) term.setCursorBlink(false)
term.setTextColor(16384) term.setTextColor(16384)
term.write("Could not find /boot/cct/boot.lua. UnBIOS cannot continue.") term.write("Could not find /cct/boot.lua. UnBIOS cannot continue.")
term.setCursorPos(1, 2) term.setCursorPos(1, 2)
term.write("Press any key to continue") term.write("Press any key to continue")
coroutine.yield("key") coroutine.yield("key")
@@ -73,7 +73,7 @@ function _G.term.native()
if fn == nil then if fn == nil then
term.setCursorBlink(false) term.setCursorBlink(false)
term.setTextColor(16384) term.setTextColor(16384)
term.write("Could not load /boot/cc/boot.lua. UnBIOS cannot continue.") term.write("Could not load /cc/boot.lua. UnBIOS cannot continue.")
term.setCursorPos(1, 2) term.setCursorPos(1, 2)
term.write(err) term.write(err)
term.setCursorPos(1, 3) term.setCursorPos(1, 3)
@@ -0,0 +1,287 @@
--: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) or 0) - (fs.getFreeSpace(basePath) or 0)
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
})
internal["root"] = createDisk("root", "/root", false, {
setLabel = function(label)
local h = fs.open("/.rootlabel", "w")
h.write(label)
h.close()
end,
getLabel = function()
local h = fs.open("/.rootlabel", "r")
if not h then return "$" end
local label = h.readAll()
h.close()
return label
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,12 @@
--: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
@@ -0,0 +1,195 @@
--:Minify:--
-- CCT driver peripheral helper
local kernel=...
kernel.cct={}
kernel.cct.peripheral={}
kernel.cct.callAsync=kernel.apis.callAsync
local peripheral=kernel.cct.peripheral
local apis = kernel.apis
local native = apis.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
local id = kernel.cct.callAsync(native.call, name, method, ...)
kernel.currentTask.io=function()
if kernel.apis.callAsyncReturn[id] then
local r=kernel.apis.callAsyncReturn[id]
if not r[1] then error(r[2]) end
kernel.apis.callAsyncReturn[id]=nil
return table.unpack(r,2)
end
end
kernel.currentTask.status="D"
return
end
for n = 1, #sides do
local side = sides[n]
if native.hasType(side, "peripheral_hub") and native.call(side, "isPresentRemote", name) then
local id = kernel.cct.callAsync(native.call, side, "callRemote", name, method, ...)
kernel.currentTask.io=function()
if kernel.apis.callAsyncReturn[id] then
local r=kernel.apis.callAsyncReturn[id]
if not r[1] then error(r[2]) end
kernel.apis.callAsyncReturn[id]=nil
return table.unpack(r,2)
end
end
kernel.currentTask.status="D"
return
end
end
return nil
end
function peripheral.callnative(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, wrap)
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,
})
if wrap then
for _, method in ipairs(methods) do
result[method] = function(...)
return peripheral.call(name, method, ...)
end
end
else
for _, method in ipairs(methods) do
result[method] = function(...)
return peripheral.callnative(name, method, ...)
end
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
@@ -0,0 +1,26 @@
--:Minify:--
local kernel=...
local peripheral=kernel.cct.peripheral
local function wrap(p)
return function(op, mode)
if op=="type" then
return "device"
elseif op=="open" then
if kernel.uid~=0 then error("EACCES") end
return peripheral.wrap(p, true)
end
end
end
local peripherals=peripheral.getNames()
for i=1, #peripherals do
local p=peripherals[i]
local typ=peripheral.getType(p)
local file=wrap(p)
kernel.devfs.data["raw"][p]=file
local typefolder=kernel.devfs.data["raw"]["by-type"][typ]
if not typefolder then typefolder={} end
typefolder[tostring(#table.keys(typefolder)+1)] = file
kernel.devfs.data["raw"]["by-type"][typ]=typefolder
end
@@ -0,0 +1,207 @@
--:Minify:--
local kernel = ...
local handler = {}
local http = kernel.apis.http
kernel.cct.httpqueue = kernel.cct.httpqueue or {}
kernel.cct.httpresponse = kernel.cct.httpresponse or {}
kernel.cct.httperror = kernel.cct.httperror or {}
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 split=string.split(lines[1], " ")
if #split~=3 then
return nil, "EINVAL"
end
local method, path, ver = table.unpack(split)
local headers = {}
for i = 2, #lines do
local k, v = lines[i]:match("^([^:]+):%s*(.*)$")
if k then
headers[k] = v
end
end
if path:sub(1,1)~="/" then
return nil, "EINVAL"
end
local url = address..path
local req = {
url = url,
method = method,
headers = headers
}
if body ~= "" then
req.body = body
end
return req, url
end
local function buildResponse(resp)
if not resp then
return nil, "EINVAL"
end
local code, msg = resp.getResponseCode()
local headers = resp.getResponseHeaders()
local body = resp.readAll() or ""
resp.close()
local out = {
"HTTP/1.1 " ..
tostring(code) ..
" " ..
tostring(msg or "")
}
for i,v in pairs(headers) do
out[#out+1] = i..": "..v
end
out[#out + 1] = ""
out[#out + 1] = body
return table.concat(out, "\r\n")
end
function handler.connect(fd, address)
local fdo = kernel.currentTask.fd[fd]
if not fdo then
return nil, "EBADF"
end
fdo.handle.write = function(raw)
local req, url = parseRawRequest(raw, address)
if not req then
return nil, url
end
kernel.cct.httpqueue[url] = true
local ok, err = http.request(req)
if not ok then
kernel.cct.httpqueue[url] = nil
return nil, err
end
if fdo.socket.active then
fdo.socket.content=nil
fdo.socket.file.close()
fdo.socket.file=nil
end
fdo.socket.active=true
fdo.socket.url=url
fdo.socket.loaded=false
return true
end
fdo.handle.read = function(count)
if not fdo.socket.active then
return
end
if not kernel.cct.httpqueue[fdo.socket.url] and not fdo.socket.loaded then
fdo.socket.file=kernel.sfile(buildResponse(kernel.cct.httpresponse[fdo.socket.url]))
kernel.cct.httpqueue[fdo.socket.url]=nil
kernel.cct.httpresponse[fdo.socket.url]=nil
fdo.socket.loaded=true
end
if not fdo.socket.file then
kernel.currentTask.io=function()
if not kernel.cct.httpqueue[fdo.socket.url] then
fdo.socket.file=kernel.sfile(buildResponse(kernel.cct.httpresponse[fdo.socket.url]))
kernel.cct.httpqueue[fdo.socket.url]=nil
kernel.cct.httpresponse[fdo.socket.url]=nil
fdo.socket.loaded=true
return fdo.socket.file.read(count)
end
end
kernel.currentTask.status="D"
return
else
return fdo.socket.file.read(count)
end
end
fdo.handle.seek = function(whence, offset)
if not fdo.socket.active then
return
end
if not kernel.cct.httpqueue[fdo.socket.url] and not fdo.socket.loaded then
fdo.socket.file=kernel.sfile(buildResponse(kernel.cct.httpresponse[fdo.socket.url]))
kernel.cct.httpqueue[fdo.socket.url]=nil
kernel.cct.httpresponse[fdo.socket.url]=nil
fdo.socket.loaded=true
end
if not fdo.socket.file then
kernel.currentTask.io=function()
if not kernel.cct.httpqueue[fdo.socket.url] then
fdo.socket.file=kernel.sfile(buildResponse(kernel.cct.httpresponse[fdo.socket.url]))
kernel.cct.httpqueue[fdo.socket.url]=nil
kernel.cct.httpresponse[fdo.socket.url]=nil
fdo.socket.loaded=true
return fdo.socket.file.seek(whence, offset)
end
end
kernel.currentTask.status="D"
return
else
return fdo.socket.file.seek(whence, offset)
end
end
fdo.handle.close = function()
fdo.socket.file.close()
fdo.socket.active=false
kernel.cct.httpqueue[fdo.socket.url] = nil
kernel.cct.httpresponse[fdo.socket.url] = nil
kernel.cct.httperror[fdo.socket.url] = nil
return true
end
return true
end
kernel.socket.registerProtocal(
"http://",
handler
)
kernel.socket.registerProtocal(
"https://",
handler
)
@@ -0,0 +1,25 @@
--: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}
@@ -0,0 +1,267 @@
--:Minify:--
local kernel = ...
local peripheral=kernel.cct.peripheral
kernel.cct.gfx={}
kernel.cct.term={}
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 plt = {
0xFFFFFF,
0xFF0000,
0x00FF00,
0x0000FF,
0x00FFFF,
0xFF00FF,
0xFFFF00,
0xFF6D00,
0x6DFF55,
0x24FFFF,
0x924900,
0x6D6D55,
0xDBDBAA,
0x6D00FF,
0xB6FF00,
0x000000
}
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
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
kernel.cct.ctrl,kernel.cct.alt = false, false
local function serializeBool(bool)
if bool then
return "T"
else
return "F"
end
end
local function newtty(obj, id, ev)
kernel.cct.term[id]=obj
obj.setPaletteColor(0x1, 0xFFFFFF) -- #000000
obj.setPaletteColor(0x2, 0xFF0000) -- #FFFFFF
obj.setPaletteColor(0x4, 0x00FF00) -- #FF0000
obj.setPaletteColor(0x8, 0x0000FF) -- #00FF00
obj.setPaletteColor(0x10, 0x00FFFF) -- #0000FF
obj.setPaletteColor(0x20, 0xFF00FF) -- #00FFFF
obj.setPaletteColor(0x40, 0xFFFF00) -- #FF00FF
obj.setPaletteColor(0x80, 0xFF6D00) -- #FFFF00
obj.setPaletteColor(0x100, 0x6DFF55) -- #FF6D00
obj.setPaletteColor(0x200, 0x24FFFF) -- #6DFF55
obj.setPaletteColor(0x400, 0x924900) -- #24FFFF
obj.setPaletteColor(0x800, 0x6D6D55) -- #924900
obj.setPaletteColor(0x1000, 0xDBDBAA) -- #6D6D55
obj.setPaletteColor(0x2000, 0x6D00FF) -- #DBDBAA
obj.setPaletteColor(0x4000, 0xB6FF00) -- #6D00FF
obj.setPaletteColor(0x8000, 0x000000) -- #B6FF00
kernel.devfs.data["tty"][id] = function(op, mode)
if op=="type" then
return "Terminal"
elseif op=="open" then
local h = {
write=function(content)
write(content, obj)
end,
size=function()
return obj.getSize()
end,
clear=function()
obj.clear()
obj.setCursorPos(1,1)
end,
gpos=function()
return obj.getCursorPos()
end,
spos=function(x,y)
return obj.setCursorPos(x,y)
end,
sfgc=function(c)
fg=c
return obj.setTextColor(aprox(c))
end,
sbgc=function(c)
bg=c
return obj.setBackgroundColor(aprox(c))
end,
gfgc=function()
return fg
end,
gbgc=function()
return bg
end,
isvirt=function()
return false
end,
gplt=function()
return table.deepcopy(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
}
return h
end
end
end
local fifo = kernel.newFifo()
kernel.cct.fifo=fifo
newtty(kernel.apis.term, "1", function() end)
for i,v in ipairs({peripheral.find("monitor")}) do
newtty(v,tostring(i+1),function () end)
end
kernel.devfs.data["input"]["keyboard1"] = function(op, mode)
if op=="type" then
return "Keyboard"
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
if rv~="" then return rv end
local task=kernel.currentTask
task.status="D"
task.io=function()
local event = {fifo.pop()}
if event[1] then return event[1] end
end
return nil
end,
gctrl=function()
return serializeBool(kernel.cct.ctrl)..";"..serializeBool(kernel.cct.alt)
end
}
return h
end
end
@@ -0,0 +1,120 @@
--:Minify:--
local kernel=...
local keys=kernel.apis.keys
kernel.cct.eventhooks={}
kernel.processes.cctdaemon = function()
local timeout = false
kernel.log("CCT daemon started")
while true do
local event = {kernel.EFI:getMachineEvent()}
if event[1] then
local eventType = event[1]
local charOrKey = event[3]
local ctrlKeyMap = {
[keys.a]=1, [keys.b]=2, [keys.c]=3,
[keys.d]=4, [keys.e]=5, [keys.f]=6,
[keys.g]=7, [keys.h]=8, [keys.i]=9,
[keys.j]=10, [keys.k]=11, [keys.l]=12,
[keys.m]=13, [keys.n]=14, [keys.o]=15,
[keys.p]=16, [keys.q]=17, [keys.r]=18,
[keys.s]=19, [keys.t]=20, [keys.u]=21,
[keys.v]=22, [keys.w]=23, [keys.x]=24,
[keys.y]=25, [keys.z]=26,
}
if eventType == "keyPressed" then
if charOrKey == keys.leftCtrl or charOrKey == keys.rightCtrl then
kernel.cct.ctrl = true
elseif charOrKey == keys.leftAlt or charOrKey == keys.rightAlt then
kernel.cct.alt = true
end
if kernel.cct.ctrl then
local ctrlByte = ctrlKeyMap[charOrKey]
if ctrlByte then
if ctrlByte == 3 then
for _, task in ipairs(syscall.getTasks()) do
syscall.sigsend(task, 1)
end
else
kernel.cct.fifo.push(string.char(ctrlByte))
end
end
else
local specialKeyMap = {
[keys.up] = "",
[keys.down] = "",
[keys.right] = "",
[keys.left] = "",
[keys.home] = "",
[keys["end"]] = "",
[keys.pageUp] = "[5~",
[keys.pageDown] = "[6~",
[keys.delete] = "[3~",
}
local special = specialKeyMap[charOrKey]
if special then kernel.cct.fifo.push(special) end
end
elseif eventType == "keyReleased" then
if charOrKey == keys.leftCtrl or charOrKey == keys.rightCtrl then
kernel.cct.ctrl = false
elseif charOrKey == keys.leftAlt or charOrKey == keys.rightAlt then
kernel.cct.alt = false
end
elseif eventType == "keyTyped" then
if charOrKey then kernel.cct.fifo.push(charOrKey) end
elseif eventType == "mouse_scroll" then
if event[2] == 1 then
kernel.cct.fifo.push("S")
kernel.cct.mouse.fifo.push("S")
else
kernel.cct.fifo.push("T")
kernel.cct.mouse.fifo.push("T")
end
elseif eventType == "http_success" then
if kernel.cct.httpqueue[event[2]] then
kernel.cct.httpqueue[event[2]]=nil
kernel.cct.httpresponse[event[2]]=event[3]
end
elseif eventType == "http_failure" then
if kernel.cct.httpqueue[event[2]] then
kernel.cct.httpqueue[event[2]]=nil
kernel.cct.httperror[event[2]]=event[3]
kernel.cct.httpresponse[event[2]]=event[4]
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
if kernel.cct.eventhooks[eventType] then
local ok,err = xpcall(kernel.cct.eventhooks[eventType], debug.traceback, 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("CCT daemon queued for execution")
@@ -0,0 +1,161 @@
--:Minify:--
local kernel=...
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
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, 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
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, debug.traceback, 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], debug.traceback, 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
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
@@ -0,0 +1,25 @@
--:Minify:--
local kernel=...
local rs=kernel.apis.rs
local sides = {top=1, bottom=2, left=3, right=4, front=5, back=6}
local function newGPIO(side)
return function(mode, data)
if mode=="w" then
if type(data)~="boolean" then error("data: expected bool") end
rs.setOutput(side, data)
elseif mode=="wa" then
if type(data)~="number" then error("data: expected bool") end
rs.setAnalogOutput(side, data)
elseif mode=="r" then
return rs.getInput(side)
elseif mode=="ra" then
return rs.getAnalogInput(side)
end
end
end
for side, alt in pairs(sides) do
local func=newGPIO(side)
kernel.gpio[side]=func
kernel.gpio[alt]=func
end
@@ -0,0 +1 @@
firmware for ComputerCraft Tweaked
@@ -1,363 +0,0 @@
-- :Minify:--
local kernel = ...
local apis = kernel.apis
local native = apis.peripheral
local sides = {"top", "bottom", "left", "right", "front", "back"}
local peripheral={}
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 icolors = {
[0x1] = 1, -- #000000
[0x2] = 2, -- #FFFFFF
[0x4] = 3, -- #FF0000
[0x8] = 4, -- #00FF00
[0x10] = 5, -- #0000FF
[0x20] = 6, -- #00FFFF
[0x40] = 7, -- #FF00FF
[0x80] = 8, -- #FFFF00
[0x100] = 9, -- #FF6D00
[0x200] = 10, -- #6DFF55
[0x400] = 11, -- #24FFFF
[0x800] = 12, -- #924900
[0x1000] = 13, -- #6D6D55
[0x2000] = 14, -- #DBDBAA
[0x4000] = 15, -- #6D00FF
[0x8000] = 16 -- #B6FF00
}
local colors = {
0x0001, -- #000000
0x0002, -- #FFFFFF
0x0004, -- #FF0000
0x0008, -- #00FF00
0x0010, -- #0000FF
0x0020, -- #00FFFF
0x0040, -- #FF00FF
0x0080, -- #FFFF00
0x0100, -- #FF6D00
0x0200, -- #6DFF55
0x0400, -- #24FFFF
0x0800, -- #924900
0x1000, -- #6D6D55
0x2000, -- #DBDBAA
0x4000, -- #6D00FF
0x8000 -- #B6FF00
}
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
kernel.devfs.data.tty={}
local ctrl,alt = false, false
local function serializeBool(bool)
if bool then
return "T"
else
return "F"
end
end
local function newtty(obj, id, ev)
kernel.devfs.data["tty"][id] = function(op, mode)
if op=="type" then
return "character device"
elseif op=="open" then
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(content, obj)
end,
size=function()
local s={obj.getSize()}
return table.concat(s,";")
end,
clear=function()
obj.clear()
obj.setCursorPos(1,1)
end,
gpos=function()
local s={obj.getCursorPos()}
return table.concat(s,";")
end,
spos=function(x,y)
return obj.setCursorPos(x,y)
end,
sfgc=function(c)
return obj.setTextColor(colors[c])
end,
sbgc=function(c)
return obj.setBackgroundColor(colors[c])
end,
gfgc=function()
return icolors[obj.getTextColor()]
end,
gbgc=function()
return icolors[obj.getBackgroundColor()]
end,
gctrl=function()
return serializeBool(ctrl)..";"..serializeBool(alt)
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
end
local fifo = kernel.newFifo()
kernel.processes.cctmond = function()
local timeout = false
while true do
local event = {kernel.computer:getMachineEvent()}
if event[1] then
local eventType = event[1]
local charOrKey = event[3]
-- Update modifier keys
if eventType == "keyPressed" then
if charOrKey == apis.keys.leftCtrl or charOrKey == apis.keys.rightCtrl then
ctrl = true
elseif charOrKey == apis.keys.leftAlt or charOrKey == apis.keys.rightAlt then
alt = true
end
-- Handle Ctrl+C
if ctrl and charOrKey == apis.keys.c then
for _, task in ipairs(syscall.getTasks()) do
syscall.sigsend(task, 1) -- SIGINT
end
end
elseif eventType == "keyReleased" then
if charOrKey == apis.keys.leftCtrl or charOrKey == apis.keys.rightCtrl then
ctrl = false
elseif charOrKey == apis.keys.leftAlt or charOrKey == apis.keys.rightAlt then
alt = false
end
elseif eventType == "keyTyped" then
if charOrKey then fifo.push(charOrKey) end
end
timeout = false
else
timeout = true
end
if timeout then
sleep(0.05)
end
end
end
newtty(apis.term, "TTY1", fifo.pop)
for i,v in ipairs({peripheral.find("monitor")}) do
v.setTextScale(.5)
v.write("Initializing...")
newtty(v,"TTY"..tostring(i+1),function () end)
end
@@ -1,26 +0,0 @@
local args={...}
local kernel=args[1]
local driver={}
driver.name="CCT Term Module"
driver.version="0.1.0"
driver.type="gpio"
driver.description="CCT redstone Module Kernel Module"
driver.arch="cct"
driver.author="HyperionOS Dev Team"
driver.license="MIT"
driver.api={}
function driver.load()
-- will
end
function driver.unload()
-- Nothing to unload
end
function driver.main()
-- Nothing to run
end
-- kernel.drivers.register(driver)
+1
View File
@@ -0,0 +1 @@
1.3.0
+2
View File
@@ -0,0 +1,2 @@
Hyperion
Spsf
@@ -0,0 +1,691 @@
--:Minify:--
local hostScreen = screen
local hostChip = chip
local hostYield = coroutine.yield
local function throwError(msg)
local okS, sw = pcall(hostScreen.getSize)
if okS then
pcall(hostScreen.set, 170, 0, 0)
pcall(hostScreen.draw)
end
pcall(hostChip.crash, "Hyperion NC boot failure: " .. tostring(msg))
while true do hostYield() end
end
local ok, err = xpcall(function()
local apis = {}
local keep = {
coroutine = true, debug = true, _VERSION = true, assert = true,
error = true, getmetatable = true, ipairs = true, load = true,
math = true, next = true, pairs = true, pcall = true,
rawequal = true, rawget = true, rawlen = true, rawset = true,
select = true, setmetatable = true, string = true, table = true,
tonumber = true, tostring = true, type = true, xpcall = true,
utf8 = true, _G = true
}
local moveKeys = {}
for k in pairs(_G) do
if not keep[k] then moveKeys[#moveKeys + 1] = k end
end
for i = 1, #moveKeys do
local k = moveKeys[i]
apis[k] = _G[k]
_G[k] = nil
end
local fsChip = apis.chip
local fsEvent = apis.event
local fsFiles = apis.files
local fsScreen = apis.screen
if not fsChip or not fsEvent or not fsFiles or not fsScreen then
throwError("missing NeetComputers APIs (need screen/event/files/chip)")
end
local dbgSethook = debug.sethook
function sleep(t)
t = tonumber(t) or 0
if t <= 0 then coroutine.yield() return end
local target = fsChip.getUnixTime() + t
while fsChip.getUnixTime() < target do coroutine.yield() end
end
local bootUnix = fsChip.getUnixTime()
local function fmtDate(t)
t = tonumber(t) or 0
local days = math.floor(t / 86400)
local rem = math.floor(t - days * 86400)
if rem < 0 then rem = 0 end
local z = days + 719468
local era = math.floor(z / 146097)
local doe = z - era * 146097
local yoe = math.floor((doe - math.floor(doe / 1460)
+ math.floor(doe / 36524) - math.floor(doe / 146096)) / 365)
local y = yoe + era * 400
local doy = doe - (365 * yoe + math.floor(yoe / 4) - math.floor(yoe / 100))
local mp = math.floor((5 * doy + 2) / 153)
local d = doy - math.floor((153 * mp + 2) / 5) + 1
local m = mp + 3
if m > 12 then m = m - 12 end
if m <= 2 then y = y + 1 end
local hh = math.floor(rem / 3600)
local mi = math.floor((rem - hh * 3600) / 60)
local ss = rem - hh * 3600 - mi * 60
return string.format("%04d-%02d-%02dT%02d:%02d:%02dZ", y, m, d, hh, mi, ss)
end
local function normPartList(raw)
if type(raw) ~= "table" then return {} end
if type(raw[1]) == "table" and raw[1].name == nil and #raw == 1 then
raw = raw[1]
end
local out = {}
for _, p in ipairs(raw) do
local name = type(p) == "table" and p.name or p
if type(name) == "string" and name ~= "" then
out[#out + 1] = name
end
end
return out
end
local function diskSlots()
local out = {}
local okD, raw = pcall(fsFiles.getDisks)
if okD and type(raw) == "table" then
for _, d in ipairs(raw) do
local slot = type(d) == "table" and (d.slot or d[1]) or d
if type(slot) == "number" then out[#out + 1] = slot end
end
end
if #out == 0 then out = {0} end
table.sort(out)
return out
end
local function isBootPart(slot, part)
local okA, a = pcall(fsFiles.exists, part .. ":/kernel.lua", slot)
if not (okA and a) then return false end
local okB, b = pcall(fsFiles.exists, part .. ":/nc/boot.lua", slot)
return okB and b == true
end
local BOOT_DISK, BOOT_PART = nil, nil
local slots = diskSlots()
for _, slot in ipairs(slots) do
local okB, bp = pcall(fsFiles.getBootPath, slot)
if okB and type(bp) == "string" and bp ~= "" then
local part = bp:match("^([^:]+):")
if part and isBootPart(slot, part) then
BOOT_DISK, BOOT_PART = slot, part
break
end
end
end
if not BOOT_DISK then
local okB, bp = pcall(fsFiles.getBootPath)
if okB and type(bp) == "string" and bp ~= "" then
local part = bp:match("^([^:]+):")
if part then
for _, slot in ipairs(slots) do
if isBootPart(slot, part) then
BOOT_DISK, BOOT_PART = slot, part
break
end
end
end
end
end
if not BOOT_DISK then
for _, slot in ipairs(slots) do
local okP, raw = pcall(fsFiles.getPartitions, slot)
if okP then
for _, part in ipairs(normPartList(raw)) do
if isBootPart(slot, part) then
BOOT_DISK, BOOT_PART = slot, part
break
end
end
end
if BOOT_DISK then break end
end
end
if not BOOT_DISK then
throwError("no bootable Hyperion partition found")
end
local function getFile(path)
local okH, h = pcall(fsFiles.open, BOOT_PART .. ":" .. path, "r", BOOT_DISK)
if not okH or not h then
throwError("cannot open boot file: " .. path)
end
local okR, data = pcall(h.read, "a")
pcall(h.close)
if not okR or type(data) ~= "string" then
throwError("cannot read boot file: " .. path)
end
return data
end
local function readBootData(path)
local okH, h = pcall(fsFiles.open, BOOT_PART .. ":" .. path, "rb", BOOT_DISK)
if not okH or not h then return nil end
local okR, data = pcall(h.read, "a")
pcall(h.close)
if not okR or type(data) ~= "string" then return nil end
return data
end
local function parsePSF(data)
if not data or #data < 4 then return nil, "too short" end
local b1, b2 = data:byte(1, 2)
local glyphs, gw, gh = {}, 8, 0
if b1 == 0x36 and b2 == 0x04 then
local mode, size = data:byte(3, 4)
if not size or size == 0 then return nil, "bad PSF1 header" end
gh = size
local n = (mode % 4 >= 2) and 512 or 256
for i = 0, n - 1 do
local off = 4 + i * size
if off + size > #data then break end
glyphs[i] = data:sub(off + 1, off + size)
end
elseif b1 == 0x72 and b2 == 0xb5 then
local okU, headersize, flags, num, bpg, h, w =
pcall(string.unpack, "<I4I4I4I4I4I4I4", data, 5)
if not okU or not w or not h or w == 0 or h == 0 then
return nil, "bad PSF2 header"
end
gw, gh = w, h
for i = 0, num - 1 do
local off = headersize + i * bpg
if off + bpg > #data then break end
glyphs[i] = data:sub(off + 1, off + bpg)
end
else
return nil, "not a PSF file"
end
return {glyphs = glyphs, w = gw, h = gh, bpr = math.floor((gw + 7) / 8)}
end
local fontData = readBootData("/nc/font.psf")
if not fontData then throwError("missing /nc/font.psf on boot partition") end
local font = parsePSF(fontData)
fontData = nil
if not font then throwError("cannot parse /nc/font.psf") end
local okS, sw, sh = pcall(fsScreen.getSize)
if not okS or type(sw) ~= "number" then
throwError("screen has no usable display")
end
local SW, SH = sw, sh
local CW, CHH = font.w, font.h
local COLS = math.max(1, math.floor(SW / CW))
local ROWS = math.max(1, math.floor(SH / CHH))
local function split24(c)
c = math.floor(tonumber(c) or 0)
if c < 0 then c = 0 end
if c > 0xFFFFFF then c = 0xFFFFFF end
local r = math.floor(c / 65536)
local g = math.floor((c - r * 65536) / 256)
local b = c - r * 65536 - g * 256
return r, g, b
end
local glyphCache = {}
local function glyphBuffer(code, r, g, b)
local key = code * 16777216 + r * 65536 + g * 256 + b
local buf = glyphCache[key]
if buf then return buf end
local gl = font.glyphs[code] or font.glyphs[63]
local on = string.char(r, g, b, 255)
local off = string.char(0, 0, 0, 255)
local chunks = {}
local n = 0
for yy = 0, CHH - 1 do
for xx = 0, CW - 1 do
local byte = gl and gl:byte(yy * font.bpr + math.floor(xx / 8) + 1) or 0
n = n + 1
if (math.floor(byte / (2 ^ (7 - (xx % 8)))) % 2) == 1 then
chunks[n] = on
else
chunks[n] = off
end
end
end
buf = table.concat(chunks)
glyphCache[key] = buf
return buf
end
local function drawTextCell(px, py, code, fg)
local r, g, b = split24(fg)
local buf = glyphBuffer(code, r, g, b)
fsScreen.writeData(px, py, buf, CW)
end
local function fillCellBG(px, py, bg)
local r, g, b = split24(bg)
fsScreen.fill(px, py, px + CW - 1, py + CHH - 1, r, g, b, 255)
end
local function newTerm()
local t = {
cols = COLS, rows = ROWS,
cx = 1, cy = 1,
fg = 0xDBDBAA, bg = 0x000000,
cursor = true,
cells = {},
dirty = {},
lastCurX = nil, lastCurY = nil,
}
for y = 1, ROWS do
local row = {}
for x = 1, COLS do
row[x] = {ch = 32, fg = t.fg, bg = t.bg}
end
t.cells[y] = row
end
local function markRow(y)
t.dirty[y] = true
end
local function paintCell(x, y)
local cell = t.cells[y][x]
local px = (x - 1) * CW
local py = (y - 1) * CHH
fillCellBG(px, py, cell.bg)
if cell.ch ~= 32 then
drawTextCell(px, py, cell.ch, cell.fg)
end
end
local function hideCursor()
if t.lastCurX then
local x, y = t.lastCurX, t.lastCurY
t.lastCurX, t.lastCurY = nil, nil
if t.cells[y] and t.cells[y][x] then paintCell(x, y) end
end
end
local function scrollUp()
hideCursor()
if CHH < SH then
local data = fsScreen.readData(0, CHH, SW - 1, SH - 1)
fsScreen.writeData(0, 0, data, SW)
end
local top = table.remove(t.cells, 1)
for x = 1, COLS do
top[x].ch, top[x].fg, top[x].bg = 32, t.fg, t.bg
end
t.cells[ROWS] = top
local shifted = {}
for y in pairs(t.dirty) do
if y > 1 then shifted[y - 1] = true end
end
shifted[ROWS] = true
t.dirty = shifted
end
function t.present()
hideCursor()
for y in pairs(t.dirty) do
local row = t.cells[y]
if row then
for x = 1, COLS do paintCell(x, y) end
end
end
t.dirty = {}
if t.cursor then
local px = (t.cx - 1) * CW
local py = (t.cy - 1) * CHH
local r, g, b = split24(t.fg)
fsScreen.fill(px, py + CHH - 2, px + CW - 1, py + CHH - 1, r, g, b, 255)
t.lastCurX, t.lastCurY = t.cx, t.cy
end
fsScreen.draw()
end
function t.write(s)
hideCursor()
s = tostring(s)
for i = 1, #s do
local byte = s:byte(i)
if byte == 10 then
t.cx = 1
t.cy = t.cy + 1
elseif byte == 9 then
t.cx = t.cx + (4 - ((t.cx - 1) % 4))
elseif byte == 8 then
if t.cx > 1 then
t.cx = t.cx - 1
local cell = t.cells[t.cy][t.cx]
cell.ch, cell.fg, cell.bg = 32, t.fg, t.bg
markRow(t.cy)
end
else
if t.cx > COLS then
t.cx = 1
t.cy = t.cy + 1
end
if t.cy > ROWS then
scrollUp()
t.cy = ROWS
end
local cell = t.cells[t.cy][t.cx]
cell.ch, cell.fg, cell.bg = byte, t.fg, t.bg
markRow(t.cy)
t.cx = t.cx + 1
end
if t.cx > COLS + 1 then t.cx = COLS + 1 end
if t.cy > ROWS then
scrollUp()
t.cy = ROWS
end
end
t.present()
end
function t.clear()
for y = 1, ROWS do
local row = t.cells[y]
for x = 1, COLS do
row[x].ch, row[x].fg, row[x].bg = 32, t.fg, t.bg
end
end
t.dirty = {}
t.cx, t.cy = 1, 1
hideCursor()
local r, g, b = split24(t.bg)
fsScreen.fill(0, 0, SW - 1, SH - 1, r, g, b, 255)
t.present()
end
function t.getSize()
return t.cols, t.rows
end
function t.getCursor()
return t.cx, t.cy
end
function t.setCursor(x, y)
x, y = tonumber(x), tonumber(y)
if not x or not y then error("Invalid arg") end
if x < 1 then x = 1 end
if y < 1 then y = 1 end
if x > COLS then x = COLS end
if y > ROWS then y = ROWS end
hideCursor()
t.cx, t.cy = x, y
t.present()
end
function t.setFg(c) t.fg = math.floor(tonumber(c) or 0) end
function t.setBg(c) t.bg = math.floor(tonumber(c) or 0) end
function t.getFg() return t.fg end
function t.getBg() return t.bg end
function t.setCursorVisible(v)
t.cursor = v and true or false
t.present()
end
return t
end
local ncGfx = {
screenW = SW, screenH = SH,
cellW = CW, cellH = CHH,
cols = COLS, rows = ROWS,
newTerm = newTerm,
}
local con = newTerm()
con.setCursorVisible(false)
local function readBootFile(name)
local okH, h = pcall(fsFiles.open, BOOT_PART .. ":/nc/" .. name, "r", BOOT_DISK)
if not okH or not h then return "" end
local okR, data = pcall(h.read, "a")
pcall(h.close)
if not okR or type(data) ~= "string" then return "" end
return data
end
local function writeBootFile(name, text)
local okH, h = pcall(fsFiles.open, BOOT_PART .. ":/nc/" .. name, "w", BOOT_DISK)
if not okH or not h then return end
pcall(h.write, tostring(text))
pcall(h.flush)
pcall(h.close)
end
local eventQueue = {}
local function queueEvent(ev, ...)
if #eventQueue >= 512 then table.remove(eventQueue, 1) end
eventQueue[#eventQueue + 1] = {ev, ...}
end
local EFI = {
getEpochMs = function() return math.floor(fsChip.getUnixTime() * 1000) end,
getUptime = function() return math.floor((fsChip.getUnixTime() - bootUnix) * 1000) end,
date = function() return fmtDate(fsChip.getUnixTime()) end,
getMachineEvent = function()
if #eventQueue > 0 then
return table.unpack(table.remove(eventQueue, 1))
else
return nil
end
end,
getEEPROM = function() return readBootFile("eeprom.dat") end,
setEEPROM = function(_, text) writeBootFile("eeprom.dat", text) end,
getNvram = function() return readBootFile("nvram.dat") end,
setNvram = function(_, text) writeBootFile("nvram.dat", text) end,
beep = function() end,
architecture = "nc",
firmware = apis,
status = "running",
nc = ncGfx,
yield = function() coroutine.yield() end,
screenCtl = {
print = function(_, text) con.write(tostring(text) .. "\n") end,
printInline = function(_, text) con.write(tostring(text)) end,
clear = function() con.clear() end,
resetCursor = function() con.setCursor(1, 1) end,
setBackgroundColor = function(_, c) con.setBg(c) end,
setTextColor = function(_, c) con.setFg(c) end,
getBackgroundColor = function() return con.getBg() end,
getTextColor = function() return con.getFg() end,
enable = function() con.setCursorVisible(true) end,
disable = function() con.setCursorVisible(false) end,
},
}
local sliceInfo = setmetatable({}, {__mode = "k"})
function EFI.resumeWithTimeout(co, timeout, ...)
timeout = tonumber(timeout) or 0.05
local start = fsChip.getUnixTime()
local info = sliceInfo[co]
if info and info.result == "success" and (info.dur or 1) < 0.0002 then
local r = {coroutine.resume(co, ...)}
sliceInfo[co] = {result = (r[1] and "success" or "error"),
dur = fsChip.getUnixTime() - start}
if not r[1] then return "error", r[2] end
return "success", table.unpack(r, 2)
end
if not dbgSethook then
local r = {coroutine.resume(co, ...)}
sliceInfo[co] = {result = (r[1] and "success" or "error"),
dur = fsChip.getUnixTime() - start}
if not r[1] then return "error", r[2] end
return "success", table.unpack(r, 2)
end
local deadline = start + timeout
dbgSethook(co, function()
if coroutine.isyieldable() and fsChip.getUnixTime() >= deadline then
coroutine.yield("timeout")
end
end, "", 1000)
local ret = {coroutine.resume(co, ...)}
local stop = fsChip.getUnixTime()
if ret[1] and ret[2] == "timeout" then
sliceInfo[co] = {result = "timeout", dur = stop - start}
return "timeout"
elseif ret[1] == false then
sliceInfo[co] = {result = "error", dur = stop - start}
return "error", ret[2]
else
if dbgSethook then pcall(dbgSethook, co) end
sliceInfo[co] = {result = "success", dur = stop - start}
return "success", table.unpack(ret, 2)
end
end
local Kernel = load(getFile("/kernel.lua"), "@Kernel")
local initFsMod = load(getFile("/nc/initdisks"), "@Init_disks")
local initFs = load(getFile("/initfs"), "@InitFs")
if not Kernel then throwError("cannot parse kernel.lua") end
if not initFsMod then throwError("cannot parse nc/initdisks") end
if not initFs then throwError("cannot parse initfs") end
local disks = initFsMod(apis, BOOT_DISK, BOOT_PART)
local ifs = initFs()
local kernelCo = coroutine.create(function()
local okK, errK = xpcall(Kernel, debug.traceback, EFI)
EFI._kernelDone = true
if not okK then
EFI._kernelErr = errK
EFI.status = EFI.status == "reboot" and "reboot" or "error"
end
end)
EFI.initfs = ifs
EFI.disks = disks
local startTime = fsChip.getUnixTime()
EFI.screenCtl:print("HyperionOS/NC booted from " .. tostring(BOOT_DISK)
.. ":" .. BOOT_PART .. " in "
.. string.format("%.2f", startTime - bootUnix) .. "s")
local function pump()
local okU, q = pcall(fsEvent.getQueue, "User")
if okU and type(q) == "table" then
for i = 1, #q do
local e = q[i]
if type(e) == "table" then
local kind = e[1]
if kind == "keyPressed" then
local code, letter, mods = e[2], e[3], e[4]
queueEvent("keyPressed", 1, code, letter, mods)
if type(letter) == "string" and letter ~= "" then
queueEvent("keyTyped", 1, letter)
end
elseif kind == "keyReleased" then
queueEvent("keyReleased", 1, e[2], e[3], e[4])
elseif kind == "mouseClicked" or kind == "mouseReleased"
or kind == "mouseDragged" or kind == "mouseMoved"
or kind == "mouseScrolled" then
queueEvent(table.unpack(e))
else
queueEvent(table.unpack(e))
end
end
end
end
for _, label in ipairs({"System", "Network", "Peripheral",
"Compatibility", "Unlabeled"}) do
local okQ, qq = pcall(fsEvent.getQueue, label)
if okQ and type(qq) == "table" then
for i = 1, #qq do
local e = qq[i]
if type(e) == "table" then
queueEvent(table.unpack(e))
end
end
end
end
end
local function waitKey()
while true do
pump()
for i = 1, #eventQueue do
local e = eventQueue[i]
if e[1] == "keyPressed" or e[1] == "keyTyped" then
eventQueue = {}
return
end
end
eventQueue = {}
coroutine.yield()
end
end
while true do
pump()
local okR, errR = coroutine.resume(kernelCo)
if not okR then
con.setFg(0xFF0000)
con.write("Hyperion kernel fault:\n" .. tostring(errR)
.. "\nPress any key to shut down.")
con.setFg(0xDBDBAA)
waitKey()
fsChip.shutdown()
return
end
if coroutine.status(kernelCo) == "dead" then
if EFI.status == "reboot" then
fsChip.reboot()
else
if EFI._kernelErr then
con.setFg(0xFF0000)
con.write("Hyperion kernel error:\n"
.. tostring(EFI._kernelErr)
.. "\nPress any key to shut down.")
con.setFg(0xDBDBAA)
waitKey()
end
fsChip.shutdown()
end
return
end
coroutine.yield()
end
end, debug.traceback)
if not ok then
throwError(err)
end
@@ -0,0 +1,2 @@
return true
Binary file not shown.
@@ -0,0 +1,318 @@
--:Minify:--
-- HyperionOS NeetComputers initdisks.
-- Adapts the NeetComputers files API (disks x partitions) to the Hyperion
-- disk interface documented in docs/kernel/bootloaders/diskAPI.
--
-- Addresses look like "0:hyperion" (disk slot + partition name); the boot
-- partition is additionally aliased as "$".
--
-- NeetComputers file headers are snapshots: reads see the file as it was at
-- open time and writes only persist on flush/close (and always append). This
-- adapter keeps a Lua-side buffer per open handle so that read/seek/write
-- behave like regular POSIX files. Flush rewrites the whole file.
local args = {...}
local apis = args[1]
local bootDisk = args[2]
local bootPart = args[3]
local files = apis.files
local function fp(part, path)
if not path or path == "" then path = "/" end
if path:sub(1, 1) ~= "/" then path = "/" .. path end
return part .. ":" .. path
end
local function normParts(raw)
if type(raw) ~= "table" then return {} end
-- tolerate a doubly-wrapped list
if type(raw[1]) == "table" and raw[1].name == nil and #raw == 1 then
raw = raw[1]
end
local out = {}
for _, p in ipairs(raw) do
local name = type(p) == "table" and p.name or p
if type(name) == "string" and name ~= "" then
out[#out + 1] = name
end
end
return out
end
local function diskSlots()
local out = {}
local ok, raw = pcall(files.getDisks)
if ok and type(raw) == "table" then
for _, d in ipairs(raw) do
local slot = type(d) == "table" and (d.slot or d[1]) or d
if type(slot) == "number" then
out[#out + 1] = slot
end
end
end
if #out == 0 then out = {0} end
table.sort(out)
return out
end
local function partReadOnly(slot, part)
local ok, info = pcall(files.getPartition, part, slot)
if ok and type(info) == "table" then
return info.readonly == true
end
return false
end
local function createDisk(id, slot, part)
local readonly = partReadOnly(slot, part)
local disk = {
address = id,
isReadOnly = function() return readonly end
}
function disk:spaceUsed() return 0 end
function disk:spaceTotal() return 2 ^ 40 end
function disk:list(path)
local ok, r = pcall(files.getChildren, fp(part, path), slot)
if not ok or type(r) ~= "table" then return nil, "not directory" end
local out = {}
for _, n in ipairs(r) do
if type(n) == "string" then out[#out + 1] = n end
end
return out
end
function disk:fileExists(path)
local ok, r = pcall(files.exists, fp(part, path), slot)
if not (ok and r) then return false end
local ok2, d = pcall(files.isDir, fp(part, path), slot)
if ok2 and d then return false end
return true
end
function disk:directoryExists(path)
if not path or path == "" or path == "/" then return true end
local ok, r = pcall(files.isDir, fp(part, path), slot)
return ok and r == true
end
function disk:type(path)
local ok, r = pcall(files.exists, fp(part, path), slot)
if not (ok and r) then return nil end
local ok2, d = pcall(files.isDir, fp(part, path), slot)
if ok2 and d then return "directory" end
return "file"
end
function disk:makeDirectory(path)
local ok, r = pcall(files.makeDir, fp(part, path), slot)
if not ok then return nil, "cannot create directory" end
if r == false then return nil, "cannot create directory" end
return true
end
function disk:remove(path)
local ok, r = pcall(files.delete, fp(part, path), slot)
if not ok then return nil, "cannot delete" end
if r == false then return nil, "cannot delete" end
return true
end
function disk:setLabel(label) return true end
function disk:getLabel() return part end
function disk:attributes(path)
local isDir = self:directoryExists(path)
local size = 0
if not isDir then
local ok, h = pcall(files.open, fp(part, path), "r", slot)
if ok and h then
local ok2, data = pcall(h.read, "a")
pcall(h.close)
if ok2 and type(data) == "string" then size = #data end
end
end
return {
size = size,
isDir = isDir,
isReadOnly = readonly,
modified = 0,
created = 0
}
end
function disk:open(path, mode)
mode = mode or "r"
local wantWrite = mode ~= "r" and mode ~= "rb"
-- Snapshot the current content with a dedicated read handle.
-- ("a"/"ab" headers are not readable themselves, and every header
-- only appends, so all POSIX read/write/seek behavior below runs
-- on this Lua-side buffer; persist() rewrites the file on flush.)
local buf = ""
if mode ~= "w" and mode ~= "wb" then
local okR, hr = pcall(files.open, fp(part, path), "r", slot)
if okR and hr then
local okD, data = pcall(hr.read, "a")
pcall(hr.close)
if okD and type(data) == "string" then buf = data end
end
end
local ok, h = pcall(files.open, fp(part, path), mode, slot)
if not ok or not h then
return nil, "file not found or access denied"
end
-- The live header is only needed to prove the open mode is valid
-- (existence/creation); persist() reopens the file itself.
pcall(h.close)
local pos = 1
if mode == "w" or mode == "wb" then
buf = ""
else
pos = #buf + 1
if mode == "r" or mode == "rb" or mode == "r+" or mode == "rb+"
or mode == "r+b" or mode == "w+" or mode == "wb+"
or mode == "w+b" then
pos = 1
end
end
local closed = false
local handle = {}
function handle.read(n)
if closed then error("EBADF") end
if type(n) == "number" then
if n <= 0 then return nil end
if pos > #buf then return nil end
local chunk = buf:sub(pos, pos + n - 1)
pos = pos + #chunk
if chunk == "" then return nil end
return chunk
end
local fmt = n or "l"
if pos > #buf then return nil end
if fmt == "a" then
local chunk = buf:sub(pos)
pos = #buf + 1
return chunk
elseif fmt == "l" or fmt == "L" then
local s, e = buf:find("\n", pos, true)
if not s then
local chunk = buf:sub(pos)
pos = #buf + 1
return chunk
end
local chunk
if fmt == "l" then chunk = buf:sub(pos, s - 1)
else chunk = buf:sub(pos, s) end
pos = s + 1
return chunk
else
error("EINVAL")
end
end
function handle.readAll()
if closed then error("EBADF") end
local chunk = buf:sub(pos)
pos = #buf + 1
return chunk
end
function handle.write(data)
if closed then error("EBADF") end
if not wantWrite then error("EACCES") end
data = tostring(data)
local before = buf:sub(1, pos - 1)
local after = buf:sub(pos + #data)
buf = before .. data .. after
pos = pos + #data
return true
end
function handle.seek(whence, offset)
if closed then error("EBADF") end
whence = whence or "cur"
offset = offset or 0
local base
if whence == "set" then base = 1
elseif whence == "cur" then base = pos
elseif whence == "end" then base = #buf + 1
else error("EINVAL") end
local np = base + offset
if whence == "end" and offset > 0 then error("EINVAL") end
if np < 1 then error("EINVAL") end
if np > #buf + 1 then error("EINVAL") end
pos = np
return pos - 1
end
local function persist()
if not wantWrite then return true end
local ok2, h2 = pcall(files.open, fp(part, path), "w", slot)
if not ok2 or not h2 then return nil, "flush failed" end
if #buf > 0 then
local ok3, err = pcall(h2.write, buf)
if not ok3 then pcall(h2.close) return nil, err end
end
local ok4, err = pcall(h2.flush)
pcall(h2.close)
if not ok4 then return nil, err end
return true
end
function handle.flush()
if closed then error("EBADF") end
local ok2, err = persist()
if not ok2 then error(err or "EIO") end
return true
end
function handle.close()
if closed then return true end
closed = true
if wantWrite then pcall(persist) end
buf = ""
return true
end
return handle
end
return disk
end
local internal = {}
local disks = {}
internal["$"] = createDisk("$", bootDisk, bootPart)
local function refresh()
disks = {}
for _, slot in ipairs(diskSlots()) do
local ok, raw = pcall(files.getPartitions, slot)
if ok and type(raw) == "table" then
for _, part in ipairs(normParts(raw)) do
if not (slot == bootDisk and part == bootPart) then
local addr = tostring(slot) .. ":" .. part
disks[addr] = createDisk(addr, slot, part)
end
end
end
end
end
local function iter()
refresh()
local combined = {}
for id, obj in pairs(internal) do combined[id] = obj end
for id, obj in pairs(disks) do combined[id] = obj end
return pairs(combined)
end
return {refresh = refresh, list = iter}
@@ -0,0 +1,11 @@
--:Minify:--
local kernel=...
if kernel.arch~="nc" then
kernel.deny("neetcomputers/01_devices.kmod")
kernel.deny("neetcomputers/13_devraw.kmod")
kernel.deny("neetcomputers/22_http.kmod")
kernel.deny("neetcomputers/25_tty.kmod")
kernel.deny("neetcomputers/26_keyboards.kmod")
kernel.deny("neetcomputers/30_daemon.kmod")
kernel.deny("neetcomputers/36_scheduler.kmod")
end
@@ -0,0 +1,19 @@
--:Minify:--
local kernel=...
kernel.nc={}
kernel.nc.io=kernel.apis.io
kernel.nc.chip=kernel.apis.chip
kernel.nc.event=kernel.apis.event
kernel.nc.files=kernel.apis.files
kernel.log("Installed peripherals:")
local ok, peripherals = pcall(kernel.nc.io.getPeripherals)
if ok and type(peripherals)=="table" then
for _, id in ipairs(peripherals) do
local okT, typ = pcall(kernel.nc.io.getType, id)
if not okT then typ = "unknown" end
kernel.log(" "..tostring(id).." : "..tostring(typ))
end
else
kernel.log(" (none)")
end
@@ -0,0 +1,28 @@
--:Minify:--
local kernel=...
local io=kernel.nc.io
local function wrap(id)
return function(op, mode)
if op=="type" then
return "device"
elseif op=="open" then
if kernel.uid~=0 then error("EACCES") end
return io.wrapPeripheral(id)
end
end
end
local ok, peripherals = pcall(io.getPeripherals)
if ok and type(peripherals)=="table" then
for _, id in ipairs(peripherals) do
local obj=wrap(id)
kernel.devfs.data["raw"][tostring(id)]=obj
local okT, typ = pcall(io.getType, id)
typ = (okT and type(typ)=="string") and typ or "unknown"
local typefolder=kernel.devfs.data["raw"]["by-type"][typ]
if not typefolder then typefolder={} end
typefolder[tostring(#table.keys(typefolder)+1)] = obj
kernel.devfs.data["raw"]["by-type"][typ]=typefolder
end
end
@@ -0,0 +1,133 @@
--:Minify:--
-- NeetComputers TTY driver: a cell-buffered text terminal rendered through
-- the bootloader's shared framebuffer interface (EFI.nc.newTerm).
local kernel = ...
local ncgfx = kernel.EFI.nc
if not ncgfx or not ncgfx.newTerm then
kernel.panic("neetcomputers/25_tty.kmod: EFI.nc framebuffer missing")
end
local term = ncgfx.newTerm()
-- Interactive programs (hysh, lua REPL, micro) draw their own inverted
-- block cursor; the terminal's hardware underline would sit next to it
-- as a stray extra cursor, so keep it off.
term.setCursorVisible(false)
kernel.nc.term = term
kernel.log("initialized nc framebuffer tty "
.. tostring(ncgfx.screenW) .. "x" .. tostring(ncgfx.screenH)
.. " (" .. tostring(term.cols) .. "x" .. tostring(term.rows) .. " chars)")
kernel.devfs.data["tty"]["1"] = function(op, mode)
if op == "type" then
return "Terminal"
elseif op == "open" then
local h = {
read = function(amount) end,
write = function(content)
term.write(tostring(content))
end,
size = function()
return term.getSize()
end,
clear = function()
term.clear()
end,
gpos = function()
return term.getCursor()
end,
spos = function(x, y)
if not tonumber(x) or not tonumber(y) then error("Invailid arg") end
term.setCursor(x, y)
end,
sfgc = function(c)
term.setFg(c)
end,
sbgc = function(c)
term.setBg(c)
end,
gfgc = function()
return term.getFg()
end,
gbgc = function()
return term.getBg()
end,
isvirt = function()
return false
end,
gplt = function()
return {
0x000000, 0x000040, 0x000080, 0x0000C0, 0x0000FF,
0x002400, 0x002440, 0x002480, 0x0024C0, 0x0024FF,
0x004900, 0x004940, 0x004980, 0x0049C0, 0x0049FF,
0x006D00, 0x006D40, 0x006D80, 0x006DC0, 0x006DFF,
0x009200, 0x009240, 0x009280, 0x0092C0, 0x0092FF,
0x00B600, 0x00B640, 0x00B680, 0x00B6C0, 0x00B6FF,
0x00DB00, 0x00DB40, 0x00DB80, 0x00DBC0, 0x00DBFF,
0x00FF00, 0x00FF40, 0x00FF80, 0x00FFC0, 0x00FFFF,
0x330000, 0x330040, 0x330080, 0x3300C0, 0x3300FF,
0x332400, 0x332440, 0x332480, 0x3324C0, 0x3324FF,
0x334900, 0x334940, 0x334980, 0x3349C0, 0x3349FF,
0x336D00, 0x336D40, 0x336D80, 0x336DC0, 0x336DFF,
0x339200, 0x339240, 0x339280, 0x3392C0, 0x3392FF,
0x33B600, 0x33B640, 0x33B680, 0x33B6C0, 0x33B6FF,
0x33DB00, 0x33DB40, 0x33DB80, 0x33DBC0, 0x33DBFF,
0x33FF00, 0x33FF40, 0x33FF80, 0x33FFC0, 0x33FFFF,
0x660000, 0x660040, 0x660080, 0x6600C0, 0x6600FF,
0x662400, 0x662440, 0x662480, 0x6624C0, 0x6624FF,
0x664900, 0x664940, 0x664980, 0x6649C0, 0x6649FF,
0x666D00, 0x666D40, 0x666D80, 0x666DC0, 0x666DFF,
0x669200, 0x669240, 0x669280, 0x6692C0, 0x6692FF,
0x66B600, 0x66B640, 0x66B680, 0x66B6C0, 0x66B6FF,
0x66DB00, 0x66DB40, 0x66DB80, 0x66DBC0, 0x66DBFF,
0x66FF00, 0x66FF40, 0x66FF80, 0x66FFC0, 0x66FFFF,
0x990000, 0x990040, 0x990080, 0x9900C0, 0x9900FF,
0x992400, 0x992440, 0x992480, 0x9924C0, 0x9924FF,
0x994900, 0x994940, 0x994980, 0x9949C0, 0x9949FF,
0x996D00, 0x996D40, 0x996D80, 0x996DC0, 0x996DFF,
0x999200, 0x999240, 0x999280, 0x9992C0, 0x9992FF,
0x99B600, 0x99B640, 0x99B680, 0x99B6C0, 0x99B6FF,
0x99DB00, 0x99DB40, 0x99DB80, 0x99DBC0, 0x99DBFF,
0x99FF00, 0x99FF40, 0x99FF80, 0x99FFC0, 0x99FFFF,
0xCC0000, 0xCC0040, 0xCC0080, 0xCC00C0, 0xCC00FF,
0xCC2400, 0xCC2440, 0xCC2480, 0xCC24C0, 0xCC24FF,
0xCC4900, 0xCC4940, 0xCC4980, 0xCC49C0, 0xCC49FF,
0xCC6D00, 0xCC6D40, 0xCC6D80, 0xCC6DC0, 0xCC6DFF,
0xCC9200, 0xCC9240, 0xCC9280, 0xCC92C0, 0xCC92FF,
0xCCB600, 0xCCB640, 0xCCB680, 0xCCB6C0, 0xCCB6FF,
0xCCDB00, 0xCCDB40, 0xCCDB80, 0xCCDBC0, 0xCCDBFF,
0xCCFF00, 0xCCFF40, 0xCCFF80, 0xCCFFC0, 0xCCFFFF,
0xFF0000, 0xFF0040, 0xFF0080, 0xFF00C0, 0xFF00FF,
0xFF2400, 0xFF2440, 0xFF2480, 0xFF24C0, 0xFF24FF,
0xFF4900, 0xFF4940, 0xFF4980, 0xFF49C0, 0xFF49FF,
0xFF6D00, 0xFF6D40, 0xFF6D80, 0xFF6DC0, 0xFF6DFF,
0xFF9200, 0xFF9240, 0xFF9280, 0xFF92C0, 0xFF92FF,
0xFFB600, 0xFFB640, 0xFFB680, 0xFFB6C0, 0xFFB6FF,
0xFFDB00, 0xFFDB40, 0xFFDB80, 0xFFDBC0, 0xFFDBFF,
0xFFFF00, 0xFFFF40, 0xFFFF80, 0xFFFFC0, 0xFFFFFF,
0x000000, 0x0F0F0F, 0x1E1E1E, 0x2D2D2D,
0x3C3C3C, 0x4B4B4B, 0x5A5A5A, 0x696969,
0x787878, 0x878787, 0x969696, 0xA5A5A5,
0xB4B4B4, 0xC3C3C3, 0xD2D2D2, 0xE1E1E1
}
end,
gfx = function()
return false
end
}
if mode == "rw" then
return h
elseif mode == "r" then
h["write"] = nil
return h
elseif mode == "w" then
h["read"] = nil
return h
end
end
end
@@ -0,0 +1,129 @@
--:Minify:--
-- NeetComputers keyboard driver. The bootloader delivers User-queue key
-- events as ("keyPressed", 1, code, letter, mods) /
-- ("keyTyped", 1, letter) / ("keyReleased", 1, code, ...); the ncdaemon
-- task (30_daemon.kmod) feeds the fifo below.
local kernel=...
kernel.nc.keyboards={}
local kbs=kernel.nc.keyboards
local keyboard = {}
-- NeetComputers key codes: printable keys are ASCII, the rest follows the
-- emulator/mod keybind tables (Return=13, arrows 128-131, ...).
keyboard.keys = {
back = 8,
delete = 127,
down = 131,
enter = 13,
home = 158,
lcontrol = 132,
left = 128,
lmenu = 133,
lshift = 14,
pageDown = 161,
pageUp = 160,
rcontrol = 132,
right = 129,
rmenu = 133,
rshift = 14,
space = 32,
tab = 9,
up = 130,
["end"] = 159,
numpadenter = 13,
}
kernel.nc.keys=keyboard.keys
for i=0, 255 do
kernel.nc.keys[string.char(i)]=i
end
-------------------------------------------------------------------------------
function keyboard.isAltDown(addr)
return kbs[addr] and kbs[addr].alt or false
end
function keyboard.isControl(char)
return type(char) == "number" and (char < 0x20 or (char >= 0x7F and char <= 0x9F))
end
function keyboard.isControlDown(addr)
return kbs[addr] and kbs[addr].ctrl or false
end
function keyboard.isKeyDown(addr,charOrCode)
if not kbs[addr] then return false end
if type(charOrCode) == "string" then
return kbs[addr].pressedChars[utf8 and utf8.codepoint(charOrCode) or charOrCode:byte()]
elseif type(charOrCode) == "number" then
return kbs[addr].pressedCodes[charOrCode]
end
end
function keyboard.isShiftDown(addr)
return kbs[addr] and kbs[addr].shift or false
end
kernel.nc.keyboard=keyboard
local function serializeBool(bool)
if bool then
return "T"
else
return "F"
end
end
kbs["1"]={pressedChars={}, pressedCodes={}, events=kernel.newFifo(),
ctrl=false, alt=false, shift=false}
kernel.devfs.data["input"]["keyboard1"]=function(op,mode)
if op=="type" then
return "Keyboard"
elseif op=="open" then
local fifo=kernel.nc.keyboards["1"].events
local h = {
read=function(amount)
amount = amount or 1
-- Drain whatever is already queued first.
local rv=""
for i=1, amount do
local event = {fifo.pop()}
if event[1] then
rv=rv..event[1]
else
break
end
end
if rv~="" then return rv end
-- Nothing queued: block the task until the ncdaemon
-- feeds input instead of busy-spinning syscalls.
local task=kernel.currentTask
task.status="D"
task.io=function()
local event = {fifo.pop()}
if event[1] then return event[1] end
end
return nil
end,
write=function(content)
end,
gctrl=function()
local kb=kernel.nc.keyboards["1"]
return serializeBool(kb.ctrl)..";"..serializeBool(kb.alt)
end,
isKeyDown=function(char)
return keyboard.isKeyDown("1",char)
end
}
if mode=="rw" then
return h
elseif mode=="r" then
h["write"]=nil
return h
elseif mode=="w" then
h["read"]=nil
return h
end
end
end
@@ -0,0 +1,106 @@
--:Minify:--
-- NeetComputers input daemon. Consumes kernel machine events produced by
-- the bootloader event pump and feeds /dev/input/keyboard1. Ctrl+C sends
-- SIGINT to all tasks, mirroring the OC/CCT daemons.
local kernel=...
local NCTRACEBACK = debug.traceback
local keys=kernel.nc.keys
kernel.nc.eventhooks=kernel.nc.eventhooks or {}
kernel.processes.ncdaemon = function()
local timeout = false
kernel.log("NC daemon started")
local function isCtrl(mods) return (math.floor((tonumber(mods) or 0) / 2) % 2) == 1 end
local specialKeyMap = {
[keys.up] = "\27[A",
[keys.down] = "\27[B",
[keys.right] = "\27[C",
[keys.left] = "\27[D",
[keys.home] = "\27[H",
[keys["end"]] = "\27[F",
[keys.pageUp] = "\27[5~",
[keys.pageDown] = "\27[6~",
[keys.delete] = "\27[3~",
[keys.enter] = "\n",
[keys.back] = "\b",
[keys.tab] = "\t",
}
while true do
local event = {kernel.EFI.getMachineEvent()}
if event[1] then
local eventType = event[1]
local kb = kernel.nc.keyboards["1"]
if eventType == "keyPressed" then
local code, letter, mods = event[3], event[4], event[5]
kb.pressedCodes[code] = true
if type(letter) == "string" and #letter == 1 then
kb.pressedChars[letter:byte()] = true
end
if isCtrl(mods) then
kb.ctrl = true
local ch = nil
if type(letter) == "string" and #letter == 1 then
ch = letter:lower():byte()
elseif type(code) == "number" and code >= 64 and code <= 95 then
ch = code
end
if ch and ch >= 97 and ch <= 122 then
local byte = ch - 96
if byte == 3 then
for _, task in ipairs(syscall.getTasks()) do
syscall.sigsend(task, 1)
end
else
kb.events.push(string.char(byte))
end
end
else
local special = specialKeyMap[code]
if special then
kb.events.push(special)
end
end
elseif eventType == "keyReleased" then
local code = event[3]
kb.pressedCodes[code] = nil
if type(event[4]) == "string" and #event[4] == 1 then
kb.pressedChars[event[4]:byte()] = nil
end
if not isCtrl(event[5]) then kb.ctrl = false end
elseif eventType == "keyTyped" then
if event[3] then kb.events.push(event[3]) end
else
if kernel.nc.eventhooks[eventType] then
local ok,err = xpcall(kernel.nc.eventhooks[eventType], NCTRACEBACK, table.unpack(event))
if not ok then
kernel.log("Error on eventhook "..eventType.."\n"..err)
end
end
end
timeout = false
else
timeout = true
end
if timeout then
sleep(0.05)
end
end
end
kernel.log("NC daemon queued for execution")
@@ -0,0 +1,187 @@
--:Minify:--
-- NeetComputers scheduler (adaptive timeslice + optional preemption
-- via EFI.resumeWithTimeout; same design as the CCT/OC schedulers).
local kernel=...
-- Cache the real traceback: 48_dbg replaces _G.debug with a restricted
-- table, and re-reading the global in this hot loop flakes on YSLua.
local NCTRACEBACK = debug.traceback
local alpha = 0.85
local C_target = 0.01
local Tmin = 0.0005
local Tmax = 0.5
local lambda_budget = 0.08
local lambda_clamp = 0.03
local lambda_var = 0.02
local k_min = 0.5
local k_max = 0.5
local B = 0.01
function kernel.main()
kernel.log("Starting main loop...")
kernel.saveLog()
local stopLog=5
local logTasks=100
-- Host-tick budget: the bootloader resumes the kernel once per host
-- frame and every EFI:yield ends that resume, so one syscall-step per
-- frame makes interactive use crawl (roughly a frame per syscall).
-- Run a bounded burst of passes per frame instead: a burst where no
-- task ran means everything is parked, so yield at once. The step cap
-- plus preemption keep a runaway task from tripping the host watchdog.
local burstSteps = 0
local maxBurstSteps = 64
while not kernel.exitMain do
if kernel.config.logTasks then
if logTasks<0 then
kernel.log("Active Tasks:")
for i,v in pairs(kernel.tasks) do
kernel.log(v.name.." : "..v.status.." : "..tostring(v.pid).." : "..tostring(v.exit))
end
kernel.log("[END BLOCK]")
logTasks=100
end
logTasks=logTasks-1
end
local N = 0
local Tmin_hit = 0
local Tmax_hit = 0
local totalTaskTime = 0
local taskTimes = {}
for id,hook in ipairs(kernel.mainHooks) do
local ok,err = xpcall(hook, NCTRACEBACK)
if not ok then
kernel.log("[MAIN HOOK ERR]: "..err, "ERROR", 0xFF0000)
kernel.mainHooks[id]=nil
end
end
for pid, task in pairs(kernel.tasks) do
if kernel.exitMain then break end
for _,list in ipairs(kernel.perTaskHooks) do
for id,hook in ipairs(list) do
local ok,err = xpcall(hook, NCTRACEBACK, task, pid)
if not ok then
kernel.log("[TASK HOOK ERR]: "..err, "ERROR", 0xFF0000)
list[id]=nil
end
end
end
if task.status == "R" then
N = N + 1
task.timeSlice = math.min(Tmax, math.max(Tmin, B / (N ^ alpha)))
if task.status == "R" then
local startTime = kernel.EFI:getEpochMs()
local ret
if stopLog > 0 then
kernel.log("Running task " .. tostring(task.pid) .. " (" .. task.name .. ") with time slice " .. string.format("%.3f", task.timeSlice) .. "s", "DBUG", 0x00FFFF)
end
if kernel.config.preempt then
if not task.debugger then
ret = { kernel.EFI.resumeWithTimeout(task.coro, task.timeSlice, table.unpack(task.syscallReturn)) }
else
ret = { coroutine.resume(task.coro, table.unpack(task.syscallReturn)) }
end
else
ret = { coroutine.resume(task.coro, table.unpack(task.syscallReturn)) }
end
local elapsed = kernel.EFI:getEpochMs() - startTime
task.lastTime = elapsed
task.totalTime = (task.totalTime or 0) + elapsed
task.numRuns = (task.numRuns or 0) + 1
taskTimes[#taskTimes+1] = elapsed
totalTaskTime = totalTaskTime + elapsed
if elapsed <= Tmin then Tmin_hit = Tmin_hit + 1 end
if elapsed >= Tmax then Tmax_hit = Tmax_hit + 1 end
if ret[1] == "error" or ret[1] == false then
kernel.log("processHandlerException: " .. tostring(ret[2]), "ERROR", 0xFF0000)
task.status = "Z"
task.exit = "processHandlerException: " .. tostring(ret[2])
elseif ret[1] == "timeout" then
task.ivs = task.ivs + 1
task.syscallReturn = {}
elseif ret[1] == "success" or ret[1] == true then
task.vs = task.vs + 1
if ret[2] == "syscall" then
local scname = ret[3]
if kernel.syscalls[scname] then
if kernel.config.debugSyscalls then
kernel.log("Task " .. task.pid .. " syscall: " .. scname, "DBUG", 0x00FFFF)
for i = 4, #ret do
kernel.log(" inval[" .. (i-3) .. "] = " .. tostring(ret[i]), "DBUG", 0x00FFFF)
end
end
local sysret = { xpcall(kernel.syscalls[scname], NCTRACEBACK, table.unpack(ret, 4)) }
if kernel.config.debugSyscalls then
if not sysret[1] then
kernel.log("Task " .. task.pid .. " syscall " .. scname .. " failed: " .. tostring(sysret[2]), "ERROR", 0xFF0000)
else
kernel.log("Task " .. task.pid .. " syscall " .. scname .. " ok, " .. (#sysret-1) .. " retvals", "DBUG", 0x00FFFF)
for i = 2, #sysret do
local v = type(sysret[i]) == "table" and table.serialize(sysret[i]) or tostring(sysret[i])
kernel.log(" retval[" .. (i-1) .. "] = " .. v, "DBUG", 0x00FFFF)
end
end
end
if not sysret[1] then
task.syscallReturn = { false, sysret[2] }
else
task.syscallReturn = { true, table.unpack(sysret, 2) }
end
else
task.syscallReturn = { false, "Unknown syscall: " .. tostring(scname) }
end
end
end
end
end
-- No yield per task anymore: passes run back-to-back in one
-- host tick (see burst budget below). Yielding here cost a
-- full frame per task-step.
end
burstSteps = burstSteps + N
if N == 0 or burstSteps >= maxBurstSteps then
burstSteps = 0
-- Yield to the host once per burst (even when no task ran):
-- without this an idle system spins without voluntary yields
-- and trips the host watchdog.
kernel.EFI:yield()
end
local T_prev_avg = (N > 0) and (totalTaskTime / N) or 0
local T_prev_var = 0
for _, t in ipairs(taskTimes) do
T_prev_var = T_prev_var + (t - T_prev_avg) ^ 2
end
if N > 0 then T_prev_var = T_prev_var / N end
if N > 0 then
local f_clamp = k_min * (Tmin_hit / N) - k_max * (Tmax_hit / N)
local B_budget = (C_target * (N ^ (alpha - 1))) / math.max(T_prev_avg, 1e-8)
B = B + lambda_budget * (B_budget - B) + lambda_clamp * f_clamp - lambda_var * T_prev_var
end
kernel.hpv.reapDeadTasks()
if stopLog > 0 then
kernel.log("Executed " .. N .. " tasks, avg time: " .. string.format("%.2f", T_prev_avg) .. "ms, var: " .. string.format("%.2f", T_prev_var) .. ", B: " .. string.format("%.5f", B))
stopLog = stopLog - 1
kernel.saveLog()
end
end
kernel.log("Exited main")
kernel.saveLog()
end
+1
View File
@@ -0,0 +1 @@
firmware for NeetComputers
+1
View File
@@ -0,0 +1 @@
1.0.0
+4
View File
@@ -0,0 +1,4 @@
Hyperion
Astronand
Xtimhedae
Spsf
-41
View File
@@ -1,41 +0,0 @@
local lua = {
coroutine = true,
debug = true,
_HOST = true,
_VERSION = true,
assert = true,
collectgarbage = true,
error = true,
gcinfo = true,
getfenv = 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,
setfenv = true,
setmetatable = true,
string = true,
table = true,
tonumber = true,
tostring = true,
type = true,
xpcall = true,
_G=true
}
local apis={}
for i,v in pairs(_G) do
if not lua[i] or lua[i]==nil then
apis[i]=v
_G[i]=nil
end
end
-18
View File
@@ -1,18 +0,0 @@
checkArg=nil
local oldcomputer=computer
_G.computer=nil
local os=os
_G.os=nil
function component.wrap(address)
local methods=oldcomponent.methods(address)
local object={}
for _,method in ipairs(methods) do
object[method]=function(_,...)
return oldcomponent.invoke(address,method,...)
end
end
return object
end
local
@@ -1 +0,0 @@
local fs={}
@@ -0,0 +1,122 @@
---@diagnostic disable-next-line: undefined-global
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 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
@@ -0,0 +1,68 @@
local init
do
local component_invoke = component.invoke
local function boot_invoke(address, method, ...)
local result = table.pack(pcall(component_invoke, address, method, ...))
if not result[1] then
return nil, result[2]
else
return table.unpack(result, 2, result.n)
end
end
-- backwards compatibility, may remove later
local eeprom = component.list("eeprom")()
computer.getBootAddress = function()
return boot_invoke(eeprom, "getData")
end
computer.setBootAddress = function(address)
return boot_invoke(eeprom, "setData", address)
end
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
local data, reason = boot_invoke(address, "read", handle, math.maxinteger or math.huge)
if not data and reason then
return nil, reason
end
buffer = buffer .. (data or "")
until not data
boot_invoke(address, "close", handle)
return load(buffer, "=init")
end
local reason
if computer.getBootAddress() then
init, reason = tryLoadFrom(computer.getBootAddress())
end
if not init then
computer.setBootAddress()
for address in component.list("filesystem") do
init, reason = tryLoadFrom(address)
if init then
computer.setBootAddress(address)
break
end
end
end
if not init then
error("no bootable medium found" .. (reason and (": " .. tostring(reason)) or ""), 0)
end
end
local ok, err = xpcall(init,debug.traceback)
if not ok then
error(err)
else
return err
end
@@ -0,0 +1,225 @@
local args = {...}
local apis = args[1]
local bootdrive = args[2]
local bootaddr = args[3]
local disks = {}
local internal = {}
local function normalize(path)
if type(path) ~= "string" then
return path
end
-- Preserve root directory.
if path == "/" then
return "/"
end
-- Remove trailing slashes.
path = path:gsub("/+$", "")
return path == "" and "/" or path
end
local function createDisk(id, hw)
local disk = {
address = id,
isReadOnly = function()
return hw.isReadOnly()
end
}
function disk:spaceUsed()
return hw.spaceUsed()
end
function disk:spaceTotal()
return hw.spaceTotal()
end
function disk:list(path)
path = normalize(path)
if not hw.exists(path) or not hw.isDirectory(path) then
return nil, "not directory"
end
local ret = {}
for i, v in ipairs(hw.list(path)) do
ret[i] = normalize(v)
end
return ret
end
function disk:fileExists(path)
path = normalize(path)
return hw.exists(path) and not hw.isDirectory(path)
end
function disk:directoryExists(path)
path = normalize(path)
return hw.exists(path) and hw.isDirectory(path)
end
function disk:type(path)
path = normalize(path)
if not hw.exists(path) then
return nil
elseif hw.isDirectory(path) then
return "directory"
else
return "file"
end
end
function disk:makeDirectory(path)
path = normalize(path)
return hw.makeDirectory(path)
end
function disk:remove(path)
path = normalize(path)
if hw.exists(path) then
return hw.remove(path)
end
end
function disk:setLabel(label)
return hw.setLabel(label)
end
function disk:getLabel()
return hw.getLabel()
end
function disk:attributes(path)
path = normalize(path)
return {
size = hw.size(path),
isDir = hw.isDirectory(path),
isReadOnly = hw.isReadOnly(),
modified = hw.lastModified(path),
created = hw.lastModified(path)
}
end
function disk:open(path, mode)
path = normalize(path)
local fd = hw.open(path, mode)
if not fd then
local dir = path:match("^(.*)/[^/]+$")
if dir and not hw.exists(dir) then
local ok, err = hw.makeDirectory(dir)
if not ok then
return nil, err or "could not create parent directory"
end
end
fd = hw.open(path, mode)
if not fd then
return nil, "file not found or access denied"
end
end
return {
read = function(num)
return hw.read(fd, num)
end,
readAll = function()
local data = {}
while true do
local chunk, err = hw.read(fd, 2048)
if chunk == nil then
if err then
return nil, err
end
break
end
if #chunk == 0 then
break
end
data[#data + 1] = chunk
end
return table.concat(data)
end,
write = function(data)
return hw.write(fd, data)
end,
seek = function(whence, offset)
return hw.seek(fd, whence, offset)
end,
flush = function()
if fd then
hw.close(fd)
fd = hw.open(path, mode)
end
end,
close = function()
if fd then
hw.close(fd)
fd = nil
end
end
}
end
return disk
end
internal["$"] = createDisk("$", bootdrive)
local function refresh()
disks = {}
for addr in apis.component.list("filesystem") do
if addr ~= bootaddr then
disks[addr] = createDisk(
addr,
apis.component.proxy(addr)
)
end
end
end
local function iter()
refresh()
local combined = {}
for id, obj in pairs(internal) do
combined[id] = obj
end
for id, obj in pairs(disks) do
combined[id] = obj
end
return pairs(combined)
end
return {
refresh = refresh,
list = iter
}
@@ -0,0 +1,11 @@
--:Minify:--
local kernel=...
if kernel.arch~="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
@@ -0,0 +1,15 @@
--:Minify:--
local kernel=...
kernel.oc={}
kernel.oc.component=kernel.apis.component
kernel.oc.computer=kernel.apis.computer
kernel.log("Installed components:")
for addr, typ in kernel.oc.component.list() do
local dev=kernel.oc.component.proxy(addr)
local tier=""
if dev.getTier then
tier=dev.getTier()
end
kernel.log(" "..addr.." : "..typ..tier)
end
@@ -0,0 +1,23 @@
--:Minify:--
local kernel=...
local component=kernel.oc.component
local function wrap(p)
return function(op, mode)
if op=="type" then
return "device"
elseif op=="open" then
if kernel.uid~=0 then error("EACCES") end
return component.proxy(p)
end
end
end
for addr, typ in kernel.oc.component.list() do
local obj=wrap(addr)
kernel.devfs.data["raw"][addr]=obj
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
@@ -0,0 +1,442 @@
--:Minify:--
local kernel = ...
local component = kernel.oc and kernel.oc.component
local internetAddress
for address in component.list("internet") do
internetAddress = address
break
end
if not internetAddress then
if kernel.log then
kernel.log("NET: No Internet component available")
end
return
end
local internet = component.proxy(internetAddress)
local tcpEnabled = false
local httpEnabled = false
if internet.isTcpEnabled then
local ok, result = pcall(internet.isTcpEnabled)
tcpEnabled = ok and result == true
end
if internet.isHttpEnabled then
local ok, result = pcall(internet.isHttpEnabled)
httpEnabled = ok and result == true
end
local function closeHandle(handle)
if handle and handle.close then
pcall(handle.close)
end
end
local function parseRawRequest(raw, address)
local headerEnd = raw:find("\r\n\r\n", 1, true)
local headerPart
local body = ""
if headerEnd then
headerPart = raw:sub(1, headerEnd - 1)
body = raw:sub(headerEnd + 4)
else
headerPart = raw
end
local lines = {}
for line in headerPart:gmatch("[^\r\n]+") do
lines[#lines + 1] = line
end
if #lines == 0 then
return nil, "EINVAL"
end
local method, path, ver =
lines[1]:match("^(%S+)%s+(%S+)%s+(%S+)$")
if not method then
return nil, "EINVAL"
end
if path:sub(1, 1) ~= "/" then
return nil, "EINVAL"
end
local headers = {}
for i = 2, #lines do
local k, v = lines[i]:match("^([^:]+):%s*(.*)$")
if k then
headers[k] = v
end
end
local url = address .. path
return {
url = url,
method = method,
headers = headers,
body = body
}, url
end
local function buildHTTPResponse(req)
if req.method ~= "GET" and req.method ~= "POST" then
return nil, "EOPNOTSUPP"
end
local postData
if req.method == "POST" then
postData = req.body or ""
end
local ok, response = pcall(
internet.request,
req.url,
postData,
req.headers
)
if not ok or not response then
return nil, tostring(response or "ECONN")
end
local connected, connectResult = pcall(
response.finishConnect
)
if not connected or connectResult == false then
closeHandle(response)
return nil, tostring(connectResult or "ECONN")
end
local code = 200
local msg = "OK"
local headers = {}
if response.response then
local responseOK, c, m, h = pcall(response.response)
if responseOK then
code = c or code
msg = m or msg
headers = h or headers
end
end
local chunks = {}
while true do
local readOK, chunk = pcall(response.read, 8192)
if not readOK then
closeHandle(response)
return nil, tostring(chunk)
end
if not chunk or #chunk == 0 then
break
end
chunks[#chunks + 1] = chunk
end
closeHandle(response)
local out = {
"HTTP/1.1 " .. tostring(code) .. " " .. tostring(msg)
}
for k, v in pairs(headers) do
if type(v) == "table" then
for i = 1, #v do
out[#out + 1] = k .. ": " .. tostring(v[i])
end
else
out[#out + 1] = k .. ": " .. tostring(v)
end
end
out[#out + 1] = ""
out[#out + 1] = table.concat(chunks)
return table.concat(out, "\r\n")
end
local function closeFile(socket)
if socket.file then
pcall(socket.file.close)
socket.file = nil
end
end
local httpHandler = {}
function httpHandler.connect(fd, address)
local fdo = kernel.currentTask.fd[fd]
if not fdo then
return nil, "EBADF"
end
fdo.socket = fdo.socket or {}
local socket = fdo.socket
socket.active = false
socket.loaded = false
socket.file = nil
fdo.handle.write = function(raw)
local req, url = parseRawRequest(raw, address)
if not req then
return nil, url
end
closeFile(socket)
socket.active = true
socket.loaded = false
socket.url = url
local response, err = buildHTTPResponse(req)
if not response then
socket.active = false
socket.error = err
return nil, err
end
socket.content = response
socket.file = kernel.sfile(response)
socket.loaded = true
socket.error = nil
return true
end
fdo.handle.read = function(count)
if not socket.active then
return
end
if socket.error then
return nil, socket.error
end
if not socket.file then
return
end
return socket.file.read(count)
end
fdo.handle.seek = function(whence, offset)
if not socket.active or not socket.file then
return
end
return socket.file.seek(whence, offset)
end
fdo.handle.close = function()
closeFile(socket)
socket.active = false
socket.loaded = false
socket.content = nil
socket.url = nil
socket.error = nil
return true
end
return true
end
local tcpHandler = {}
local function parseTCPAddress(address)
local host, port
if address:sub(1, 1) == "[" then
host, port = address:match("^%[([^%]]+)%]:(%d+)$")
if not host then
host = address:match("^%[([^%]]+)%]$")
end
else
host, port = address:match("^([^:]+):(%d+)$")
if not host then
host = address
end
end
if not host or host == "" then
return nil, nil, "EINVAL"
end
if port then
port = tonumber(port)
if not port or port < 1 or port > 65535 then
return nil, nil, "EINVAL"
end
end
return host, port
end
function tcpHandler.connect(fd, address)
if not tcpEnabled then
return nil, "EOPNOTSUPP"
end
local fdo = kernel.currentTask.fd[fd]
if not fdo then
return nil, "EBADF"
end
local host, port, err = parseTCPAddress(address)
if not host then
return nil, err
end
fdo.socket = fdo.socket or {}
local socket = fdo.socket
if socket.tcp then
closeHandle(socket.tcp)
end
socket.tcp = nil
socket.active = false
socket.error = nil
socket.host = host
socket.port = port
local ok, tcp = pcall(
internet.connect,
host,
port
)
if not ok or not tcp then
return nil, tostring(tcp or "ECONN")
end
socket.tcp = tcp
socket.active = true
local connected, result = pcall(
tcp.finishConnect
)
if not connected or result == false then
closeHandle(tcp)
socket.tcp = nil
socket.active = false
return nil, tostring(result or "ECONN")
end
fdo.handle.write = function(data)
if not socket.active or not socket.tcp then
return nil, "ENOTCONN"
end
if type(data) ~= "string" then
return nil, "EINVAL"
end
local writeOK, written = pcall(
socket.tcp.write,
data
)
if not writeOK then
return nil, tostring(written)
end
return written
end
fdo.handle.read = function(count)
if not socket.active or not socket.tcp then
return nil, "ENOTCONN"
end
local readOK, data = pcall(
socket.tcp.read,
count
)
if not readOK then
return nil, tostring(data)
end
return data
end
fdo.handle.seek = function()
return nil, "ESPIPE"
end
fdo.handle.close = function()
closeHandle(socket.tcp)
socket.tcp = nil
socket.active = false
socket.error = nil
socket.host = nil
socket.port = nil
return true
end
return true
end
if httpEnabled then
kernel.socket.registerProtocal(
"http://",
httpHandler
)
kernel.socket.registerProtocal(
"https://",
httpHandler
)
if kernel.log then
kernel.log("NET: HTTP/HTTPS initialized")
end
end
if tcpEnabled then
kernel.socket.registerProtocal(
"tcp://",
tcpHandler
)
if kernel.log then
kernel.log("NET: TCP initialized")
end
end
@@ -0,0 +1,390 @@
local kernel = ...
local component = kernel.oc.component
local computer = kernel.oc.computer
local plt = {
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,
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
}
local gpus = {}
local screens = {}
-- Collect GPUs.
for addr, typ in component.list("gpu") do
if typ == "gpu" then
local gpu = component.proxy(addr)
gpus[#gpus + 1] = {
addr = addr,
gpu = gpu,
screen = nil,
fg = nil,
bg = nil
}
end
end
-- Collect screens.
for addr, typ in component.list("screen") do
if typ == "screen" then
screens[addr] = {
cx = 1,
cy = 1,
w = 0,
h = 0,
addr = addr,
fg = 0xFFFFFF,
bg = 0x000000,
gpu = nil
}
end
end
-- Count screens.
local scrnum = 0
for _ in pairs(screens) do
scrnum = scrnum + 1
end
-- Find a GPU that can bind to a screen.
local function bindGPU(scr)
if scr.gpu then
local state = scr.gpu
if state.screen == scr.addr then
return state
end
end
for i = 1, #gpus do
local state = gpus[i]
-- Avoid unnecessary rebinding.
if state.screen == scr.addr then
scr.gpu = state
return state
end
-- Try binding this GPU.
local ok, result = pcall(state.gpu.bind, scr.addr)
if ok and result ~= false then
state.screen = scr.addr
state.fg = nil
state.bg = nil
scr.gpu = state
local w, h = state.gpu.maxResolution()
scr.w = w
scr.h = h
pcall(state.gpu.setResolution, w, h)
return state
end
end
error("No GPU available for screen " .. tostring(scr.addr))
end
-- Initialize screens.
for addr, scr in pairs(screens) do
local ok, result = pcall(bindGPU, scr)
if not ok then
kernel.log(
"Failed to initialize screen " ..
tostring(addr) .. ": " .. tostring(result)
)
end
end
kernel.log(
"initialized " ..
tostring(#gpus) ..
" gpus and " ..
tostring(scrnum) ..
" screens"
)
local newid = 0
-- Get the GPU currently assigned to a screen.
local function getGPU(scr)
local state = scr.gpu
if not state then
state = bindGPU(scr)
end
if state.screen ~= scr.addr then
local ok, result = pcall(state.gpu.bind, scr.addr)
if not ok or result == false then
state.screen = nil
state.fg = nil
state.bg = nil
scr.gpu = nil
state = bindGPU(scr)
else
state.screen = scr.addr
state.fg = nil
state.bg = nil
end
end
return state
end
-- Set colors only when they actually change.
local function setColors(state, scr)
local gpu = state.gpu
if state.fg ~= scr.fg then
gpu.setForeground(scr.fg)
state.fg = scr.fg
end
if state.bg ~= scr.bg then
gpu.setBackground(scr.bg)
state.bg = scr.bg
end
end
-- Scroll terminal.
local function scroll(scr, gpu)
gpu.copy(
1, 2,
scr.w, scr.h - 1,
0, -1
)
gpu.fill(
1, scr.h,
scr.w, 1,
" "
)
end
-- Write terminal output.
local function write(text, addr)
local scr = screens[addr]
if not scr then
error("NODEV")
end
local state = getGPU(scr)
local gpu = state.gpu
setColors(state, scr)
for i = 1, #text do
local char = text:sub(i, i)
if char == "\n" then
scr.cx = 1
scr.cy = scr.cy + 1
elseif char == "\t" then
scr.cx = scr.cx + (4 - ((scr.cx - 1) % 4))
elseif char == "\b" then
if scr.cx > 1 then
scr.cx = scr.cx - 1
gpu.set(scr.cx, scr.cy, " ")
end
else
gpu.set(scr.cx, scr.cy, char)
scr.cx = scr.cx + 1
end
if scr.cx > scr.w then
scr.cx = 1
scr.cy = scr.cy + 1
end
if scr.cy > scr.h then
scroll(scr, gpu)
scr.cy = scr.cy - 1
end
end
end
-- Create TTY.
local function newtty(addr)
newid = newid + 1
kernel.devfs.data["tty"][tostring(newid)] = function(op, mode)
if op == "type" then
return "Terminal"
elseif op == "open" then
local h = {
read = function(amount)
end,
write = function(content)
write(content, addr)
end,
size = function()
local scr = screens[addr]
return scr.w, scr.h
end,
clear = function()
local scr = screens[addr]
local state = getGPU(scr)
local gpu = state.gpu
setColors(state, scr)
gpu.fill(
1, 1,
scr.w, scr.h,
" "
)
scr.cx = 1
scr.cy = 1
end,
gpos = function()
local scr = screens[addr]
return scr.cx, scr.cy
end,
spos = function(x, y)
if not tonumber(x) or not tonumber(y) then
error("Invalid arg")
end
local scr = screens[addr]
scr.cx = x
scr.cy = y
end,
sfgc = function(c)
local scr = screens[addr]
if scr.fg ~= c then
scr.fg = c
end
end,
sbgc = function(c)
local scr = screens[addr]
if scr.bg ~= c then
scr.bg = c
end
end,
gfgc = function()
return screens[addr].fg
end,
gbgc = function()
return screens[addr].bg
end,
isvirt = function()
return false
end,
gplt = function()
return plt
end,
gfx = function()
return false
end
}
if mode == "rw" then
return h
elseif mode == "r" then
h.write = nil
return h
elseif mode == "w" then
h.read = nil
return h
end
end
end
end
if #gpus >= 1 and scrnum >= 1 then
for addr, scr in pairs(screens) do
if scr.gpu then
newtty(addr)
end
end
end
@@ -0,0 +1,120 @@
--:Minify:--
local kernel=...
kernel.oc.keyboards={}
local kbs=kernel.oc.keyboards
local kbidx=0
local keyboard = {}
keyboard.keys = {
back = 0x0E,
delete = 0xD3,
down = 0xD0,
enter = 0x1C,
home = 0xC7,
lcontrol = 0x1D,
left = 0xCB,
lmenu = 0x38,
lshift = 0x2A,
pageDown = 0xD1,
rcontrol = 0x9D,
right = 0xCD,
rmenu = 0xB8,
rshift = 0x36,
space = 0x39,
tab = 0x0F,
up = 0xC8,
["end"] = 0xCF,
numpadenter = 0x9C,
}
kernel.oc.keys=keyboard.keys
for i=0, 255 do
kernel.oc.keys[string.char(i)]=i
end
function keyboard.isAltDown(addr)
return kbs[addr].pressedCodes[keyboard.keys.lmenu] or kbs[addr].pressedCodes[keyboard.keys.rmenu]
end
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].pressedCodes[keyboard.keys.lcontrol] or kbs[addr].pressedCodes[keyboard.keys.rcontrol]
end
function keyboard.isKeyDown(addr,charOrCode)
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].pressedCodes[keyboard.keys.lshift] or kbs[addr].pressedCodes[keyboard.keys.rshift]
end
kernel.oc.keyboard=keyboard
local function serializeBool(bool)
if bool then
return "T"
else
return "F"
end
end
for addr, typ in kernel.oc.component.list("keyboard") do
if typ=="keyboard" then
kbidx=kbidx+1
kbs[addr]={pressedChars = {}, pressedCodes = {}, events=kernel.newFifo()}
kernel.devfs.data["input"]["keyboard"..tostring(kbidx)]=function(op,mode)
if op=="type" then
return "Keyboard"
elseif op=="open" then
local h = {
read=function(amount)
amount = amount or 1
local rv=""
for i=1, amount do
local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then
rv=rv..event[1]
else
break
end
end
if rv~="" then return rv end
local task=kernel.currentTask
task.status="D"
task.io=function()
local event = {kernel.oc.keyboards[addr].events.pop()}
if event[1] then return event[1] end
end
return nil
end,
write=function(content)
end,
gctrl=function()
return serializeBool(keyboard.isControlDown(addr))..";"..serializeBool(keyboard.isAltDown(addr))
end,
isKeyDown=function(char)
return keyboard.isKeyDown(addr,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
end
end
@@ -0,0 +1,97 @@
--:Minify:--
local kernel=...
local keys=kernel.oc.keys
kernel.processes.ocdaemon = function()
local timeout = false
kernel.log("OC daemon started")
local ctrlKeyMap = {
[keys.a]=1, [keys.b]=2, [keys.c]=3,
[keys.d]=4, [keys.e]=5, [keys.f]=6,
[keys.g]=7, [keys.h]=8, [keys.i]=9,
[keys.j]=10, [keys.k]=11, [keys.l]=12,
[keys.m]=13, [keys.n]=14, [keys.o]=15,
[keys.p]=16, [keys.q]=17, [keys.r]=18,
[keys.s]=19, [keys.t]=20, [keys.u]=21,
[keys.v]=22, [keys.w]=23, [keys.x]=24,
[keys.y]=25, [keys.z]=26,
}
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.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 addr = event[2]
local char = event[3]
local keyCode = event[4]
if eventType == "key_down" then
local keyboard = kernel.oc.keyboards[addr]
if keyboard.ctrl then
local ctrlByte = ctrlKeyMap[keyCode]
if ctrlByte then
if ctrlByte == 3 then
for _, task in ipairs(syscall.getTasks()) do
syscall.sigsend(task, 1)
end
else
keyboard.events.push(string.char(ctrlByte))
end
end
else
local special = specialKeyMap[keyCode]
if special then
keyboard.events.push(special)
elseif char and char > 0 then
keyboard.events.push(kernel.apis.unicode.char(char))
end
end
elseif eventType == "key_up" then
end
timeout = false
else
timeout = true
end
if timeout then
sleep(0.05)
end
end
end
kernel.log("OC daemon queued for execution")
@@ -0,0 +1,154 @@
--:Minify:--
local kernel=...
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
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 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, debug.traceback, task, pid)
if not ok then
kernel.log("[MAIN 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
ret = { coroutine.resume(task.coro, table.unpack(task.syscallReturn)) }
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], debug.traceback, 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
end
burstSteps = burstSteps + N
if N == 0 or burstSteps >= maxBurstSteps then
burstSteps = 0
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
end
+1
View File
@@ -0,0 +1 @@
firmware for Opencomputers mod
+1
View File
@@ -0,0 +1 @@
1.0.0
Loaded 100 of 361 files, more files were not shown because too many files have changed in this diff. Show more