Parcourir la source

feat(hal): working impl of HAL.

completely removal of c/c++ stuff.
greatbridf il y a 8 mois
Parent
commit
8672c72a5d
98 fichiers modifiés avec 646 ajouts et 4798 suppressions
  1. 0 29
      .clang-format
  2. 2 2
      .vscode/launch.json
  3. 2 2
      .vscode/tasks.json
  4. 0 71
      CMakeLists.txt
  5. 26 25
      Cargo.lock
  6. 2 2
      Cargo.toml
  7. 66 40
      Makefile.src
  8. 19 14
      README.md
  9. 3 2
      arch/src/x86_64/init.rs
  10. 0 4
      arch/src/x86_64/mod.rs
  11. 15 12
      arch/src/x86_64/percpu.rs
  12. 10 1
      build.rs
  13. 39 90
      configure
  14. 2 0
      crates/eonix_hal/Cargo.toml
  15. 49 0
      crates/eonix_hal/build.rs
  16. 167 11
      crates/eonix_hal/src/arch/x86_64/bootstrap.rs
  17. 96 0
      crates/eonix_hal/src/arch/x86_64/link.x
  18. 12 0
      crates/eonix_hal/src/arch/x86_64/memory.x
  19. 0 0
      crates/eonix_hal/src/arch/x86_64/mm.rs
  20. 4 5
      crates/eonix_hal/src/arch/x86_64/mod.rs
  21. 1 1
      crates/eonix_hal/src/arch/x86_64/trap.rs
  22. 1 1
      crates/eonix_hal/src/context.rs
  23. 1 0
      crates/eonix_hal/src/lib.rs
  24. 114 0
      crates/eonix_hal/src/link.x.in
  25. 1 0
      crates/eonix_hal/src/mm.rs
  26. 2 2
      crates/eonix_hal/src/trap.rs
  27. 0 71
      gblibc/CMakeLists.txt
  28. 0 16
      gblibc/include/alloca.h
  29. 0 21
      gblibc/include/assert.h
  30. 0 32
      gblibc/include/bits/alltypes.h
  31. 0 27
      gblibc/include/bits/ioctl.h
  32. 0 18
      gblibc/include/ctype.h
  33. 0 35
      gblibc/include/dirent.h
  34. 0 41
      gblibc/include/errno.h
  35. 0 49
      gblibc/include/fcntl.h
  36. 0 35
      gblibc/include/poll.h
  37. 0 69
      gblibc/include/signal.h
  38. 0 11
      gblibc/include/stdarg.h
  39. 0 30
      gblibc/include/stdint.h
  40. 0 80
      gblibc/include/stdio.h
  41. 0 37
      gblibc/include/stdlib.h
  42. 0 50
      gblibc/include/string.h
  43. 0 16
      gblibc/include/sys/ioctl.h
  44. 0 24
      gblibc/include/sys/mman.h
  45. 0 21
      gblibc/include/sys/mount.h
  46. 0 17
      gblibc/include/sys/prctl.h
  47. 0 105
      gblibc/include/sys/stat.h
  48. 0 16
      gblibc/include/sys/time.h
  49. 0 28
      gblibc/include/sys/types.h
  50. 0 19
      gblibc/include/sys/uio.h
  51. 0 43
      gblibc/include/sys/utsname.h
  52. 0 29
      gblibc/include/sys/wait.h
  53. 0 182
      gblibc/include/termios.h
  54. 0 19
      gblibc/include/time.h
  55. 0 63
      gblibc/include/unistd.h
  56. 0 11
      gblibc/private-include/devutil.h
  57. 0 34
      gblibc/private-include/list.h
  58. 0 41
      gblibc/private-include/priv-vars.h
  59. 0 97
      gblibc/private-include/syscall.h
  60. 0 65
      gblibc/src/arithmetic.c
  61. 0 12
      gblibc/src/assert.c
  62. 0 35
      gblibc/src/crt0.s
  63. 0 25
      gblibc/src/ctype.c
  64. 0 77
      gblibc/src/dirent.c
  65. 0 37
      gblibc/src/errno.c
  66. 0 27
      gblibc/src/fcntl.c
  67. 0 116
      gblibc/src/init.c
  68. 0 20
      gblibc/src/internal.c
  69. 0 5
      gblibc/src/platform-independent.s
  70. 0 23
      gblibc/src/signal.c
  71. 0 29
      gblibc/src/stat.c
  72. 0 845
      gblibc/src/stdio.c
  73. 0 286
      gblibc/src/stdlib.c
  74. 0 269
      gblibc/src/string.c
  75. 0 20
      gblibc/src/time.c
  76. 0 249
      gblibc/src/unistd.c
  77. 0 12
      gblibc/src/wait.c
  78. 0 341
      pretty-print.py
  79. 0 3
      rust-headers.hpp
  80. 4 7
      script/build-img.sh
  81. 0 232
      src/kernel.ld
  82. 2 1
      src/kernel/cpu.rs
  83. 1 1
      src/kernel/mem/mm_list.rs
  84. 4 4
      src/kernel/user/dataflow.rs
  85. 1 1
      src/kernel_init.rs
  86. 0 123
      src/mbr.S
  87. 0 0
      user-programs/busybox
  88. 0 0
      user-programs/busybox-minimal
  89. BIN
      user-programs/init.out
  90. BIN
      user-programs/int.out
  91. 0 21
      user-space-program/CMakeLists.txt
  92. 0 36
      user-space-program/basic-lib.h
  93. 0 9
      user-space-program/configure
  94. 0 25
      user-space-program/hello-world.s
  95. 0 91
      user-space-program/init.c
  96. 0 29
      user-space-program/interrupt-test.s
  97. 0 5
      user-space-program/priv-test.c
  98. 0 16
      user-space-program/stack-test.s

+ 0 - 29
.clang-format

@@ -1,29 +0,0 @@
----
-BasedOnStyle: Google
-AllowShortBlocksOnASingleLine: 'false'
-AllowShortCaseLabelsOnASingleLine: 'false'
-AllowShortFunctionsOnASingleLine: Inline
-AllowShortIfStatementsOnASingleLine: Never
-AllowShortLoopsOnASingleLine: 'false'
-BreakConstructorInitializers: BeforeComma
-ColumnLimit: '100'
-FixNamespaceComments: 'true'
-IncludeBlocks: Regroup
-IndentWidth: '4'
-NamespaceIndentation: Inner
-SpacesBeforeTrailingComments: '1'
-Language: Cpp
-Standard: Cpp11
-IncludeCategories:
-  - Regex: '^<types/'
-    Priority: '4'
-  - Regex: '^<(kernel|fs|net|driver)/'
-    Priority: '5'
-  - Regex: '^<.*\.h>'
-    Priority: '3'
-  - Regex: '^<.*>'
-    Priority: '2'
-  - Regex: '.*'
-    Priority: '1'
-
-...

+ 2 - 2
.vscode/launch.json

@@ -4,7 +4,7 @@
             "type": "cppdbg",
             "request": "launch",
             "name": "Launch Kernel",
-            "program": "${workspaceFolder}/build/kernel.out",
+            "program": "${workspaceFolder}/build/kernel.sym",
             "args": [],
             "stopAtEntry": false,
             "cwd": "${workspaceFolder}",
@@ -37,7 +37,7 @@
             "type": "cppdbg",
             "request": "launch",
             "name": "Attach Kernel",
-            "program": "${workspaceFolder}/build/kernel.out",
+            "program": "${workspaceFolder}/build/kernel.sym",
             "args": [],
             "stopAtEntry": false,
             "cwd": "${workspaceFolder}",

+ 2 - 2
.vscode/tasks.json

@@ -10,7 +10,7 @@
             "isBackground": true,
             "problemMatcher": [
                 {
-                    "owner": "cpp",
+                    "owner": "rustc",
                     "fileLocation": [
                         "relative",
                         "${workspaceFolder}"
@@ -25,7 +25,7 @@
                     },
                     "background": {
                         "activeOnStart": true,
-                        "beginsPattern": "cmake --build",
+                        "beginsPattern": "cargo build",
                         "endsPattern": "qemu"
                     }
                 }

+ 0 - 71
CMakeLists.txt

@@ -1,71 +0,0 @@
-cmake_minimum_required(VERSION 3.15)
-project(kernel_main C CXX ASM)
-
-set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
-
-set(CMAKE_CXX_LINK_EXECUTABLE
-    "<CMAKE_LINKER> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>")
-
-set(C_CXX_FLAGS "-nostdinc -nostdlib -mno-sse -mno-mmx -W -Wall -Wextra -Wno-stringop-overflow -Wno-builtin-declaration-mismatch -Wno-format -fverbose-asm -fno-exceptions -ffreestanding -fno-pic -mno-red-zone -mstack-protector-guard=global -mcmodel=kernel")
-set(CMAKE_C_FLAGS "${C_CXX_FLAGS} -Werror=implicit-int -Werror=implicit-function-declaration -Werror=strict-aliasing")
-set(CMAKE_CXX_FLAGS "${C_CXX_FLAGS} -fno-use-cxa-atexit -fno-rtti")
-set(CMAKE_CXX_LINK_FLAGS "-z noexecstack --gc-sections --no-check-sections")
-SET(CMAKE_ASM_FLAGS "${CFLAGS} -x assembler-with-cpp")
-set(CMAKE_CXX_STANDARD 20)
-
-if (CMAKE_BUILD_TYPE STREQUAL "Debug")
-    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DDEBUG -O0 -g")
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DDEBUG -O0 -g")
-    set(CARGO_BUILD_TYPE "debug")
-    set(CARGO_BUILD_FLAGS "")
-elseif(CMAKE_BUILD_TYPE STREQUAL "Release")
-    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O2 -g -DNDEBUG")
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2 -g -DNDEBUG")
-    set(CARGO_BUILD_TYPE "release")
-    set(CARGO_BUILD_FLAGS "--release")
-endif()
-
-if (NOT DEFINED FDISK_BIN)
-    set(FDISK_BIN fdisk)
-endif()
-
-add_subdirectory(gblibc)
-add_subdirectory(user-space-program)
-
-set(BOOTLOADER_SOURCES src/mbr.S)
-
-add_executable(kernel.out ${BOOTLOADER_SOURCES})
-add_dependencies(kernel.out rustpart)
-target_link_libraries(kernel.out gblibc gbos_rust_part)
-target_include_directories(kernel.out PRIVATE ${PROJECT_SOURCE_DIR}/include)
-target_link_options(kernel.out PRIVATE
-    -T "${CMAKE_SOURCE_DIR}/src/kernel.ld"
-    -L "${CMAKE_BINARY_DIR}/x86_64-unknown-none/${CARGO_BUILD_TYPE}"
-    --no-check-sections
-    )
-set_target_properties(kernel.out PROPERTIES LINK_DEPENDS "${CMAKE_SOURCE_DIR}/src/kernel.ld")
-set_target_properties(kernel.out PROPERTIES LINKER_LANGUAGE CXX)
-set_source_files_properties(src/mbr.S PROPERTIES OBJECT_DEPENDS
-    "${CMAKE_BINARY_DIR}/x86_64-unknown-none/${CARGO_BUILD_TYPE}/libgbos_rust_part.a"
-    )
-
-add_custom_target(rustpart
-    COMMAND cargo build ${CARGO_BUILD_FLAGS}
-)
-
-add_custom_command(OUTPUT mbr_hole.bin
-    DEPENDS kernel.out
-    COMMAND ${CMAKE_OBJCOPY} --strip-debug -O binary ${CMAKE_BINARY_DIR}/kernel.out mbr_hole.bin
-)
-
-add_custom_target(boot.img
-    DEPENDS mbr_hole.bin
-    DEPENDS user_space_programs
-    COMMAND make -C ${CMAKE_SOURCE_DIR} image
-)
-
-add_custom_command(OUTPUT run
-    POST_BUILD
-    DEPENDS boot.img
-    COMMAND bochs -f ${CMAKE_SOURCE_DIR}/bochs.conf
-)

+ 26 - 25
Cargo.lock

@@ -73,6 +73,31 @@ version = "1.13.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
 
+[[package]]
+name = "eonix-kernel"
+version = "0.1.0"
+dependencies = [
+ "acpi",
+ "arch",
+ "atomic_unique_refcell",
+ "bitflags",
+ "buddy_allocator",
+ "eonix_hal",
+ "eonix_log",
+ "eonix_macros",
+ "eonix_mm",
+ "eonix_percpu",
+ "eonix_preempt",
+ "eonix_runtime",
+ "eonix_sync",
+ "intrusive-collections",
+ "intrusive_list",
+ "itertools",
+ "pointers",
+ "posix_types",
+ "slab_allocator",
+]
+
 [[package]]
 name = "eonix_hal"
 version = "0.1.0"
@@ -81,6 +106,7 @@ dependencies = [
  "cfg-if",
  "eonix_hal_macros",
  "eonix_hal_traits",
+ "eonix_mm",
  "eonix_percpu",
  "eonix_preempt",
 ]
@@ -172,31 +198,6 @@ dependencies = [
  "intrusive-collections",
 ]
 
-[[package]]
-name = "gbos-rust-part"
-version = "0.1.0"
-dependencies = [
- "acpi",
- "arch",
- "atomic_unique_refcell",
- "bitflags",
- "buddy_allocator",
- "eonix_hal",
- "eonix_log",
- "eonix_macros",
- "eonix_mm",
- "eonix_percpu",
- "eonix_preempt",
- "eonix_runtime",
- "eonix_sync",
- "intrusive-collections",
- "intrusive_list",
- "itertools",
- "pointers",
- "posix_types",
- "slab_allocator",
-]
-
 [[package]]
 name = "intrusive-collections"
 version = "0.9.7"

+ 2 - 2
Cargo.toml

@@ -1,10 +1,10 @@
 [package]
-name = "gbos-rust-part"
+name = "eonix-kernel"
 version = "0.1.0"
 edition = "2021"
 
 [lib]
-crate-type = ["staticlib"]
+crate-type = ["bin"]
 
 [dependencies]
 arch = { path = "./arch" }

+ 66 - 40
Makefile.src

@@ -1,42 +1,51 @@
-# disable kvm to debug triple faults
-QEMU_BIN=##PLACEHOLDER_1##
-GDB_BIN=##PLACEHOLDER_2##
-QEMU_ACCELERATION_FLAG=##PLACEHOLDER_3##
-QEMU_DEBUG_FLAG=#-d cpu_reset,int -D build/qemu.log
-QEMU_ARGS=-machine q35 -drive id=disk,file=build/boot.img,format=raw,if=none \
+HOST ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
+ARCH ?= ##DEFAULT_ARCH##
+MODE ?= debug
+SMP ?= 4
+
+QEMU ?= ##QEMU##
+GDB ?= ##GDB##
+FDISK ?= ##FDISK##
+
+QEMU_ARGS ?= -machine q35 -drive id=disk,file=build/boot.img,format=raw,if=none \
 	-device ahci,id=ahci -device ide-hd,drive=disk,bus=ahci.0 -smp 4 \
-	-no-reboot -no-shutdown $(QEMU_ACCELERATION_FLAG) $(QEMU_DEBUG_FLAG)
+	-netdev user,id=mynet0,net=192.168.1.0/24,dhcpstart=192.168.1.16 -device e1000e,netdev=mynet0 \
+	-no-reboot -no-shutdown
+
+ifeq ($(HOST),darwin)
+QEMU_ACCEL ?= -accel tcg
+else ifeq ($(HOST),linux)
+QEMU_ACCEL ?= -accel kvm
+endif
+
+QEMU_ARGS += $(QEMU_ACCEL)
+
+ifneq ($(DEBUG_TRAPS),)
+QEMU_ARGS += -d cpu_reset,int,guest_errors -D build/qemu.log
+endif
 
-FDISK_BIN ?= ##PLACEHOLDER_5##
+ifneq ($(SMP),)
+QEMU_ARGS += -smp $(SMP)
+endif
+
+ifeq ($(MODE),debug)
+MODE := dev
+endif
 
-CROSS_COMPILE=##PLACEHOLDER_4##
 .PHONY: run
 run: build
-	$(QEMU_BIN) $(QEMU_ARGS) -display curses -S -s
+	$(QEMU) $(QEMU_ARGS) -display none -serial mon:stdio
+
 .PHONY: srun
 srun: build
-	$(QEMU_BIN) $(QEMU_ARGS) -display none -S -s -serial mon:stdio
-.PHONY: nativerun
-nativerun: build
-	$(QEMU_BIN) $(QEMU_ARGS) -display none -serial mon:stdio
-
-.PHONY: prepare
-prepare:
-	cmake -Bbuild -DCMAKE_BUILD_TYPE=Debug $(CROSS_COMPILE)
-	cp build/compile_commands.json .
-
-.PHONY: reprepare
-reprepare: clean prepare
-	true
-
-.PHONY: build
-build:
-	cmake --build build -j 6 --target boot.img
+	$(QEMU) $(QEMU_ARGS) -display none -S -s -serial mon:stdio
 
 .PHONY: clean
 clean:
+	-mv build/fs.img .
 	-rm -rf build
-	-rm compile_commands.json
+	-mkdir build
+	-mv fs.img build
 
 .PHONY: clean-all
 clean-all: clean
@@ -44,14 +53,14 @@ clean-all: clean
 
 .PHONY: debug
 debug:
-	-$(GDB_BIN) --symbols=build/kernel.out \
+	-RUST_GDB=$(GDB) rust-gdb --symbols=build/kernel.sym \
 		-iex 'source pretty-print.py' \
 		-iex 'set pagination off' \
 		-iex 'set output-radix 16' \
 		-iex 'set print asm-demangle on' \
 		-iex 'set print pretty on' \
 		-iex 'target remote:1234'
-	-killall $(QEMU_BIN)
+	-killall $(QEMU)
 
 .PHONY: tmux-debug
 tmux-debug:
@@ -62,17 +71,34 @@ tmux-debug:
 	-tmux attach -t gbos-debug
 	tmux kill-session -t gbos-debug
 
+.PHONY: kernel
+kernel:
+	cargo build --profile $(MODE)
+
+build/kernel.sym: kernel
+	cargo objcopy --profile $(MODE) -- --only-keep-debug build/kernel.sym
+
+build/mbr.bin: kernel
+	cargo objcopy --profile $(MODE) -- -O binary -j .mbr build/mbr.bin
+
+build/stage1.bin: kernel
+	cargo objcopy --profile $(MODE) -- -O binary -j .stage1 build/stage1.bin
+
+build/kernel.bin: kernel
+	cargo objcopy --profile $(MODE) -- -O binary --strip-debug \
+		-R .mbr -R .stage1 build/kernel.bin
+
 build/fs.img: init_script.sh
 	sh script/build-img.sh
 
-build/boot.img: build/fs.img build/mbr_hole.bin
-	dd if=build/mbr_hole.bin of=build/boot.img
-	dd if=build/fs.img of=build/boot.img bs=$(shell expr 4 \* 1024 \* 1024) seek=1 conv=notrunc
-	sh -c 'echo n; echo; echo; echo 8192; echo; echo a; echo w' | $(FDISK_BIN) build/boot.img
+build/boot.img: build/mbr.bin build/stage1.bin build/kernel.bin build/fs.img
+	dd if=build/mbr.bin of=build/boot.img bs=512 count=1 conv=notrunc 2> /dev/null
+	dd if=build/stage1.bin of=build/boot.img bs=512 seek=1 conv=notrunc 2> /dev/null
+	dd if=build/kernel.bin of=build/boot.img bs=4096 seek=1 conv=notrunc 2> /dev/null
+	dd if=build/fs.img of=build/boot.img bs=$(shell expr 4 \* 1024 \* 1024) \
+		seek=1 conv=notrunc 2> /dev/null
+	sh -c 'echo n; echo; echo; echo 8192; echo; echo a; echo w' \
+		| $(FDISK) build/boot.img 2> /dev/null > /dev/null
 
-build/boot.vdi: build/boot.img
-	-rm build/boot.vdi
-	VBoxManage convertfromraw $< $@ --format VDI
-
-.PHONY: image
-image: build/boot.img
+.PHONY: build
+build: build/boot.img build/kernel.sym

+ 19 - 14
README.md

@@ -15,7 +15,7 @@
 - [x] 静态 ELF 加载器
 - [x] TTY 及任务控制接口(正在进一步实现)
 - [x] FAT32 文件系统的读取实现
-- [ ] 全部 Rust 化(只剩一点点)
+- [x] 全部 Rust 化(只剩一点点)
 - [ ] 网卡驱动(WIP)
 - [ ] POSIX 线程接口(WIP)
 - [ ] 动态加载器(WIP)
@@ -180,11 +180,11 @@
 
 ```bash
 # 配置构建环境
-./configure && make prepare && make build
+./configure && make build
 
 # 直接运行
 
-make nativerun
+make run
 
 # 如果需要调试
 
@@ -201,14 +201,19 @@ make tmux-debug
 
 可能需要在运行 `./configure` 时在环境变量中指定正确版本的构建工具。
 
-- `QEMU`: 用于调试运行的 QEMU。默认使用 `qemu-system-x86_64`。
-- `GDB`: 用于 `make debug` 的 GDB。我们将默认查找 `gdb` 或者是 `x86_64-elf-gdb` 并检查支持的架构。
-- `FDISK_BIN`: 用于创建磁盘镜像分区表的 fdisk 可执行文件。默认使用 `fdisk`。
-
-如果正在进行交叉编译,请在运行 `./configure` 时将 `CROSS_COMPILE` 设置为你的交叉编译器的相应目标三元组。
-
-## 运行自己编译的程序
-
-项目目录下的 `user` 目录主要是出于一些*历史*原因存在,几乎没有任何用处。所以不要尝试查看里面的内容。
-
-要将你的程序(可以使用任何编译器为i386架构编译,静态链接)复制到构建的磁盘镜像中,你可以编辑 `CMakeLists.txt` 并在 `boot.img` 部分添加一行。你也可以尝试编辑 `init_script.sh` 以自定义启动过程。
+- `DEFAULT_ARCH`: 在调用 Makefile 时如果不进行额外指定,默认使用的架构。默认为 `x86_64`。
+- `QEMU`: 用于调试运行的 QEMU。默认使用 `qemu-system-$(ARCH)`。
+- `GDB`: 用于 `make debug` 的 GDB。我们将默认查找 `$(ARCH)-elf-gdb` 并检查支持的架构。
+- `FDISK`: 用于创建磁盘镜像分区表的 fdisk 可执行文件,要求使用来自 util-linux 版本的 fdisk。默认使用 `fdisk`。
+
+在运行 make 时可以指定的额外选项:
+
+- `HOST`: 当前平台架构,用于决定 qemu 的默认加速模式,默认使用 `uname -s` 的输出。
+- `ARCH`: 编译运行的目标架构,默认使用 configure 时指定的值。
+- `MODE`: 编译运行的模式,可以使用 `debug` 或者是 `release`。
+- `SMP`: 是否运行多处理器处理,默认使用 4 CPU。
+- `QEMU`: 手动指定 qemu 路径。
+- `GDB`: 手动指定 gdb 路径。
+- `FDISK`: 手动指定 fdisk 路径。
+- `QEMU_ACCEL`: 手动指定要使用的 qemu 加速方法。
+- `DEBUG_TRAPS`: 是否要进行 trap 的调试,使 qemu 输出详细的 trap 日志。

+ 3 - 2
arch/src/x86_64/init.rs

@@ -114,7 +114,7 @@ macro_rules! define_smp_bootstrap {
 
         core::arch::global_asm!(
             r#"
-        .pushsection .stage1.smp
+        .pushsection .stage1.smp, "ax", @progbits
         .code16
         .globl ap_bootstrap
         .type ap_bootstrap, @function
@@ -180,7 +180,8 @@ macro_rules! define_smp_bootstrap {
 
             xor %rbp, %rbp
             push %rbp # NULL return address
-            jmp {AP_ENTRY}
+            mov ${AP_ENTRY}, %rax
+            jmp *%rax
             .popsection
             "#,
             KERNEL_PML4 = const 0x1000,

+ 0 - 4
arch/src/x86_64/mod.rs

@@ -1,11 +1,9 @@
-mod bootstrap;
 mod fence;
 mod fpu;
 mod gdt;
 mod init;
 mod interrupt;
 mod io;
-mod mm;
 mod percpu;
 mod user;
 
@@ -18,10 +16,8 @@ pub use self::init::*;
 pub use self::interrupt::*;
 pub use self::io::*;
 pub use self::user::*;
-pub use bootstrap::*;
 pub use fence::*;
 pub use fpu::*;
-pub use mm::*;
 pub use percpu::*;
 
 #[inline(always)]

+ 15 - 12
arch/src/x86_64/percpu.rs

@@ -1,5 +1,4 @@
 use super::wrmsr;
-use crate::x86_64::mm::PAGE_SIZE;
 use core::{
     alloc::Layout,
     arch::asm,
@@ -7,6 +6,7 @@ use core::{
     ptr::{null_mut, NonNull},
     sync::atomic::{AtomicPtr, Ordering},
 };
+use eonix_mm::paging::PAGE_SIZE;
 
 pub const MAX_CPUS: usize = 256;
 
@@ -21,23 +21,27 @@ static PERCPU_POINTERS: [AtomicPtr<PercpuData>; MAX_CPUS] =
     [const { AtomicPtr::new(null_mut()) }; MAX_CPUS];
 
 impl PercpuArea {
-    fn page_count() -> usize {
+    fn len() -> usize {
         extern "C" {
-            static PERCPU_PAGES: usize;
+            fn PERCPU_LENGTH();
         }
-        // SAFETY: `PERCPU_PAGES` is defined in linker script and never change.
-        let page_count = unsafe { PERCPU_PAGES };
-        assert_ne!(page_count, 0);
-        page_count
+        let len = PERCPU_LENGTH as usize;
+
+        assert_ne!(len, 0, "Percpu length should not be zero.");
+        len
+    }
+
+    fn page_count() -> usize {
+        Self::len().div_ceil(PAGE_SIZE)
     }
 
     fn data_start() -> NonNull<u8> {
         extern "C" {
-            fn _PERCPU_DATA_START();
+            fn PERCPU_DATA_START();
         }
 
-        NonNull::new(_PERCPU_DATA_START as usize as *mut _)
-            .expect("Percpu data should not be null.")
+        let addr = PERCPU_DATA_START as usize;
+        NonNull::new(addr as *mut _).expect("Percpu data should not be null.")
     }
 
     fn layout() -> Layout {
@@ -52,8 +56,7 @@ impl PercpuArea {
 
         unsafe {
             // SAFETY: The `data_pointer` is of valid length and properly aligned.
-            data_pointer
-                .copy_from_nonoverlapping(Self::data_start(), Self::page_count() * PAGE_SIZE);
+            data_pointer.copy_from_nonoverlapping(Self::data_start(), Self::len());
         }
 
         Self {

+ 10 - 1
build.rs

@@ -1 +1,10 @@
-fn main() {}
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+    println!("cargo:rustc-link-arg=-T{}", "link.x");
+    if let Ok(extra_link_args) = std::env::var("DEP_EONIX_HAL_EXTRA_LINK_ARGS") {
+        for arg in extra_link_args.split_whitespace() {
+            println!("cargo:rustc-link-arg={}", arg);
+        }
+    }
+
+    Ok(())
+}

+ 39 - 90
configure

@@ -1,41 +1,27 @@
 #!/bin/sh
-QEMU_EXECUTABLES="qemu-system-x86_64"
-GDB_EXECUTABLES="gdb x86_64-elf-gdb"
+DEFAULT_ARCH="x86_64"
 
 event() {
     printf "$1... "
 }
 
-# $1: OS NAME
-# $2: CROSS COMPILE FLAG
-# $3: FDISK_BIN
-generate_cross_compile_script() {
-cat > cross-compile.cmake <<EOF
-set(CMAKE_SYSTEM_NAME $1)
-
-set(TOOLCHAIN_PATH_AND_PREFIX "$2")
-
-set(CMAKE_C_COMPILER \${TOOLCHAIN_PATH_AND_PREFIX}gcc)
-set(CMAKE_CXX_COMPILER \${TOOLCHAIN_PATH_AND_PREFIX}c++)
-set(CMAKE_AR \${TOOLCHAIN_PATH_AND_PREFIX}ar)
-set(CMAKE_LINKER \${TOOLCHAIN_PATH_AND_PREFIX}ld)
-set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
-
-SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
-# for libraries and headers in the target directories
-SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
-SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
-SET(FDISK_BIN $3)
-EOF
-}
-
-event "finding qemu"
-for item in $QEMU_EXECUTABLES; do
-    if $item --version > /dev/null 2>&1; then
-        QEMU="$item"
+if [ "$QEMU" = "" ]; then
+    event "checking default qemu"
+    QEMU="qemu-system-$DEFAULT_ARCH"
+    if $QEMU --version > /dev/null 2>&1; then
+        QEMU="qemu-system-\$(ARCH)"
         break
     fi
-done
+else
+    event "checking given qemu"
+    for item in $QEMU; do
+        if $item --version > /dev/null 2>&1; then
+            QEMU="$item"
+            break
+        fi
+    done
+    QEMU=""
+fi
 if [ "$QEMU" = "" ]; then
     echo "failed"
     exit 1
@@ -46,7 +32,7 @@ check_gdb_arch() {
     local item="$1"
     if $item --init-eval-command 'set arch' \
              --init-eval-command 'q' 2>&1 \
-             | grep 'x86-64' >/dev/null 2>&1; then
+             | grep "$DEFAULT_ARCH" >/dev/null 2>&1; then
         return 0
     else
         return 1
@@ -54,77 +40,41 @@ check_gdb_arch() {
 }
 
 if [ "$GDB" = "" ]; then
-    event "finding gdb"
-    for item in $GDB_EXECUTABLES; do
-        if check_gdb_arch "$item"; then
+    event "checking default gdb"
+    if check_gdb_arch "$DEFAULT_ARCH-elf-gdb"; then
+        GDB="\$(ARCH)-elf-gdb"
+        break
+    fi
+else
+    event 'checking given gdb'
+    for item in $GDB; do
+        if check_gdb_arch "$GDB"; then
             GDB="$item"
             break
         fi
     done
-    if [ "$GDB" = "" ]; then
-        echo "failed"
-        exit 1
-    fi
-else
-    event 'checking given gdb'
-    if ! check_gdb_arch "$GDB"; then
-        echo "failed"
-        exit 1
-    fi
+    GDB=""
+fi
+if [ "$GDB" = "" ]; then
+    echo "failed"
+    exit 1
 fi
 echo "$GDB"
 
-event "checking os type"
-OS=`uname`
-case "$OS" in
-    "Linux")
-        echo "Linux"
-        ;;
-    "Darwin")
-        echo "macOS"
-        ;;
-    *)
-        echo "unknown"
-        exit 1
-        ;;
-esac
-
-event "setting hardware acceleration type"
-case "$OS" in
-    "Linux")
-        echo "kvm"
-        # QEMU_ACCEL='-enable-kvm'
-        ;;
-    "Darwin")
-        echo "tcg"
-        QEMU_ACCEL='-accel tcg'
-        ;;
-esac
-
 event "checking util-linux fdisk"
-if [ "$FDISK_BIN" = "" -a "$CROSS_COMPILE" = "" ]; then
+if [ "$FDISK" = "" ]; then
     if ! which fdisk > /dev/null 2>&1; then
         echo "no"
         exit 1
     fi
-    FDISK_BIN=`which fdisk`
+    FDISK=`which fdisk`
 fi
 
-if ! $FDISK_BIN -v 2>&1 | grep util-linux > /dev/null 2>&1 ; then
+if ! $FDISK -v 2>&1 | grep util-linux > /dev/null 2>&1 ; then
     echo "no, fdisk is not from util-linux"
     exit 1
 else
-    echo "$FDISK_BIN"
-fi
-
-event "checking cross compiling"
-if [ "$CROSS_COMPILE" != "" ]; then
-    echo "yes"
-    CROSS_COMPILE_FLAG='--toolchain cross-compile.cmake'
-    generate_cross_compile_script "$OS" "$CROSS_COMPILE" "$FDISK_BIN"
-else
-    echo "no"
-    CROSS_COMPILE_FLAG=
+    echo "$FDISK"
 fi
 
 event "checking mkfs tool"
@@ -136,9 +86,8 @@ else
 fi
 
 cp Makefile.src Makefile
-sed -i '' -e "s|##PLACEHOLDER_1##|$QEMU|" Makefile > /dev/null 2>&1
-sed -i '' -e "s|##PLACEHOLDER_2##|$GDB|" Makefile > /dev/null 2>&1
-sed -i '' -e "s|##PLACEHOLDER_3##|$QEMU_ACCEL|" Makefile > /dev/null 2>&1
-sed -i '' -e "s|##PLACEHOLDER_4##|$CROSS_COMPILE_FLAG|" Makefile > /dev/null 2>&1
-sed -i '' -e "s|##PLACEHOLDER_5##|$FDISK_BIN|" Makefile > /dev/null 2>&1
+sed -i '' -e "s|##DEFAULT_ARCH##|$DEFAULT_ARCH|" Makefile > /dev/null 2>&1
+sed -i '' -e "s|##GDB##|$GDB|" Makefile > /dev/null 2>&1
+sed -i '' -e "s|##QEMU##|$QEMU|" Makefile > /dev/null 2>&1
+sed -i '' -e "s|##FDISK##|$FDISK|" Makefile > /dev/null 2>&1
 exit 0

+ 2 - 0
crates/eonix_hal/Cargo.toml

@@ -2,12 +2,14 @@
 name = "eonix_hal"
 version = "0.1.0"
 edition = "2024"
+links = "eonix_hal"
 
 [dependencies]
 eonix_hal_traits = { path = "./eonix_hal_traits" }
 eonix_hal_macros = { path = "./eonix_hal_macros" }
 
 arch = { path = "../../arch" }
+eonix_mm = { path = "../eonix_mm" }
 eonix_percpu = { path = "../eonix_percpu" }
 eonix_preempt = { path = "../eonix_preempt" }
 

+ 49 - 0
crates/eonix_hal/build.rs

@@ -0,0 +1,49 @@
+use std::path::PathBuf;
+use std::{env, fs};
+
+fn read_dependent_script(script: &str) -> Result<String, Box<dyn std::error::Error>> {
+    let content = fs::read_to_string(script)?;
+    println!("cargo:rerun-if-changed={}", script);
+    Ok(content)
+}
+
+fn process_ldscript_x86(script: &mut String) -> Result<(), Box<dyn std::error::Error>> {
+    // Otherwise `bootstrap.rs` might be ignored and not linked in.
+    println!("cargo:extra-link-args=--undefined=move_mbr --no-check-sections");
+
+    let memory = read_dependent_script("src/arch/x86_64/memory.x")?;
+    let link = read_dependent_script("src/arch/x86_64/link.x")?;
+
+    *script = memory + script;
+    script.push_str(&link);
+
+    Ok(())
+}
+
+fn process_ldscript_arch(
+    script: &mut String,
+    arch: &str,
+) -> Result<(), Box<dyn std::error::Error>> {
+    match arch {
+        "x86_64" => {
+            process_ldscript_x86(script)?;
+        }
+        _ => panic!("Unsupported architecture: {}", arch),
+    }
+
+    Ok(())
+}
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+    let out_dir = PathBuf::from(env::var("OUT_DIR")?);
+    let out_script = out_dir.join("link.x");
+
+    let in_script = "src/link.x.in";
+    let mut script = read_dependent_script(in_script)?;
+
+    process_ldscript_arch(&mut script, &env::var("CARGO_CFG_TARGET_ARCH")?)?;
+
+    fs::write(out_script, script)?;
+    println!("cargo:rustc-link-search={}", out_dir.display());
+    Ok(())
+}

+ 167 - 11
arch/src/x86_64/bootstrap.rs → crates/eonix_hal/src/arch/x86_64/bootstrap.rs

@@ -9,20 +9,168 @@ const KERNEL_PD_KIMAGE: usize = 0x4000;
 const KERNEL_PT_KIMAGE: usize = 0x5000;
 const KERNEL_PD_STRUCT_PAGE_ARR: usize = 0x6000;
 
-extern "C" {
-    static EARLY_GDT: [u64; 7];
-    static EARLY_GDT_DESCRIPTOR: [u8; 6];
-    static BIOS_IDT_DESCRIPTOR: [u8; 6];
-    static E820_MEM_MAP_DATA: [u8; 1024];
+#[unsafe(link_section = ".low")]
+static EARLY_GDT: [u64; 7] = [0; 7];
+
+#[unsafe(no_mangle)]
+#[unsafe(link_section = ".low")]
+static EARLY_GDT_DESCRIPTOR: (u16, u32) = (0, 0);
+
+#[unsafe(link_section = ".low")]
+static BIOS_IDT_DESCRIPTOR: (u16, u32) = (0, 0);
+
+#[unsafe(link_section = ".low")]
+static E820_MEM_MAP_DATA: [u64; 128] = [0; 128];
+
+unsafe extern "C" {
     fn _kernel_init() -> !;
 
     fn KIMAGE_32K_COUNT();
     fn KIMAGE_PAGES();
+
+    fn STAGE1_MAGIC();
+    fn STAGE1_MAGIC_VALUE();
+
+    fn start_32bit() -> !;
 }
 
 global_asm!(
-    r"
-    .pushsection .stage1
+    r#"
+    .pushsection .mbr, "ax", @progbits
+    .code16
+
+    .globl move_mbr
+    move_mbr:
+        xor %ax, %ax
+        mov %ax, %ds
+        mov %ax, %es
+        mov %ax, %ss
+
+        # move the MBR to 0xe00
+        mov $128, %cx # 512 bytes
+        mov $0x7c00, %si
+        mov $0x0e00, %di
+        rep movsl
+
+        ljmp $0x00, $2f
+
+    2:
+        # read the kernel stage1
+        mov $.Lread_data_packet, %si
+        mov $0x42, %ah
+        mov $0x80, %dl
+        int $0x13
+        jc .Lhalt16
+
+        # get memory size info and storage it
+        mov $0xe801, %ax
+        int $0x15
+        jc .Lhalt16
+
+        cmp $0x86, %ah # unsupported function
+        je .Lhalt16
+        cmp $0x80, %ah # invalid command
+        je .Lhalt16
+
+        jcxz 2f
+        mov %cx, %ax
+        mov %dx, %bx
+
+    2:
+        mov ${e820_data_addr}, %esp
+        movzw %ax, %eax
+        mov %eax, 8(%esp)  # 1k blocks
+        movzw %bx, %ebx
+        mov %ebx, 12(%esp) # 64k blocks
+
+        # save the destination address to es:di
+        mov %sp, %di
+        add $16, %di # buffer is 1024 - 16 bytes
+
+        # set default entry size
+        movl $20, 4(%esp)
+
+        # clear %ebx, len
+        xor %ebx, %ebx
+        mov %ebx, (%esp)
+
+    2:
+        # set the magic number to edx
+        mov $0x534D4150, %edx
+
+        # set function number to eax
+        mov $0xe820, %eax
+
+        # set default entry size
+        mov $24, %ecx
+
+        int $0x15
+
+        incl (%esp)
+        add $24, %edi
+
+        jc .Lsave_mem_fin
+        cmp $0, %ebx
+        jz .Lsave_mem_fin
+
+        cmp $24, %ecx
+        cmovnz 4(%esp), %ecx
+        mov %ecx, 4(%esp)
+
+        jmp 2b
+
+    .Lsave_mem_fin:
+        mov $0x3ff, %ax
+        mov ${bios_idt_descriptor}, %di
+        mov %ax, (%di)
+
+        xor %eax, %eax
+        mov %eax, 2(%di)
+
+        lgdt .Learly_gdt_descriptor
+
+        cli
+        # IDT descriptor is 6 0's. borrow the null gdt entry
+        lidt .Learly_gdt
+
+        # enable protection mode
+        mov %cr0, %eax
+        or $1, %eax
+        mov %eax, %cr0
+
+        ljmp $0x08, ${start_32bit}
+
+    .Lhalt16:
+        hlt
+        jmp .
+
+    .align 16
+    .Learly_gdt:
+        .8byte 0x0                # null selector
+        .8byte 0x00cf9a000000ffff # 32bit code selector
+        .8byte 0x00cf92000000ffff # 32bit data selector
+
+    .align 4
+    .Learly_gdt_descriptor:
+        .word 0x17 # size
+        .long .Learly_gdt  # address
+
+    .align 16
+    .Lread_data_packet:
+        .long  0x00070010 # .stage1 takes up 3.5K, or 7 sectors
+        .long  0x00007000 # read to 0000:7000
+        .8byte 1          # read from LBA 1
+    .popsection
+    "#,
+    start_32bit = sym start_32bit,
+    bios_idt_descriptor = sym BIOS_IDT_DESCRIPTOR,
+    e820_data_addr = sym E820_MEM_MAP_DATA,
+    options(att_syntax),
+);
+
+global_asm!(
+    r#"
+    .pushsection .stage1, "ax", @progbits
     .code16
     .Lhalt:
         hlt
@@ -140,13 +288,18 @@ global_asm!(
         .8byte 0x000f9a000000ffff # 16bit code selector
         .8byte 0x000f92000000ffff # 16bit data selector
 
-    .globl start_32bit
-    start_32bit:
+    {start_32bit}:
         mov $0x10, %ax
         mov %ax, %ds
         mov %ax, %es
         mov %ax, %ss
 
+        mov ${STAGE1_MAGIC}, %edi
+        mov (%edi), %edi
+
+        cmp ${STAGE1_MAGIC_VALUE}, %edi
+        jne .Lhalt
+
         mov ${EARLY_GDT_DESCRIPTOR}, %edi
         mov $0x37, %ax
         mov %ax, (%edi)
@@ -185,7 +338,7 @@ global_asm!(
         mov ${KIMAGE_32K_COUNT}, %ecx
         shl $1, %ecx
         movl ${KERNEL_IMAGE_PADDR}, 4(%esp) # destination address
-        movl $9, (%esp) # LBA
+        movl $8, (%esp) # LBA
 
     2:
         mov (%esp), %edi
@@ -320,12 +473,14 @@ global_asm!(
         jmp {start_64bit}
     
     .popsection
-    ",
+    "#,
     EARLY_GDT = sym EARLY_GDT,
     EARLY_GDT_DESCRIPTOR = sym EARLY_GDT_DESCRIPTOR,
     BIOS_IDT_DESCRIPTOR = sym BIOS_IDT_DESCRIPTOR,
     KIMAGE_32K_COUNT = sym KIMAGE_32K_COUNT,
     KIMAGE_PAGES = sym KIMAGE_PAGES,
+    STAGE1_MAGIC = sym STAGE1_MAGIC,
+    STAGE1_MAGIC_VALUE = sym STAGE1_MAGIC_VALUE,
     KERNEL_IMAGE_PADDR = const KERNEL_IMAGE_PADDR,
     KERNEL_PML4 = const KERNEL_PML4,
     PA_P = const PA_P,
@@ -339,6 +494,7 @@ global_asm!(
     KERNEL_PD_KIMAGE = const KERNEL_PD_KIMAGE,
     KERNEL_PT_KIMAGE = const KERNEL_PT_KIMAGE,
     start_64bit = sym start_64bit,
+    start_32bit = sym start_32bit,
     options(att_syntax),
 );
 

+ 96 - 0
crates/eonix_hal/src/arch/x86_64/link.x

@@ -0,0 +1,96 @@
+SECTIONS {
+    .low 0x500 (NOLOAD) :
+    {
+
+        KEEP(*(.low .low*));
+
+    } > LOWMEM
+
+    .mbr 0xe00 :
+    {
+        KEEP(*(.mbr));
+
+        /* avoid the MBR being overwritten */
+        . = ABSOLUTE(ADDR(.mbr) + 446);
+
+        /* avoid the MBR being overwritten */
+        . = ABSOLUTE(ADDR(.mbr) + 510);
+        BYTE(0x55);
+        BYTE(0xaa);
+    } > LOWMEM = 0x00
+
+    .stage1 0x7000 :
+    {
+        KEEP(*(.stage1.smp));
+
+        . = ALIGN(16);
+        KEEP(*(.stage1));
+
+        . = ABSOLUTE(ADDR(.stage1) + 512 * 7 - 4);
+        STAGE1_MAGIC = .;
+        LONG(ABSOLUTE(STAGE1_MAGIC_VALUE));
+
+        STAGE1_MAGIC_VALUE = 0x01145140;
+    } > LOWMEM AT> LOWMEM
+}
+
+SECTIONS {
+    .text.syscall_fns :
+    {
+
+        KEEP(*(.syscall_fns*));
+
+    } > REGION_TEXT
+}
+INSERT AFTER .text;
+
+SECTIONS {
+    .rodata.fixups :
+    {
+        . = ALIGN(16);
+        FIX_START = .;
+
+        KEEP(*(.fix));
+
+        FIX_END = .;
+    } > REGION_RODATA
+
+    .rodata.syscalls :
+    {
+        . = ALIGN(16);
+        __raw_syscall_handlers_start = .;
+
+        RAW_SYSCALL_HANDLERS = .;
+        KEEP(*(.raw_syscalls*));
+
+        __raw_syscall_handlers_end = .;
+
+        RAW_SYSCALL_HANDLERS_SIZE =
+            ABSOLUTE(__raw_syscall_handlers_end - __raw_syscall_handlers_start);
+    } > REGION_RODATA
+}
+INSERT AFTER .rodata;
+
+SECTIONS {
+    .percpu : ALIGN(16)
+    {
+        __spercpu = .;
+
+        PERCPU_START = .;
+        QUAD(0); /* Reserved for x86 percpu pointer */
+
+        . = ALIGN(16);
+
+        *(.percpu .percpu*);
+
+        . = ALIGN(16);
+        __epercpu = .;
+    } > KPERCPU AT> REGION_RODATA
+
+    PERCPU_DATA_START = LOADADDR(.percpu);
+    PERCPU_LENGTH = ABSOLUTE(__epercpu - __spercpu);
+
+    KIMAGE_PAGES = (__edata - _stext + 0x1000 - 1) / 0x1000;
+    KIMAGE_32K_COUNT = (KIMAGE_PAGES + 8 - 1) / 8;
+}
+INSERT AFTER .rodata;

+ 12 - 0
crates/eonix_hal/src/arch/x86_64/memory.x

@@ -0,0 +1,12 @@
+MEMORY {
+    LOWMEM             : org = 0x0000000000000000, len = 1M
+    KBSS         (wa)  : org = 0xffffffffc0200000, len = 2M
+    KIMAGE       (rwx) : org = 0xffffffffffc00000, len = 2M
+    KPERCPU            : org = 0x0000000000000000, len = 128K
+}
+
+REGION_ALIAS("REGION_TEXT", KIMAGE);
+REGION_ALIAS("REGION_RODATA", KIMAGE);
+REGION_ALIAS("REGION_DATA", KIMAGE);
+REGION_ALIAS("REGION_BSS", KBSS);
+REGION_ALIAS("REGION_EHFRAME", KIMAGE);

+ 0 - 0
arch/src/x86_64/mm.rs → crates/eonix_hal/src/arch/x86_64/mm.rs


+ 4 - 5
crates/eonix_hal/src/arch/x86_64/mod.rs

@@ -1,5 +1,4 @@
-mod context;
-mod trap;
-
-pub use context::TaskContext;
-pub use trap::{TrapContext, TRAP_STUBS_START};
+pub mod bootstrap;
+pub mod context;
+pub mod mm;
+pub mod trap;

+ 1 - 1
crates/eonix_hal/src/arch/x86_64/trap.rs

@@ -1,6 +1,6 @@
 mod trap_context;
 
-use super::TaskContext;
+use super::context::TaskContext;
 use core::arch::{global_asm, naked_asm};
 use eonix_hal_traits::{context::RawTaskContext, trap::TrapReturn};
 

+ 1 - 1
crates/eonix_hal/src/context.rs

@@ -1 +1 @@
-pub use crate::arch::TaskContext;
+pub use crate::arch::context::TaskContext;

+ 1 - 0
crates/eonix_hal/src/lib.rs

@@ -4,6 +4,7 @@
 pub(crate) mod arch;
 
 pub mod context;
+pub mod mm;
 pub mod processor;
 pub mod trap;
 

+ 114 - 0
crates/eonix_hal/src/link.x.in

@@ -0,0 +1,114 @@
+PROVIDE(_stext = ORIGIN(REGION_TEXT));
+
+SECTIONS {
+    .text.dummy (NOLOAD) :
+    {
+        /*
+         * If we use _stext somewhere before its first appearance below, we
+         * need to define it as absolute here to avoid linker errors.
+         */
+        . = ABSOLUTE(_stext);
+
+    } > REGION_TEXT
+
+    .text _stext :
+    {
+        __stext = .;
+
+        *(.text .text.*);
+
+    } > REGION_TEXT
+
+    __etext = .;
+
+    .rodata : ALIGN(16)
+    {
+        __srodata = .;
+
+        *(.rodata .rodata.*);
+
+    } > REGION_RODATA
+
+    __erodata = .;
+
+    .data : ALIGN(16)
+    {
+        __sdata = .;
+
+        *(.data .data.*);
+        *(.got .got.plt);
+
+    } > REGION_DATA
+
+    __edata = .;
+
+    .bss (NOLOAD) : ALIGN(16)
+    {
+        __sbss = .;
+
+        *(.bss .bss.*);
+
+        . = ALIGN(0x1000);
+    } > REGION_BSS
+
+    __ebss = .;
+
+    .eh_frame : ALIGN(16)
+    {
+        __seh_frame = .;
+
+        KEEP(*(.eh_frame .eh_frame*));
+
+    } > REGION_EHFRAME
+
+    . = ALIGN(0x1000);
+    __eeh_frame = .;
+}
+
+SECTIONS {
+    /* Stabs debugging sections.  */
+    .stab          0 : { KEEP(*(.stab)); }
+    .stabstr       0 : { KEEP(*(.stabstr)); }
+    .stab.excl     0 : { KEEP(*(.stab.excl)); }
+    .stab.exclstr  0 : { KEEP(*(.stab.exclstr)); }
+    .stab.index    0 : { KEEP(*(.stab.index)); }
+    .stab.indexstr 0 : { KEEP(*(.stab.indexstr)); }
+    .comment       0 : { KEEP(*(.comment)); }
+    /* DWARF debug sections.
+       Symbols in the DWARF debugging sections are relative to the beginning
+       of the section so we begin them at 0.  */
+    /* DWARF 1 */
+    .debug          0 : { KEEP(*(.debug)); }
+    .line           0 : { KEEP(*(.line)); }
+    /* GNU DWARF 1 extensions */
+    .debug_srcinfo  0 : { KEEP(*(.debug_srcinfo)); }
+    .debug_sfnames  0 : { KEEP(*(.debug_sfnames)); }
+    /* DWARF 1.1 and DWARF 2 */
+    .debug_aranges  0 : { KEEP(*(.debug_aranges)); }
+    .debug_pubnames 0 : { KEEP(*(.debug_pubnames)); }
+    /* DWARF 2 */
+    .debug_info     0 : { KEEP(*(.debug_info)); }
+    .debug_abbrev   0 : { KEEP(*(.debug_abbrev)); }
+    .debug_line     0 : { KEEP(*(.debug_line)); }
+    .debug_frame    0 : { KEEP(*(.debug_frame)); }
+    .debug_str      0 : { KEEP(*(.debug_str)); }
+    .debug_loc      0 : { KEEP(*(.debug_loc)); }
+    .debug_macinfo  0 : { KEEP(*(.debug_macinfo)); }
+    /* SGI/MIPS DWARF 2 extensions */
+    .debug_weaknames 0 : { KEEP(*(.debug_weaknames)); }
+    .debug_funcnames 0 : { KEEP(*(.debug_funcnames)); }
+    .debug_typenames 0 : { KEEP(*(.debug_typenames)); }
+    .debug_varnames  0 : { KEEP(*(.debug_varnames)); }
+
+    /* DWARF Other */
+    .debug_ranges  0 : { KEEP(*(.debug_ranges)); }
+    .debug_line_str 0 : { KEEP(*(.debug_line_str)); }
+
+    /DISCARD/ :
+    {
+        *(.fini_array*)
+        *(.note*)
+        *(.dtors*)
+        *(.debug_gdb_scripts*)
+    }
+}

+ 1 - 0
crates/eonix_hal/src/mm.rs

@@ -0,0 +1 @@
+pub use crate::arch::mm::{DefaultPagingMode, PAGE_SIZE};

+ 2 - 2
crates/eonix_hal/src/trap.rs

@@ -1,8 +1,8 @@
 use eonix_hal_traits::trap::IsRawTrapContext;
 
-pub use crate::arch::TrapContext;
+pub use crate::arch::trap::TrapContext;
 
 // TODO: Remove this once the arch module is fully implemented.
-pub use crate::arch::TRAP_STUBS_START;
+pub use crate::arch::trap::TRAP_STUBS_START;
 
 struct _CheckTrapContext(IsRawTrapContext<TrapContext>);

+ 0 - 71
gblibc/CMakeLists.txt

@@ -1,71 +0,0 @@
-cmake_minimum_required(VERSION 3.15)
-project(gblibc)
-
-add_library(gblibc STATIC
-    src/stdio.c
-    src/arithmetic.c
-    src/string.c
-    src/fcntl.c
-    src/unistd.c
-    src/wait.c
-    src/assert.c
-    src/dirent.c
-    src/ctype.c
-    src/stdlib.c
-    src/errno.c
-    src/init.c
-    src/internal.c
-    src/stat.c
-    src/time.c
-    src/signal.c
-    src/platform-independent.s
-)
-
-add_library(gblibc_32 STATIC
-    src/stdio.c
-    src/arithmetic.c
-    src/string.c
-    src/fcntl.c
-    src/unistd.c
-    src/wait.c
-    src/assert.c
-    src/dirent.c
-    src/ctype.c
-    src/stdlib.c
-    src/errno.c
-    src/init.c
-    src/internal.c
-    src/stat.c
-    src/time.c
-    src/signal.c
-    src/platform-independent.s
-)
-
-add_library(crt0_32 OBJECT
-    src/crt0.s
-)
-
-target_compile_options(gblibc_32 PRIVATE "-fno-pic")
-target_compile_options(gblibc_32 PRIVATE "-mcmodel=32")
-target_compile_options(gblibc_32 PRIVATE "-m32")
-target_compile_options(crt0_32 PRIVATE "-fno-pic")
-target_compile_options(crt0_32 PRIVATE "-m32")
-target_compile_options(crt0_32 PRIVATE "-mcmodel=32")
-target_link_options(gblibc_32 PRIVATE "LINKER:-melf_i386")
-target_link_options(crt0_32 PRIVATE "LINKER:-melf_i386")
-
-file(GLOB_RECURSE GBLIBC_PUBLIC_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/include)
-
-target_include_directories(gblibc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
-                                  PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/private-include)
-
-set_target_properties(gblibc PROPERTIES PRIVATE_HEADER
-    "private-include/devutil.h,private-include/syscall.h")
-set_target_properties(gblibc PROPERTIES PUBLIC_HEADER "${GBLIBC_PUBLIC_HEADERS}")
-
-target_include_directories(gblibc_32 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
-                                  PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/private-include)
-
-set_target_properties(gblibc_32 PROPERTIES PRIVATE_HEADER
-    "private-include/devutil.h,private-include/syscall.h")
-set_target_properties(gblibc_32 PROPERTIES PUBLIC_HEADER "${GBLIBC_PUBLIC_HEADERS}")

+ 0 - 16
gblibc/include/alloca.h

@@ -1,16 +0,0 @@
-#ifndef __GBLIBC_ALLOCA_H_
-#define __GBLIBC_ALLOCA_H_
-
-#include <stdint.h>
-
-#define alloca(size) __builtin_alloca(size)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 21
gblibc/include/assert.h

@@ -1,21 +0,0 @@
-#ifndef __GBLIBC_ASSERT_H_
-#define __GBLIBC_ASSERT_H_
-
-#ifdef NDEBUG
-#define assert(st) ((void)(st))
-#else
-#define assert(st) ((void)((st) || (__assert_fail(#st, __FILE__, __LINE__, __func__), 0)))
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-void __attribute__((noreturn))
-__assert_fail(const char* statement, const char* file, int line, const char* func);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 32
gblibc/include/bits/alltypes.h

@@ -1,32 +0,0 @@
-#ifndef __GBLIBC_BITS_ALLTYPES_H_
-#define __GBLIBC_BITS_ALLTYPES_H_
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef size_t blksize_t;
-typedef size_t blkcnt_t;
-
-struct timespec {
-    time_t tv_sec;
-    long tv_nsec;
-};
-
-struct timeval {
-    time_t tv_sec;
-    size_t tv_usec;
-};
-
-struct timezone {
-    int tz_minuteswest;
-    int tz_dsttime;
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 27
gblibc/include/bits/ioctl.h

@@ -1,27 +0,0 @@
-#ifndef __GBLIBC_BITS_IOCTL_H_
-#define __GBLIBC_BITS_IOCTL_H_
-
-#include <sys/uio.h>
-
-#define TCGETS (0x5401)
-#define TCSETS (0x5402)
-#define TIOCGPGRP (0x540f)
-#define TIOCSPGRP (0x5410)
-#define TIOCGWINSZ (0x5413)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct winsize {
-    unsigned short ws_row;
-    unsigned short ws_col;
-    unsigned short ws_xpixel;
-    unsigned short ws_ypixel;
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 18
gblibc/include/ctype.h

@@ -1,18 +0,0 @@
-#ifndef __GBLIBC_CTYPE_H_
-#define __GBLIBC_CTYPE_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int islower(int c);
-int isupper(int c);
-
-int tolower(int c);
-int toupper(int c);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 35
gblibc/include/dirent.h

@@ -1,35 +0,0 @@
-#ifndef __GBLIBC_DIRENT_H_
-#define __GBLIBC_DIRENT_H_
-
-#include <sys/types.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct dirent {
-    ino_t d_ino;
-    off_t d_off;
-    unsigned short d_reclen;
-    unsigned char d_type;
-    char d_name[256];
-};
-
-typedef struct _DIR {
-    int fd;
-    struct dirent dent;
-    char buffer[232];
-    int bpos;
-    int blen;
-} DIR;
-
-DIR* opendir(const char* name);
-DIR* fdopendir(int fd);
-
-struct dirent* readdir(DIR* dirp);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 41
gblibc/include/errno.h

@@ -1,41 +0,0 @@
-#ifndef __GBLIBC_ERRNO_H_
-#define __GBLIBC_ERRNO_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-extern int* __errno_location(void);
-
-#undef errno
-#define errno (*__errno_location())
-
-#define EPERM 1
-#define ENOENT 2
-#define ESRCH 3
-#define EINTR 4
-#define EIO 5
-#define EBADF 9
-#define ECHILD 10
-#define EAGAIN 11
-#define ENOMEM 12
-#define EACCES 13
-#define EFAULT 14
-#define EEXIST 17
-#define ENODEV 19
-#define ENOTDIR 20
-#define EISDIR 21
-#define EINVAL 22
-#define ENOTTY 25
-#define ESPIPE 29
-#define EROFS 30
-#define EPIPE 32
-#define ERANGE 34
-#define ELOOP 40
-#define EOVERFLOW 75
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 49
gblibc/include/fcntl.h

@@ -1,49 +0,0 @@
-#ifndef __GBLIBC_FCNTL_H_
-#define __GBLIBC_FCNTL_H_
-
-#include <stdint.h>
-
-#define O_RDONLY          00
-#define O_WRONLY          01
-#define O_RDWR            02
-#define O_CREAT         0100
-#define O_EXCL          0200
-#define O_TRUNC        01000
-#define O_APPEND       02000
-#define O_DIRECTORY  0200000
-#define O_CLOEXEC   02000000
-
-#define F_DUPFD 0
-#define F_GETFD 1
-#define F_SETFD 2
-#define F_GETFL 3
-#define F_SETFL 4
-#define F_DUPFD_CLOEXEC 1030
-// TODO: more flags
-
-#define FD_CLOEXEC 1
-
-#define AT_FDCWD (-100)
-#define AT_SYMLINK_NOFOLLOW   0x100
-#define AT_REMOVEDIR          0x200
-#define AT_SYMLINK_FOLLOW     0x400
-#define AT_STATX_SYNC_AS_STAT 0x0000
-#define AT_STATX_SYNC_TYPE    0x6000
-#define AT_STATX_SYNC_FORCE   0x8000
-#define AT_STATX_DONT_SYNC    0x2000
-
-#define SEEK_SET 0
-#define SEEK_CUR 1
-#define SEEK_END 2
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int open(const char* filename, int flags, ...);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 35
gblibc/include/poll.h

@@ -1,35 +0,0 @@
-#ifndef __GBLIBC_POLL_H_
-#define __GBLIBC_POLL_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef unsigned int nfds_t;
-
-#define POLLIN          0x0001          /* any readable data available */
-#define POLLPRI         0x0002          /* OOB/Urgent readable data */
-#define POLLOUT         0x0004          /* file descriptor is writeable */
-#define POLLRDNORM      0x0040          /* non-OOB/URG data available */
-#define POLLWRNORM      POLLOUT         /* no write type differentiation */
-#define POLLRDBAND      0x0080          /* OOB/Urgent readable data */
-#define POLLWRBAND      0x0100          /* OOB/Urgent data can be written */
-
-#define POLLERR         0x0008          /* some poll error occurred */
-#define POLLHUP         0x0010          /* file descriptor was "hung up" */
-#define POLLNVAL        0x0020          /* requested events "invalid" */
-
-#define POLLSTANDARD    (POLLIN|POLLPRI|POLLOUT|POLLRDNORM|POLLRDBAND|\
-	                 POLLWRBAND|POLLERR|POLLHUP|POLLNVAL)
-
-struct pollfd {
-	int     fd;
-	short   events;
-	short   revents;
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 69
gblibc/include/signal.h

@@ -1,69 +0,0 @@
-#ifndef __GBLIBC_SIGNAL_H_
-#define __GBLIBC_SIGNAL_H_
-
-#include <sys/types.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define SIGHUP    1
-#define SIGINT    2
-#define SIGQUIT   3
-#define SIGILL    4
-#define SIGTRAP   5
-#define SIGABRT   6
-#define SIGIOT    SIGABRT
-#define SIGBUS    7
-#define SIGFPE    8
-#define SIGKILL   9
-#define SIGUSR1   10
-#define SIGSEGV   11
-#define SIGUSR2   12
-#define SIGPIPE   13
-#define SIGALRM   14
-#define SIGTERM   15
-#define SIGSTKFLT 16
-#define SIGCHLD   17
-#define SIGCONT   18
-#define SIGSTOP   19
-#define SIGTSTP   20
-#define SIGTTIN   21
-#define SIGTTOU   22
-#define SIGURG    23
-#define SIGXCPU   24
-#define SIGXFSZ   25
-#define SIGVTALRM 26
-#define SIGPROF   27
-#define SIGWINCH  28
-#define SIGIO     29
-#define SIGPOLL   29
-#define SIGPWR    30
-#define SIGSYS    31
-#define SIGUNUSED SIGSYS
-#define SIGRTMIN  32
-#define SIGRTMAX  64
-
-#define SIG_BLOCK 0
-#define SIG_UNBLOCK 1
-#define SIG_SETMASK 2
-
-#define SA_RESTORER 0x04000000
-#define SA_ONSTACK  0x08000000
-#define SA_RESTART  0x10000000
-#define SA_NODEFER  0x40000000
-
-#define SIG_DFL ((sighandler_t)0)
-#define SIG_IGN ((sighandler_t)1)
-
-typedef void (*sighandler_t)(int);
-typedef void (*sigrestorer_t)(void);
-
-int kill(pid_t pid, int sig);
-int raise(int sig);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 11
gblibc/include/stdarg.h

@@ -1,11 +0,0 @@
-#ifndef __GBLIBC_STDARG_H_
-#define __GBLIBC_STDARG_H_
-
-typedef __builtin_va_list va_list;
-
-#define va_start(v, l) __builtin_va_start(v, l)
-#define va_arg(v, l) __builtin_va_arg(v, l)
-#define va_end(v) __builtin_va_end(v)
-#define va_copy(v, l) __builtin_va_copy(v, l)
-
-#endif

+ 0 - 30
gblibc/include/stdint.h

@@ -1,30 +0,0 @@
-#ifndef __GBLIBC_STDINT_H_
-#define __GBLIBC_STDINT_H_
-
-#undef NULL
-#ifdef __cplusplus
-#define NULL (nullptr)
-#else
-#define NULL ((void*)0)
-#endif
-
-typedef __INT8_TYPE__ int8_t;
-typedef __INT16_TYPE__ int16_t;
-typedef __INT32_TYPE__ int32_t;
-typedef __INT64_TYPE__ int64_t;
-
-typedef __UINT8_TYPE__ uint8_t;
-typedef __UINT16_TYPE__ uint16_t;
-typedef __UINT32_TYPE__ uint32_t;
-typedef __UINT64_TYPE__ uint64_t;
-
-typedef __UINTPTR_TYPE__ uintptr_t;
-typedef __INTPTR_TYPE__ intptr_t;
-
-typedef __SIZE_TYPE__ size_t;
-typedef int64_t ssize_t;
-
-typedef uint64_t time_t;
-typedef int64_t time_diff_t;
-
-#endif

+ 0 - 80
gblibc/include/stdio.h

@@ -1,80 +0,0 @@
-#ifndef __GBLIBC_STDIO_H_
-#define __GBLIBC_STDIO_H_
-
-#include <stdarg.h>
-#include <stdint.h>
-
-#undef EOF
-#define EOF (-1)
-
-#undef BUFSIZ
-#define BUFSIZ (1024)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct __io_file {
-    int fd;
-    uint32_t flags;
-
-    char* rbuf;
-    size_t rpos;
-    size_t rcnt;
-    size_t rbsz;
-
-    char* wbuf;
-    size_t wpos;
-    size_t wbsz;
-} FILE;
-
-int putchar(int character);
-int getchar(void);
-
-int puts(const char* str);
-char* gets(char* str);
-
-int vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args);
-int snprintf(char* buf, size_t bufsize, const char* fmt, ...);
-int sprintf(char* buf, const char* fmt, ...);
-int vasprintf(char** strp, const char* fmt, va_list args);
-int asprintf(char** strp, const char* fmt, ...);
-
-int vfprintf(FILE* stream, const char* fmt, va_list args);
-int fprintf(FILE* stream, const char* fmt, ...);
-
-int vprintf(const char* fmt, va_list args);
-int printf(const char* fmt, ...);
-
-FILE* fopen(const char* path, const char* mode);
-int fflush(FILE* stream);
-int fclose(FILE* stream);
-
-int getc_unlocked(FILE* stream);
-int putc_unlocked(int character, FILE* stream);
-int fputs_unlocked(const char* s, FILE* stream);
-int fputc_unlocked(int character, FILE* stream);
-int fputs(const char* s, FILE* stream);
-int fgetc(FILE* stream);
-int fputc(int character, FILE* stream);
-
-int ferror(FILE* stream);
-int ferror_unlocked(FILE* stream);
-int feof(FILE* stream);
-void clearerr(FILE* stream);
-
-extern FILE* stdout;
-extern FILE* stdin;
-extern FILE* stderr;
-#undef stdout
-#undef stdin
-#undef stderr
-#define stdout (stdout)
-#define stdin (stdin)
-#define stderr (stderr)
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 37
gblibc/include/stdlib.h

@@ -1,37 +0,0 @@
-#ifndef __GBLIBC_STDLIB_H_
-#define __GBLIBC_STDLIB_H_
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int atoi(const char* str);
-
-void __attribute__((noreturn)) exit(int status);
-
-void* malloc(size_t size);
-void* realloc(void* ptr, size_t newsize);
-void free(void* ptr);
-
-typedef int (*comparator_t)(const void* a, const void* b);
-void qsort(void* base, size_t num, size_t size, comparator_t comparator);
-void* bsearch(
-    const void* key,
-    const void* base,
-    size_t num,
-    size_t size,
-    comparator_t comparator);
-
-int rand(void);
-int rand_r(unsigned int* seedp);
-void srand(unsigned int seed);
-
-int setenv(const char* name, const char* value, int overwrite);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 50
gblibc/include/string.h

@@ -1,50 +0,0 @@
-#ifndef __GBLIBC_STRING_H_
-#define __GBLIBC_STRING_H_
-
-#include <stdint.h>
-
-#undef CR
-#undef LF
-#define CR ('\r')
-#define LF ('\n')
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int memcmp(const void* ptr1, const void* ptr2, size_t num);
-
-void* memmove(void* dst, const void* src, size_t n);
-void* memcpy(void* dst, const void* src, size_t n);
-void* mempcpy(void* dst, const void* src, size_t n);
-void* memset(void* dst, int c, size_t n);
-
-char* strerror(int errnum);
-
-int strcmp(const char* s1, const char* s2);
-int strncmp(const char* s1, const char* s2, size_t n);
-int strcasecmp(const char* s1, const char* s2);
-int strncasecmp(const char* s1, const char* s2, size_t n);
-size_t strlen(const char* str);
-char* strchr(const char* str, int character);
-char* strrchr(const char* str, int character);
-char* strchrnul(const char* str, int character);
-size_t strcspn(const char* str1, const char* str2);
-char* strstr(const char* str1, const char* str2);
-char* strpbrk(const char* str1, const char* str2);
-
-char* strcpy(char* dst, const char* src);
-char* strncpy(char* dst, const char* src, size_t n);
-char* stpcpy(char* dst, const char* src);
-char* stpncpy(char* dst, const char* src, size_t n);
-
-char* strdup(const char* str);
-char* strndup(const char* str, size_t n);
-
-char* strsignal(int sig);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 16
gblibc/include/sys/ioctl.h

@@ -1,16 +0,0 @@
-#ifndef __GBLIBC_SYS_IOCTL_H_
-#define __GBLIBC_SYS_IOCTL_H_
-
-#include <bits/ioctl.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int ioctl(int fd, unsigned long request, ...);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 24
gblibc/include/sys/mman.h

@@ -1,24 +0,0 @@
-#ifndef __GBLIBC_SYS_MMAN_H
-#define __GBLIBC_SYS_MMAN_H
-
-#include <sys/types.h>
-
-#define MAP_SHARED 0x01
-#define MAP_PRIVATE 0x02
-#define MAP_FIXED 0x10
-#define MAP_ANONYMOUS 0x20
-
-#define PROT_NONE 0
-#define PROT_READ 1
-#define PROT_WRITE 2
-#define PROT_EXEC 4
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 21
gblibc/include/sys/mount.h

@@ -1,21 +0,0 @@
-#ifndef __GBLIBC_SYS_MOUNT_H
-#define __GBLIBC_SYS_MOUNT_H
-
-#define MS_RDONLY      (1 <<  0)
-#define MS_NOSUID      (1 <<  1)
-#define MS_NODEV       (1 <<  2)
-#define MS_NOEXEC      (1 <<  3)
-#define MS_NOATIME     (1 << 10)
-#define MS_RELATIME    (1 << 21)
-#define MS_STRICTATIME (1 << 24)
-#define MS_LAZYTIME    (1 << 25)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 17
gblibc/include/sys/prctl.h

@@ -1,17 +0,0 @@
-#ifndef __GBLIBC_SYS_PRCTL_H
-#define __GBLIBC_SYS_PRCTL_H
-
-#include <sys/types.h>
-
-#define PR_SET_NAME 15
-#define PR_GET_NAME 16
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 105
gblibc/include/sys/stat.h

@@ -1,105 +0,0 @@
-#ifndef __GBLIBC_SYS_STAT_H
-#define __GBLIBC_SYS_STAT_H
-
-#include <stdint.h>
-#include <bits/alltypes.h>
-#include <sys/types.h>
-
-#define STATX_TYPE (1 << 0)
-#define STATX_MODE (1 << 1)
-#define STATX_NLINK (1 << 2)
-#define STATX_UID (1 << 3)
-#define STATX_GID (1 << 4)
-#define STATX_ATIME (1 << 5)
-#define STATX_MTIME (1 << 6)
-#define STATX_CTIME (1 << 7)
-#define STATX_INO (1 << 8)
-#define STATX_SIZE (1 << 9)
-#define STATX_BLOCKS (1 << 10)
-#define STATX_BASIC_STATS (0x7ff)
-#define STATX_BTIME (1 << 11)
-
-#define S_IFMT 0170000
-
-#define S_IFSOCK 0140000
-#define S_IFLNK 0120000
-#define S_IFREG 0100000
-#define S_IFBLK 0060000
-#define S_IFDIR 0040000
-#define S_IFCHR 0020000
-#define S_IFIFO 0010000
-
-#define S_ISSOCK(m) (((m)&S_IFMT) == S_IFSOCK)
-#define S_ISLNK(m) (((m)&S_IFMT) == S_IFLNK)
-#define S_ISREG(m) (((m)&S_IFMT) == S_IFREG)
-#define S_ISBLK(m) (((m)&S_IFMT) == S_IFBLK)
-#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)
-#define S_ISCHR(m) (((m)&S_IFMT) == S_IFCHR)
-#define S_ISFIFO(m) (((m)&S_IFMT) == S_IFIFO)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct statx_timestamp {
-    int64_t tv_sec;
-    uint32_t tv_nsec;
-    int32_t __reserved;
-};
-
-struct statx {
-    uint32_t stx_mask;
-    uint32_t stx_blksize;
-    uint64_t stx_attributes;
-    uint32_t stx_nlink;
-    uint32_t stx_uid;
-    uint32_t stx_gid;
-    uint16_t stx_mode;
-    uint16_t __spare0[1];
-    uint64_t stx_ino;
-    uint64_t stx_size;
-    uint64_t stx_blocks;
-    uint64_t stx_attributes_mask;
-    struct statx_timestamp stx_atime;
-    struct statx_timestamp stx_btime;
-    struct statx_timestamp stx_ctime;
-    struct statx_timestamp stx_mtime;
-    uint32_t stx_rdev_major;
-    uint32_t stx_rdev_minor;
-    uint32_t stx_dev_major;
-    uint32_t stx_dev_minor;
-    uint64_t stx_mnt_id;
-    uint64_t stx_dio_alignment[13];
-};
-
-struct stat {
-    dev_t st_dev;
-    ino_t st_ino;
-    nlink_t st_nlink;
-
-    mode_t st_mode;
-    uid_t st_uid;
-    gid_t st_gid;
-
-    dev_t st_rdev;
-    off_t st_size;
-    blksize_t st_blksize;
-    blkcnt_t st_blocks;
-
-    struct timespec st_atim;
-    struct timespec st_mtim;
-    struct timespec st_ctim;
-
-    long __padding[3];
-};
-
-int stat(const char* pathname, struct stat* statbuf);
-int fstat(int fd, struct stat* statbuf);
-
-mode_t umask(mode_t mask);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 16
gblibc/include/sys/time.h

@@ -1,16 +0,0 @@
-#ifndef __GBLIBC_SYS_TIME_H_
-#define __GBLIBC_SYS_TIME_H_
-
-#include <bits/alltypes.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int gettimeofday(struct timeval* tv, struct timezone* tz);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 28
gblibc/include/sys/types.h

@@ -1,28 +0,0 @@
-#ifndef __GBLIBC_SYS_TYPES_H
-#define __GBLIBC_SYS_TYPES_H
-
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef int pid_t;
-typedef unsigned long ino_t;
-typedef long off_t;
-typedef unsigned dev_t;
-typedef unsigned uid_t;
-typedef unsigned gid_t;
-typedef unsigned short mode_t;
-typedef unsigned long nlink_t;
-
-typedef unsigned long long ino64_t;
-typedef long long off64_t;
-
-typedef off64_t loff_t;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 19
gblibc/include/sys/uio.h

@@ -1,19 +0,0 @@
-#ifndef __GBLIBC_SYS_UIO_H
-#define __GBLIBC_SYS_UIO_H
-
-#include <sys/types.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct iovec {
-    void* iov_base;
-    size_t iov_len;
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 43
gblibc/include/sys/utsname.h

@@ -1,43 +0,0 @@
-#ifndef __GBLIBC_SYS_UTSNAME_H
-#define __GBLIBC_SYS_UTSNAME_H
-
-#include <sys/types.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define OLD_UTSNAME_LENGTH 8
-
-struct oldold_utsname {
-    char sysname[9];
-    char nodename[9];
-    char release[9];
-    char version[9];
-    char machine[9];
-};
-
-#define UTSNAME_LENGTH 64
-
-struct old_utsname {
-    char sysname[65];
-    char nodename[65];
-    char release[65];
-    char version[65];
-    char machine[65];
-};
-
-struct new_utsname {
-    char sysname[65];
-    char nodename[65];
-    char release[65];
-    char version[65];
-    char machine[65];
-    char domainname[65];
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 29
gblibc/include/sys/wait.h

@@ -1,29 +0,0 @@
-#ifndef __GBLIBC_SYS_WAIT_H
-#define __GBLIBC_SYS_WAIT_H
-
-#include <sys/types.h>
-
-#define WNOHANG 1
-#define WUNTRACED 2
-
-#define WEXISTATUS(s) (((s) & 0xff00) >> 8)
-#define WTERMSIG(s) ((s) & 0x7f)
-#define WSTOPSIG(s) WEXITSTATUS(s)
-#define WCOREDUMP(s) ((s) & 0x80)
-#define WIFEXITED(s) (!WTERMSIG(s))
-#define WIFSTOPPED(s) (((s) & 0x7f) == 0x7f)
-#define WIFSIGNALED(s) (WTERMSIG(s) && !WIFSTOPPED(s))
-#define WIFCONTINUED(s) ((s) == 0xffff)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-pid_t wait(int* code);
-pid_t waitpid(pid_t pid, int* code, int options);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 182
gblibc/include/termios.h

@@ -1,182 +0,0 @@
-#ifndef __GBLIBC_TERMIOS_H_
-#define __GBLIBC_TERMIOS_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define NCCS 32
-
-typedef unsigned char cc_t;
-typedef unsigned int speed_t;
-typedef unsigned int tcflag_t;
-
-struct termios {
-    tcflag_t c_iflag;
-    tcflag_t c_oflag;
-    tcflag_t c_cflag;
-    tcflag_t c_lflag;
-
-    cc_t c_line;
-    cc_t c_cc[NCCS];
-
-    speed_t c_ispeed;
-    speed_t c_ospeed;
-};
-
-// taken from linux kernel code
-
-/* c_cc characters */
-#define VINTR		 0
-#define VQUIT		 1
-#define VERASE		 2
-#define VKILL		 3
-#define VEOF		 4
-#define VTIME		 5
-#define VMIN		 6
-#define VSWTC		 7
-#define VSTART		 8
-#define VSTOP		 9
-#define VSUSP		10
-#define VEOL		11
-#define VREPRINT	12
-#define VDISCARD	13
-#define VWERASE		14
-#define VLNEXT		15
-#define VEOL2		16
-
-/* c_iflag bits */
-#define IGNBRK	0x0001			/* Ignore break condition */
-#define BRKINT	0x0002			/* Signal interrupt on break */
-#define IGNPAR	0x0004			/* Ignore characters with parity errors */
-#define PARMRK	0x0008			/* Mark parity and framing errors */
-#define INPCK	0x0010			/* Enable input parity check */
-#define ISTRIP	0x0020			/* Strip 8th bit off characters */
-#define INLCR	0x0040			/* Map NL to CR on input */
-#define IGNCR	0x0080			/* Ignore CR */
-#define ICRNL	0x0100			/* Map CR to NL on input */
-#define IUCLC	0x0200
-#define IXON	0x0400
-#define IXANY	0x0800			/* Any character will restart after stop */
-#define IXOFF	0x1000
-#define IMAXBEL	0x2000
-#define IUTF8	0x4000
-
-/* c_oflag bits */
-#define OPOST	0x00001			/* Perform output processing */
-#define OLCUC	0x00002
-#define ONLCR	0x00004
-#define OCRNL	0x00008
-#define ONOCR	0x00010
-#define ONLRET	0x00020
-#define OFILL	0x00040
-#define OFDEL	0x00080
-#define NLDLY	0x00100
-#define   NL0	0x00000
-#define   NL1	0x00100
-#define CRDLY	0x00600
-#define   CR0	0x00000
-#define   CR1	0x00200
-#define   CR2	0x00400
-#define   CR3	0x00600
-#define TABDLY	0x01800
-#define   TAB0	0x00000
-#define   TAB1	0x00800
-#define   TAB2	0x01000
-#define   TAB3	0x01800
-#define   XTABS	0x01800
-#define BSDLY	0x02000
-#define   BS0	0x00000
-#define   BS1	0x02000
-#define VTDLY	0x04000
-#define   VT0	0x00000
-#define   VT1	0x04000
-#define FFDLY	0x08000
-#define   FF0	0x00000
-#define   FF1	0x08000
-
-/* c_cflag bit meaning */
-/* Common CBAUD rates */
-#define     B0		0x00000000	/* hang up */
-#define    B50		0x00000001
-#define    B75		0x00000002
-#define   B110		0x00000003
-#define   B134		0x00000004
-#define   B150		0x00000005
-#define   B200		0x00000006
-#define   B300		0x00000007
-#define   B600		0x00000008
-#define  B1200		0x00000009
-#define  B1800		0x0000000a
-#define  B2400		0x0000000b
-#define  B4800		0x0000000c
-#define  B9600		0x0000000d
-#define B19200		0x0000000e
-#define B38400		0x0000000f
-#define EXTA		B19200
-#define EXTB		B38400
-
-#define ADDRB		0x20000000	/* address bit */
-#define CMSPAR		0x40000000	/* mark or space (stick) parity */
-#define CRTSCTS		0x80000000	/* flow control */
-
-#define IBSHIFT		16		/* Shift from CBAUD to CIBAUD */
-
-#define CBAUD		0x0000100f
-#define CSIZE		0x00000030
-#define   CS5		0x00000000
-#define   CS6		0x00000010
-#define   CS7		0x00000020
-#define   CS8		0x00000030
-#define CSTOPB		0x00000040
-#define CREAD		0x00000080
-#define PARENB		0x00000100
-#define PARODD		0x00000200
-#define HUPCL		0x00000400
-#define CLOCAL		0x00000800
-#define CBAUDEX		0x00001000
-#define BOTHER		0x00001000
-#define     B57600	0x00001001
-#define    B115200	0x00001002
-#define    B230400	0x00001003
-#define    B460800	0x00001004
-#define    B500000	0x00001005
-#define    B576000	0x00001006
-#define    B921600	0x00001007
-#define   B1000000	0x00001008
-#define   B1152000	0x00001009
-#define   B1500000	0x0000100a
-#define   B2000000	0x0000100b
-#define   B2500000	0x0000100c
-#define   B3000000	0x0000100d
-#define   B3500000	0x0000100e
-#define   B4000000	0x0000100f
-#define CIBAUD		0x100f0000	/* input baud rate */
-
-/* c_lflag bits */
-#define ISIG	0x00001
-#define ICANON	0x00002
-#define XCASE	0x00004
-#define ECHO	0x00008
-#define ECHOE	0x00010
-#define ECHOK	0x00020
-#define ECHONL	0x00040
-#define NOFLSH	0x00080
-#define TOSTOP	0x00100
-#define ECHOCTL	0x00200
-#define ECHOPRT	0x00400
-#define ECHOKE	0x00800
-#define FLUSHO	0x01000
-#define PENDIN	0x04000
-#define IEXTEN	0x08000
-#define EXTPROC	0x10000
-
-// line disciplines
-
-#define N_TTY 0
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 19
gblibc/include/time.h

@@ -1,19 +0,0 @@
-#ifndef __GBLIBC_TIME_H_
-#define __GBLIBC_TIME_H_
-
-#include <stdint.h>
-#include <bits/alltypes.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define CLOCK_REALTIME 0
-#define CLOCK_MONOTONIC 1
-typedef int clockid_t;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 63
gblibc/include/unistd.h

@@ -1,63 +0,0 @@
-#ifndef __GBLIBC_UNISTD_H_
-#define __GBLIBC_UNISTD_H_
-
-#include <sys/types.h>
-
-#undef STDOUT_FILENO
-#undef STDIN_FILENO
-#undef STDERR_FILENO
-#define STDIN_FILENO (0)
-#define STDOUT_FILENO (1)
-#define STDERR_FILENO (2)
-
-#define F_OK 0
-#define R_OK 1
-#define W_OK 2
-#define X_OK 4
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-ssize_t read(int fd, void* buf, size_t count);
-ssize_t write(int fd, const void* buf, size_t count);
-
-int dup(int oldfd);
-int dup2(int oldfd, int newfd);
-
-int pipe(int pipefd[2]);
-
-int close(int fd);
-
-void __attribute__((noreturn)) _exit(int code);
-pid_t fork(void);
-int execve(const char* pathname, char* const argv[], char* const envp[]);
-
-unsigned int sleep(unsigned int seconds);
-
-int chdir(const char* path);
-char* getcwd(char* buf, size_t bufsize);
-
-pid_t getpid(void);
-pid_t getppid(void);
-
-int setpgid(pid_t pid, pid_t pgid);
-
-pid_t setsid(void);
-pid_t getsid(pid_t pid);
-
-pid_t tcgetpgrp(int fd);
-int tcsetpgrp(int fd, pid_t pgrp);
-
-int brk(void* addr);
-void* sbrk(ssize_t increment);
-
-int isatty(int fd);
-
-extern char** environ;
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 11
gblibc/private-include/devutil.h

@@ -1,11 +0,0 @@
-#ifndef __GBLIBC_DEVUTIL_H_
-#define __GBLIBC_DEVUTIL_H_
-
-#ifdef __i386__
-
-#define __GBLIBC__X86_SYSTEM_
-#define __32bit_system
-
-#endif
-
-#endif

+ 0 - 34
gblibc/private-include/list.h

@@ -1,34 +0,0 @@
-#ifndef __GBLIBC_LIST_H_
-#define __GBLIBC_LIST_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct list_node {
-    struct list_node* prev;
-    struct list_node* next;
-    char data[];
-};
-
-typedef struct list_node list_node;
-typedef list_node list_head;
-
-#define NDDATA(node, type) (*((type*)((node).data)))
-#define NDPREV(node) ((node).prev)
-#define NDNEXT(node) ((node).next)
-#define NDISEND(node) (!((node).next))
-#define NEWNODE(type) ((struct list_node*)malloc(sizeof(list_node) + sizeof(type)))
-#define NDPTR(p_data) ((list_node*)((char*)p_data - sizeof(list_node)))
-
-void __node_insert(list_node* node, list_node* new_node);
-void __node_erase(list_node* node);
-
-#define NDINSERT(node, newnode) __node_insert(node, newnode)
-#define NDERASE(p_node) __node_erase(p_node)
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 41
gblibc/private-include/priv-vars.h

@@ -1,41 +0,0 @@
-#ifndef __GBLIBC_PRIV_VARS_H_
-#define __GBLIBC_PRIV_VARS_H_
-
-#include <list.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct mem {
-    uint32_t sz;
-    uint32_t flag;
-};
-
-#define FILE_READ (1 << 0)
-#define FILE_WRITE (1 << 1)
-#define FILE_ERROR (1 << 2)
-#define FILE_EOF (1 << 3)
-
-void** __start_brk_location(void);
-void** __curr_brk_location(void);
-list_head* __io_files_location(void);
-size_t* __environ_size_location(void);
-
-#undef start_brk
-#define start_brk (*__start_brk_location())
-#undef curr_brk
-#define curr_brk (*__curr_brk_location())
-
-#undef iofiles
-#define iofiles (*__io_files_location())
-
-#undef environ_size
-#define environ_size (*__environ_size_location())
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 97
gblibc/private-include/syscall.h

@@ -1,97 +0,0 @@
-#ifndef __GBLIBC_SYSCALL_H_
-#define __GBLIBC_SYSCALL_H_
-
-#include <stdint.h>
-
-#define SYS_exit (0x01)
-#define SYS_fork (0x02)
-#define SYS_read (0x03)
-#define SYS_write (0x04)
-#define SYS_open (0x05)
-#define SYS_close (0x06)
-#define SYS_waitpid (0x07)
-#define SYS_execve (0x0b)
-#define SYS_chdir (0x0c)
-#define SYS_stat (0x12)
-#define SYS_getpid (0x14)
-#define SYS_fstat (0x1c)
-#define SYS_kill (0x25)
-#define SYS_dup (0x29)
-#define SYS_pipe (0x2a)
-#define SYS_brk (0x2d)
-#define SYS_ioctl (0x36)
-#define SYS_setpgid (0x39)
-#define SYS_dup2 (0x3f)
-#define SYS_umask (0x3c)
-#define SYS_getppid (0x40)
-#define SYS_setsid (0x42)
-#define SYS_gettimeofday (0x4e)
-#define SYS_getdents (0x84)
-#define SYS_writev (0x92)
-#define SYS_getsid (0x93)
-#define SYS_nanosleep (0xa2)
-#define SYS_getcwd (0xb7)
-#define SYS_set_thread_area (0xf3)
-#define SYS_exit_group (0xfc)
-#define SYS_set_tid_address (0x102)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-static inline uint32_t syscall0(uint32_t no)
-{
-    asm volatile(
-        "movl %1, %%eax\n"
-        "int $0x80\n"
-        "movl %%eax, %0"
-        : "=g"(no)
-        : "g"(no)
-        : "eax");
-    return no;
-}
-static inline uint32_t syscall1(uint32_t no, uint32_t arg)
-{
-    asm volatile(
-        "movl %1, %%ebx\n"
-        "movl %2, %%eax\n"
-        "int $0x80\n"
-        "movl %%eax, %0"
-        : "=g"(no)
-        : "g"(arg), "g"(no)
-        : "eax", "ebx");
-    return no;
-}
-static inline uint32_t syscall2(uint32_t no, uint32_t arg1, uint32_t arg2)
-{
-    asm volatile(
-        "movl %1, %%ebx\n"
-        "movl %2, %%ecx\n"
-        "movl %3, %%eax\n"
-        "int $0x80\n"
-        "movl %%eax, %0"
-        : "=g"(no)
-        : "g"(arg1), "g"(arg2), "g"(no)
-        : "eax", "ebx", "ecx");
-    return no;
-}
-static inline uint32_t syscall3(uint32_t no, uint32_t arg1, uint32_t arg2, uint32_t arg3)
-{
-    asm volatile(
-        "movl %1, %%ebx\n"
-        "movl %2, %%ecx\n"
-        "movl %3, %%edx\n"
-        "movl %4, %%eax\n"
-        "int $0x80\n"
-        "movl %%eax, %0"
-        : "=g"(no)
-        : "g"(arg1), "g"(arg2), "g"(arg3), "g"(no)
-        : "eax", "ebx", "ecx", "edx");
-    return no;
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif

+ 0 - 65
gblibc/src/arithmetic.c

@@ -1,65 +0,0 @@
-#include <devutil.h>
-#include <stdint.h>
-
-static inline uint64_t do_div(uint64_t a, uint64_t b, uint64_t* remainder)
-{
-    uint64_t r = 0, q = 0;
-    for (int32_t i = 0; i < 64; i++) {
-        r = (r << 1) + (a >> 63);
-        a <<= 1;
-        q <<= 1;
-        if (r >= b) {
-            r -= b;
-            q += 1;
-        }
-    }
-    if (remainder)
-        *remainder = r;
-    return q;
-}
-
-static inline int64_t do_div_s(int64_t a, int64_t b, uint64_t* remainder)
-{
-    int32_t qf = 0, rf = 0;
-    if (a < 0) {
-        qf = rf = 1;
-        a = -a;
-    }
-    if (b < 0) {
-        qf ^= 1;
-        b = -b;
-    }
-
-    int64_t quotient = do_div(a, b, (uint64_t*)remainder);
-
-    if (qf)
-        quotient = -quotient;
-    if (remainder && rf)
-        *remainder = -*remainder;
-
-    return quotient;
-}
-
-int64_t __divdi3(int64_t a, int64_t b)
-{
-    return do_div_s(a, b, (uint64_t*)0);
-}
-
-int64_t __moddi3(int64_t a, int64_t b)
-{
-    uint64_t remainder = 0;
-    do_div_s(a, b, &remainder);
-    return remainder;
-}
-
-uint64_t __udivdi3(uint64_t a, uint64_t b)
-{
-    return do_div(a, b, NULL);
-}
-
-uint64_t __umoddi3(uint64_t a, uint64_t b)
-{
-    uint64_t rem = 0;
-    do_div(a, b, &rem);
-    return rem;
-}

+ 0 - 12
gblibc/src/assert.c

@@ -1,12 +0,0 @@
-#include <stdio.h>
-#include <unistd.h>
-
-_Noreturn void __attribute__((weak))
-__assert_fail(const char* statement, const char* file, int line, const char* func)
-{
-    char buf[256] = {};
-    int len = snprintf(buf, sizeof(buf), "Assertion failed: (%s) in %s:%d, %s\n",
-        statement, file, line, func);
-    write(STDERR_FILENO, buf, len);
-    _exit(-1);
-}

+ 0 - 35
gblibc/src/crt0.s

@@ -1,35 +0,0 @@
-.code32
-
-.text
-
-# TODO: call .init and .fini, initialize c standard library
-.globl _start
-.type  _start @function
-_start:
-    movl %esp, %ebx     # initial stack
-    andl $0xfffffff0, %esp
-    pushl $0
-    movl %esp, %ebp
-
-    movl (%ebx), %eax           # %eax = argc
-
-    leal 8(%ebx, %eax, 4), %ecx # %ecx = envp
-    pushl %ecx
-
-    leal 4(%ebx), %ecx          # %ecx = argv
-    pushl %ecx
-
-    pushl %eax
-
-    call __init_gblibc
-
-    movl (%ebx), %eax # %eax = argc
-    movl %eax, (%esp)
-    leal 4(%ebx), %eax
-    movl %eax, 4(%esp)
-
-    call main
-
-    movl %eax, %ebx  # code
-    movl $0xfc, %eax # SYS_exit_group
-    int $0x80        # syscall

+ 0 - 25
gblibc/src/ctype.c

@@ -1,25 +0,0 @@
-#include <ctype.h>
-
-int islower(int c)
-{
-    return c >= 'a' && c <= 'z';
-}
-
-int isupper(int c)
-{
-    return c >= 'A' && c <= 'Z';
-}
-
-int tolower(int c)
-{
-    if (isupper(c))
-        return c - 'A' + 'a';
-    return c;
-}
-
-int toupper(int c)
-{
-    if (islower(c))
-        return c - 'a' + 'A';
-    return c;
-}

+ 0 - 77
gblibc/src/dirent.c

@@ -1,77 +0,0 @@
-#include <errno.h>
-#include <fcntl.h>
-#include <dirent.h>
-#include <string.h>
-#include <syscall.h>
-
-DIR* opendir(const char* name)
-{
-    // TODO: set flags
-    int fd = open(name, O_DIRECTORY);
-
-    if (fd < 0)
-        return NULL;
-
-    return fdopendir(fd);
-}
-
-DIR* fdopendir(int fd)
-{
-    static DIR dirs[64];
-    static int next = 0;
-
-    dirs[next].fd = fd;
-    dirs[next].bpos = 0;
-
-    return dirs + next++;
-}
-
-struct kernel_dirent {
-    ino_t d_ino; // inode number
-    uint32_t d_off; // ignored
-    uint16_t d_reclen; // length of this struct user_dirent
-    char d_name[1]; // file name with a padding zero
-    // uint8_t d_type; // file type, with offset of (d_reclen - 1)
-};
-
-size_t fill_dirent(struct dirent* dent, char* buffer, size_t bpos)
-{
-    struct kernel_dirent* dp = (struct kernel_dirent*)(buffer + bpos);
-    dent->d_ino = dp->d_ino;
-    dent->d_off = dp->d_off;
-    dent->d_reclen = dp->d_reclen;
-    dent->d_type = buffer[bpos + dp->d_reclen - 1];
-    strncpy(dent->d_name, dp->d_name, sizeof(dent->d_name));
-    dent->d_name[sizeof(dent->d_name) - 1] = 0;
-
-    return bpos + dp->d_reclen;
-}
-
-struct dirent* readdir(DIR* dirp)
-{
-    if (dirp->bpos) {
-        if (dirp->bpos >= dirp->blen) {
-            dirp->bpos = 0;
-        } else {
-            goto fill;
-        }
-    }
-
-    dirp->blen = syscall3(SYS_getdents,
-        dirp->fd,
-        (uint32_t)dirp->buffer,
-        sizeof(dirp->buffer)
-    );
-
-    if (dirp->blen <= 0) {
-        if (dirp->blen < 0) {
-            errno = -dirp->blen;
-            dirp->blen = 0;
-        }
-        return NULL;
-    }
-
-fill:
-    dirp->bpos = fill_dirent(&dirp->dent, dirp->buffer, dirp->bpos);
-    return &dirp->dent;
-}

+ 0 - 37
gblibc/src/errno.c

@@ -1,37 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-int* __errno_location(void)
-{
-    static int __errno = 0;
-    return &__errno;
-}
-
-static size_t _strlen(const char* str)
-{
-    size_t len = 0;
-    while (str[len] != '\0') {
-        len++;
-    }
-    return len;
-}
-
-void
-__attribute__((noreturn))
-__attribute__((weak))
-__stack_chk_fail(void)
-{
-    const char* msg = "***** stack overflow detected *****\n"
-                      "quiting...\n";
-    write(STDERR_FILENO, msg, _strlen(msg));
-    exit(-1);
-}
-
-void
-__attribute__((noreturn))
-__attribute__((weak))
-__stack_chk_fail_local(void)
-{
-    __stack_chk_fail();
-}

+ 0 - 27
gblibc/src/fcntl.c

@@ -1,27 +0,0 @@
-#include <stdarg.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <syscall.h>
-
-#include <sys/types.h>
-
-int open(const char* filename, int flags, ...)
-{
-    int ret;
-    if (flags | O_CREAT) {
-        va_list vl;
-        va_start(vl, flags);
-
-        ret = syscall3(SYS_open, (uint32_t)filename, flags, va_arg(vl, int));
-
-        va_end(vl);
-    }
-    else
-        ret = syscall2(SYS_open, (uint32_t)filename, flags);
-
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}

+ 0 - 116
gblibc/src/init.c

@@ -1,116 +0,0 @@
-#include <assert.h>
-#include <priv-vars.h>
-#include <stdlib.h>
-#include <syscall.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <list.h>
-
-FILE* stdout;
-FILE* stdin;
-FILE* stderr;
-
-#define BYTES_PER_MAX_COPY_UNIT (sizeof(uint32_t) / sizeof(uint8_t))
-static void* _memset(void* _dst, int c, size_t n)
-{
-    uint8_t* dst = (uint8_t*)_dst;
-    c &= 0xff;
-    int cc = (c + (c << 8) + (c << 16) + (c << 24));
-    for (size_t i = 0; i < n / BYTES_PER_MAX_COPY_UNIT; ++i) {
-        *(uint32_t*)dst = cc;
-        dst += BYTES_PER_MAX_COPY_UNIT;
-    }
-    for (size_t i = 0; i < (n % BYTES_PER_MAX_COPY_UNIT); ++i) {
-        *((char*)dst++) = c;
-    }
-    return dst;
-}
-
-static char* strchr(const char* s, int c)
-{
-    while (*s) {
-        if (*s == c)
-            return (char*)s;
-        ++s;
-    }
-    return NULL;
-}
-
-list_head* __io_files_location(void)
-{
-    static list_head __io_files;
-    return &__io_files;
-}
-
-size_t* __environ_size_location(void)
-{
-    static size_t __environ_size;
-    return &__environ_size;
-}
-
-void __init_gblibc(int argc, char** argv, char** envp)
-{
-    (void)argc, (void)argv;
-    // initialize program break position and heap
-    start_brk = curr_brk = (void*)syscall1(SYS_brk, (uint32_t)NULL);
-
-    sbrk(128 * 1024);
-    struct mem* first = start_brk;
-    first->sz = 0;
-    first->flag = 0;
-
-    // save environ vector
-    environ_size = 4;
-    environ = malloc(environ_size * sizeof(char*));
-    assert(environ);
-
-    while (*envp) {
-        char* eqp = strchr(*envp, '=');
-        if (!eqp || eqp == *envp)
-            goto next;
-
-        *eqp = 0;
-        char* value = eqp + 1;
-        setenv(*envp, value, 1);
-
-    next:;
-        ++envp;
-    }
-
-    // stdout, stdin, stderr objects
-    list_node* node = NULL;
-
-    // stdout
-    node = NEWNODE(FILE);
-    stdout = &NDDATA(*node, FILE);
-    _memset(stdout, 0x00, sizeof(FILE));
-
-    stdout->fd = STDOUT_FILENO;
-    stdout->flags = FILE_WRITE;
-    stdout->wbuf = malloc(BUFSIZ);
-    stdout->wbsz = BUFSIZ;
-
-    NDINSERT(&iofiles, node);
-
-    // stdin
-    node = NEWNODE(FILE);
-    stdin = &NDDATA(*node, FILE);
-    _memset(stdin, 0x00, sizeof(FILE));
-
-    stdin->fd = STDIN_FILENO;
-    stdin->flags = FILE_READ;
-    stdin->rbuf = malloc(BUFSIZ);
-    stdin->rbsz = BUFSIZ;
-
-    NDINSERT(&iofiles, node);
-
-    // stderr
-    node = NEWNODE(FILE);
-    stderr = &NDDATA(*node, FILE);
-    _memset(stderr, 0x00, sizeof(FILE));
-
-    stderr->fd = STDERR_FILENO;
-    stderr->flags = FILE_WRITE;
-
-    NDINSERT(&iofiles, node);
-}

+ 0 - 20
gblibc/src/internal.c

@@ -1,20 +0,0 @@
-#include <list.h>
-#include <stdlib.h>
-
-void __node_insert(list_node* node, list_node* newnode)
-{
-    NDNEXT(*newnode) = NDNEXT(*node);
-    if (NDNEXT(*node))
-        NDPREV(*NDNEXT(*node)) = newnode;
-    NDNEXT(*node) = newnode;
-    NDPREV(*newnode) = node;
-}
-
-void __node_erase(list_node* node)
-{
-    if (NDPREV(*node))
-        NDNEXT(*NDPREV(*node)) = NDNEXT(*node);
-    if (NDNEXT(*node))
-        NDPREV(*NDNEXT(*node)) = NDPREV(*node);
-    free(node);
-}

+ 0 - 5
gblibc/src/platform-independent.s

@@ -1,5 +0,0 @@
-.section .rodata
-
-.globl __stack_chk_guard
-__stack_chk_guard:
-    .long 0x19198101

+ 0 - 23
gblibc/src/signal.c

@@ -1,23 +0,0 @@
-#include <syscall.h>
-#include <errno.h>
-#include <unistd.h>
-#include <signal.h>
-
-int kill(pid_t pid, int sig)
-{
-    int ret = syscall2(SYS_kill, pid, sig);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-int raise(int sig)
-{
-    pid_t pid = getpid();
-    if (pid < 0)
-        return -1;
-
-    return kill(pid, sig);
-}

+ 0 - 29
gblibc/src/stat.c

@@ -1,29 +0,0 @@
-#include <stdint.h>
-#include <errno.h>
-#include <syscall.h>
-#include <sys/stat.h>
-
-int stat(const char* pathname, struct stat* statbuf)
-{
-    int ret = syscall2(SYS_stat, (uint32_t)pathname, (uint32_t)statbuf);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-int fstat(int fd, struct stat* statbuf)
-{
-    int ret = syscall2(SYS_fstat, fd, (uint32_t)statbuf);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-mode_t umask(mode_t mask)
-{
-    return syscall1(SYS_umask, mask);
-}

+ 0 - 845
gblibc/src/stdio.c

@@ -1,845 +0,0 @@
-#include <assert.h>
-#include <devutil.h>
-#include <fcntl.h>
-#include <list.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <priv-vars.h>
-
-static inline int __feof_or_error(FILE* stream)
-{
-    return !!(stream->flags & (FILE_ERROR | FILE_EOF));
-}
-
-// where n is in the range of [0, 9]
-static inline char d_to_c(int32_t n)
-{
-    return '0' + n;
-}
-
-// where n is between 0 and 15
-// base is either 'a' of 'A',
-// depending on you want capitalized
-// or not
-static inline char hex_to_c(int32_t n, char base)
-{
-    if (n < 10) {
-        // n belongs to [0, 9]
-        return d_to_c(n);
-    } else {
-        // n belongs to [10, 15]
-        return base + (n - 10);
-    }
-}
-
-static inline char x_to_c(int32_t n)
-{
-    return hex_to_c(n, 'a');
-}
-
-static inline char X_to_c(int32_t n)
-{
-    return hex_to_c(n, 'A');
-}
-
-// this will check if there is still free space
-// in the buffer. if so, push the char into it,
-// change the value of buf_size and move pointer
-// forward
-//
-// x: char* buf
-// y: size_t buf_size
-// z: char c
-#define do_write_if_free(x, y, z) \
-    if ((y) > 1) {                \
-        *((x)++) = (z);           \
-        --(y);                    \
-    }
-
-static inline ssize_t
-snprint_decimal32(
-    char* buf,
-    size_t buf_size,
-    int32_t num)
-{
-    ssize_t n_write = 0;
-
-    if (num < 0) {
-        do_write_if_free(buf, buf_size, '-');
-        ++n_write;
-        num *= (-1);
-    }
-
-    char* orig_buf = buf;
-
-    do {
-        do_write_if_free(buf, buf_size, d_to_c(num % 10));
-        num /= 10;
-        ++n_write;
-    } while (num != 0);
-
-    // prepend trailing '\0'
-    if (buf_size > 0)
-        *buf = 0x00;
-
-    // move buf pointer to the last digit of number
-    --buf;
-
-    // reverse output
-    while (orig_buf < buf) {
-        char c = *buf;
-        *buf = *orig_buf;
-        *orig_buf = c;
-        --buf;
-        ++orig_buf;
-    }
-
-    return n_write;
-}
-
-static inline ssize_t
-snprint_decimal64(
-    char* buf,
-    size_t buf_size,
-    int64_t num)
-{
-    ssize_t n_write = 0;
-
-    if (num < 0) {
-        do_write_if_free(buf, buf_size, '-');
-        ++n_write;
-        num *= (-1);
-    }
-
-    char* orig_buf = buf;
-
-    do {
-        do_write_if_free(buf, buf_size, d_to_c(num % 10));
-        num /= 10;
-        ++n_write;
-    } while (num != 0);
-
-    // prepend trailing '\0'
-    if (buf_size > 0)
-        *buf = 0x00;
-
-    // move buf pointer to the last digit of number
-    --buf;
-
-    // reverse output
-    while (orig_buf < buf) {
-        char c = *buf;
-        *buf = *orig_buf;
-        *orig_buf = c;
-        --buf;
-        ++orig_buf;
-    }
-
-    return n_write;
-}
-
-static inline ssize_t
-snprint_hex32(
-    char* buf,
-    size_t buf_size,
-    uint32_t num,
-    int32_t capitalized)
-{
-    ssize_t n_write = 0;
-
-    do_write_if_free(buf, buf_size, '0');
-    if (capitalized) {
-        do_write_if_free(buf, buf_size, 'X');
-    } else {
-        do_write_if_free(buf, buf_size, 'x');
-    }
-    n_write += 2;
-
-    char* orig_buf = buf;
-
-    do {
-        if (capitalized) {
-            do_write_if_free(buf, buf_size, X_to_c(num % 16));
-        } else {
-            do_write_if_free(buf, buf_size, x_to_c(num % 16));
-        }
-        num /= 16;
-        ++n_write;
-    } while (num != 0);
-
-    // prepend trailing '\0'
-    if (buf_size > 0)
-        *buf = 0x00;
-
-    // move buf pointer to the last digit of number
-    --buf;
-
-    // reverse output
-    while (orig_buf < buf) {
-        char c = *buf;
-        *buf = *orig_buf;
-        *orig_buf = c;
-        --buf;
-        ++orig_buf;
-    }
-
-    return n_write;
-}
-
-static inline ssize_t
-snprint_hex64(
-    char* buf,
-    size_t buf_size,
-    uint64_t num,
-    int32_t capitalized)
-{
-    ssize_t n_write = 0;
-
-    do_write_if_free(buf, buf_size, '0');
-    if (capitalized) {
-        do_write_if_free(buf, buf_size, 'X');
-    } else {
-        do_write_if_free(buf, buf_size, 'x');
-    }
-    n_write += 2;
-
-    char* orig_buf = buf;
-
-    do {
-        if (capitalized) {
-            do_write_if_free(buf, buf_size, X_to_c(num % 16));
-        } else {
-            do_write_if_free(buf, buf_size, x_to_c(num % 16));
-        }
-        num /= 16;
-        ++n_write;
-    } while (num != 0);
-
-    // prepend trailing '\0'
-    if (buf_size > 0)
-        *buf = 0x00;
-
-    // move buf pointer to the last digit of number
-    --buf;
-
-    // reverse output
-    while (orig_buf < buf) {
-        char c = *buf;
-        *buf = *orig_buf;
-        *orig_buf = c;
-        --buf;
-        ++orig_buf;
-    }
-
-    return n_write;
-}
-
-static inline ssize_t
-snprint_char(
-    char* buf,
-    size_t buf_size,
-    char c)
-{
-    if (buf_size > 1)
-        *buf = c;
-    return sizeof(c);
-}
-
-int snprintf(char* buf, size_t bufsize, const char* fmt, ...)
-{
-    va_list lst;
-    va_start(lst, fmt);
-
-    int ret = vsnprintf(buf, bufsize, fmt, lst);
-
-    va_end(lst);
-
-    return ret;
-}
-
-int vsnprintf(char* buf, size_t buf_size, const char* fmt, va_list arg)
-{
-    ssize_t n_write = 0;
-
-    for (char c; (c = *fmt) != 0x00; ++fmt) {
-        if (c == '%') {
-            size_t n_tmp_write = 0;
-
-            switch (*(++fmt)) {
-
-            // int
-            case 'd':
-                n_tmp_write = snprint_decimal32(buf, buf_size, va_arg(arg, int));
-                break;
-
-            case 'x':
-                n_tmp_write = snprint_hex32(buf, buf_size, va_arg(arg, unsigned int), 0);
-                break;
-
-            case 'X':
-                n_tmp_write = snprint_hex32(buf, buf_size, va_arg(arg, unsigned int), 1);
-                break;
-
-            // long decimal
-            case 'l':
-                switch (*(++fmt)) {
-                // long long aka int64
-                case 'l':
-                    switch (*(++fmt)) {
-                    case 'd':
-                        n_tmp_write = snprint_decimal64(buf, buf_size, va_arg(arg, long long));
-                        break;
-                    case 'x':
-                        n_tmp_write = snprint_hex64(buf, buf_size, va_arg(arg, unsigned long long), 0);
-                        break;
-                    case 'X':
-                        n_tmp_write = snprint_hex64(buf, buf_size, va_arg(arg, unsigned long long), 1);
-                        break;
-                    }
-                    break;
-                // long int aka int32
-                case 'd':
-                    n_tmp_write = snprint_decimal32(buf, buf_size, va_arg(arg, long));
-                    break;
-                case 'x':
-                    n_tmp_write = snprint_hex32(buf, buf_size, va_arg(arg, unsigned long), 0);
-                    break;
-
-                case 'X':
-                    n_tmp_write = snprint_hex32(buf, buf_size, va_arg(arg, unsigned long), 1);
-                    break;
-                }
-                break;
-
-            // c string
-            case 's':
-                n_tmp_write = snprintf(buf, buf_size, va_arg(arg, const char*));
-                break;
-
-            // int8 char
-            case 'c':
-                n_tmp_write = snprint_char(buf, buf_size, va_arg(arg, int));
-                break;
-
-            // pointer
-            case 'p':
-#ifdef __32bit_system
-                n_tmp_write = snprint_hex32(buf, buf_size, va_arg(arg, size_t), 0);
-#else
-                n_tmp_write = snprint_hex64(buf, buf_size, va_arg(arg, size_t), 0);
-#endif
-                break;
-
-            default:
-                n_tmp_write = snprint_char(buf, buf_size, *(fmt - 1));
-                break;
-            }
-
-            n_write += n_tmp_write;
-            if (buf_size > 1) {
-                if (buf_size > n_tmp_write) {
-                    buf += n_tmp_write;
-                    buf_size -= n_tmp_write;
-                } else {
-                    // no enough space
-                    // shrink buf_size to one
-                    buf += (buf_size - 1);
-                    buf_size = 1;
-                }
-            }
-
-        } else {
-            ++n_write;
-            do_write_if_free(buf, buf_size, c);
-        }
-    }
-
-    if (buf_size > 0)
-        *buf = 0x00;
-
-    return n_write;
-}
-
-int sprintf(char* buf, const char* fmt, ...)
-{
-    va_list lst;
-    va_start(lst, fmt);
-
-    int ret = vsnprintf(buf, __SIZE_MAX__, fmt, lst);
-
-    va_end(lst);
-
-    return ret;
-}
-
-int puts(const char* str)
-{
-    return fputs(str, stdout);
-}
-
-char* gets(char* buf)
-{
-    int c, num = 0;
-    while ((c = getchar()) != EOF && c != '\n')
-        buf[num++] = c;
-    buf[num] = 0;
-
-    if (c == EOF)
-        return NULL;
-    return buf;
-}
-
-int vfprintf_u32(uint32_t num, FILE* stream)
-{
-    if (num <= 9) {
-        fputc(d_to_c(num), stream);
-        return 1;
-    }
-
-    int ret = vfprintf_u32(num / 10, stream);
-    fputc(d_to_c(num % 10), stream);
-    return ret + 1;
-}
-
-int vfprintf_d32(int32_t num, FILE* stream)
-{
-    if (num < 0) {
-        fputc('-', stream);
-        return vfprintf_u32(-num, stream) + 1;
-    }
-    return vfprintf_u32(num, stream);
-}
-
-int vfprintf_u64(uint64_t num, FILE* stream)
-{
-    if (num <= 9) {
-        fputc(d_to_c(num), stream);
-        return 1;
-    }
-
-    int ret = vfprintf_u64(num / 10, stream);
-    fputc(d_to_c(num % 10), stream);
-    return ret + 1;
-}
-
-int vfprintf_d64(int64_t num, FILE* stream)
-{
-    if (num < 0) {
-        fputc('-', stream);
-        return vfprintf_u64(-num, stream) + 1;
-    }
-    return vfprintf_u64(num, stream);
-}
-
-int vfprintf_x32(uint32_t num, int off, FILE* stream)
-{
-    // print leading 0x
-    if (off & 1) {
-        --off;
-        fputc('0', stream);
-        fputc('X' + off, stream);
-        return vfprintf_x32(num, off, stream) + 2;
-    }
-
-    if (num <= 15) {
-        fputc(X_to_c(num) + off, stream);
-        return 1;
-    }
-
-    int ret = vfprintf_x32(num >> 4, off, stream);
-    fputc(X_to_c(num & 0xf) + off, stream);
-    return ret + 1;
-}
-
-int vfprintf_x64(uint64_t num, int off, FILE* stream)
-{
-    // print leading 0x
-    if (off & 1) {
-        --off;
-        fputc('0', stream);
-        fputc('X' + off, stream);
-        return vfprintf_x64(num, off, stream) + 2;
-    }
-
-    if (num <= 15) {
-        fputc(X_to_c(num) + off, stream);
-        return 1;
-    }
-
-    int ret = vfprintf_x64(num >> 4, off, stream);
-    fputc(X_to_c(num & 0xf) + off, stream);
-    return ret + 1;
-}
-
-int vfprintf(FILE* stream, const char* fmt, va_list args)
-{
-    int n = 0;
-
-    for (char c = 0; (c = *fmt) != 0x00; ++fmt) {
-        if (c == '%') {
-            switch (*(++fmt)) {
-
-            // int
-            case 'd':
-                n += vfprintf_d32(va_arg(args, int), stream);
-                break;
-
-            case 'x':
-                n += vfprintf_x32(va_arg(args, unsigned int), 'a' - 'A' + 1, stream);
-                break;
-
-            case 'X':
-                n += vfprintf_x32(va_arg(args, unsigned int), 1, stream);
-                break;
-
-            // long decimal
-            case 'l':
-                switch (*(++fmt)) {
-                // long long aka int64
-                case 'l':
-                    switch (*(++fmt)) {
-                    case 'd':
-                        n += vfprintf_d64(va_arg(args, long long), stream);
-                        break;
-                    case 'x':
-                        n += vfprintf_x64(va_arg(args, unsigned long long), 'a' - 'A' + 1, stream);
-                        break;
-                    case 'X':
-                        n += vfprintf_x64(va_arg(args, unsigned long long), 'a' - 'A' + 1, stream);
-                        break;
-                    }
-                    break;
-                // long int aka int32
-                case 'd':
-                    n += vfprintf_d32(va_arg(args, int), stream);
-                    break;
-                case 'x':
-                    n += vfprintf_x32(va_arg(args, unsigned int), 'a' - 'A' + 1, stream);
-                    break;
-
-                case 'X':
-                    n += vfprintf_x32(va_arg(args, unsigned int), 1, stream);
-                    break;
-                }
-                break;
-
-            // c string
-            case 's':
-                n += fprintf(stream, va_arg(args, const char*));
-                break;
-
-            // int8 char
-            case 'c':
-                ++n;
-                fputc(va_arg(args, int), stream);
-                break;
-
-            // pointer
-            case 'p':
-#ifdef __32bit_system
-                n += vfprintf_x32(va_arg(args, size_t), 'a' - 'A' + 1, stream);
-#else
-                n += vfprintf_x64(va_arg(args, size_t), 'a' - 'A' + 1, stream);
-#endif
-                break;
-
-            default:
-                ++n;
-                fputc(*(fmt - 1), stream);
-                break;
-            }
-        } else {
-            ++n;
-            fputc(c, stream);
-        }
-    }
-
-    return n;
-}
-
-int fprintf(FILE* stream, const char* fmt, ...)
-{
-    va_list args;
-    va_start(args, fmt);
-
-    int ret = vfprintf(stream, fmt, args);
-
-    va_end(args);
-    return ret;
-}
-
-int vprintf(const char* fmt, va_list args)
-{
-    return vfprintf(stdout, fmt, args);
-}
-
-int printf(const char* fmt, ...)
-{
-    va_list args;
-    va_start(args, fmt);
-
-    int ret = vprintf(fmt, args);
-
-    va_end(args);
-    return ret;
-}
-
-int putchar(int c)
-{
-    fputc(c, stdout);
-    return c;
-}
-
-FILE* fopen(const char* path, const char* mode)
-{
-    uint32_t flags = 0, file_flags = 0;
-
-    if (strcmp(mode, "r") == 0)
-        flags = O_RDONLY, file_flags = FILE_READ;
-
-    if (strcmp(mode, "r+") == 0)
-        flags = O_RDWR, file_flags = FILE_READ | FILE_WRITE;
-
-    if (strcmp(mode, "w") == 0)
-        flags = O_WRONLY | O_CREAT | O_TRUNC, file_flags = FILE_WRITE;
-
-    if (strcmp(mode, "w+") == 0)
-        flags = O_RDWR | O_CREAT | O_TRUNC, file_flags = FILE_READ | FILE_WRITE;
-    
-    assert(flags);
-
-    int fd = open(path, flags, 0644);
-    if (fd < 0)
-        goto open_fail;
-    
-    FILE* file = malloc(sizeof(FILE));
-    if (!file)
-        goto file_malloc_fail;
-    
-    file->fd = fd;
-    file->flags = file_flags;
-
-    if (file_flags & FILE_READ) {
-        file->rbuf = malloc(BUFSIZ);
-        if (!file->rbuf)
-            goto rbuf_malloc_fail;
-        file->rbsz = BUFSIZ;
-    }
-
-    if (file_flags & FILE_WRITE) {
-        file->wbuf = malloc(BUFSIZ);
-        if (!file->wbuf)
-            goto wbuf_malloc_fail;
-        file->wbsz = BUFSIZ;
-    }
-
-    return file;
-
-wbuf_malloc_fail:
-    free(file->rbuf);
-
-rbuf_malloc_fail:
-    free(file);
-
-file_malloc_fail:
-    close(fd);
-
-open_fail:
-    return NULL;
-}
-
-int fflush(FILE* stream)
-{
-    if (__feof_or_error(stream))
-        return EOF;
-
-    if (stream->wbuf && stream->wpos) {
-        int ret = write(stream->fd, stream->wbuf, stream->wpos);
-        if (ret < 0) {
-            stream->flags |= FILE_ERROR;
-            return EOF;
-        }
-        if (ret == 0) {
-            stream->flags |= FILE_EOF;
-            return EOF;
-        }
-        stream->wpos = 0;
-    }
-
-    // TODO: call flush()
-
-    return 0;
-}
-
-int fclose(FILE* stream)
-{
-    if (fflush(stream) == EOF)
-        return EOF;
-    
-    free(stream->rbuf);
-    free(stream->wbuf);
-    stream->rbsz = 0;
-    stream->wbsz = 0;
-    
-    if (close(stream->fd) < 0)
-        return EOF;
-    
-    NDERASE(NDPTR(stream));
-    
-    return 0;
-}
-
-int fputc_unlocked(int c, FILE* stream)
-{
-    return putc_unlocked(c, stream);
-}
-
-int fputs_unlocked(const char* s, FILE* stream)
-{
-    // 1 is for the trailing '\n'
-    int len = 1;
-    for (const char* p = s; *p; ++p, ++len)
-        fputc_unlocked(*p, stream);
-    fputc_unlocked('\n', stream);
-    return len;
-}
-
-int fputc(int c, FILE* stream)
-{
-    // TODO: lock the stream
-    return putc_unlocked(c, stream);
-}
-
-int fputs(const char* s, FILE* stream)
-{
-    // TODO: lock the stream
-    return fputs_unlocked(s, stream);
-}
-
-static inline int __fillbuf(FILE* stream)
-{
-    if ((stream->rcnt = read(stream->fd, stream->rbuf, stream->rbsz)) >= 2147483648U) {
-        stream->rcnt = 0;
-        stream->flags |= FILE_ERROR;
-        return EOF;
-    }
-    if (stream->rcnt == 0) {
-        stream->flags |= FILE_EOF;
-        return EOF;
-    }
-    stream->rpos = 0;
-    return 0;
-}
-
-int getc_unlocked(FILE* stream)
-{
-    if (__feof_or_error(stream))
-        return EOF;
-
-    if (stream->rbuf) {
-        if (stream->rpos == stream->rcnt) {
-            if (__fillbuf(stream) < 0)
-                return EOF;
-        }
-        return stream->rbuf[stream->rpos++];
-    } else {
-        int c;
-        int ret = read(stream->fd, &c, 1);
-        if (ret < 0) {
-            stream->flags |= FILE_ERROR;
-            return EOF;
-        }
-        if (ret == 0) {
-            stream->flags |= FILE_EOF;
-            return EOF;
-        }
-        return c;
-    }
-}
-
-int putc_unlocked(int c, FILE* stream)
-{
-    if (__feof_or_error(stream))
-        return EOF;
-
-    if (stream->wbuf) {
-        stream->wbuf[stream->wpos++] = c;
-        if (stream->wpos == stream->wbsz || c == '\n')
-            if (fflush(stream) == EOF)
-                return EOF;
-    } else {
-        if (write(stream->fd, &c, 1) < 0) {
-            stream->flags |= FILE_ERROR;
-            return EOF;
-        }
-    }
-
-    return c;
-}
-
-int getchar(void)
-{
-    return fgetc(stdin);
-}
-
-int fgetc(FILE* stream)
-{
-    return getc_unlocked(stream);
-}
-
-int ferror(FILE* stream)
-{
-    // TODO: lock the stream
-    return ferror_unlocked(stream);
-}
-
-int ferror_unlocked(FILE* stream)
-{
-    return stream->flags & FILE_ERROR;
-}
-
-int feof(FILE* stream)
-{
-    return stream->flags & FILE_EOF;
-}
-
-void clearerr(FILE* stream)
-{
-    stream->flags &= ~FILE_ERROR;
-}
-
-int vasprintf(char** strp, const char* fmt, va_list args)
-{
-    // TODO: this is WAY TOO SLOWWWWWWWWW
-    int sz = 8, n;
-    char* buf = NULL;
-
-    do {
-        buf = realloc(buf, sz *= 2);
-        if (!buf)
-            return -1;
-        
-        n = vsnprintf(buf, sz, fmt, args);
-        if (sz > n)
-            break;
-    } while (1);
-    
-    *strp = buf;
-    return n;
-}
-
-int asprintf(char** strp, const char* fmt, ...)
-{
-    va_list lst;
-    va_start(lst, fmt);
-
-    int ret = vasprintf(strp, fmt, lst);
-
-    va_end(lst);
-
-    return ret;
-}

+ 0 - 286
gblibc/src/stdlib.c

@@ -1,286 +0,0 @@
-#include <alloca.h>
-#include <priv-vars.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <syscall.h>
-#include <unistd.h>
-#include <string.h>
-
-#define BYTES_PER_MAX_COPY_UNIT (sizeof(uint32_t) / sizeof(uint8_t))
-
-static void* _memcpy(void* _dst, const void* _src, size_t n)
-{
-    void* orig_dst = _dst;
-    uint8_t* dst = (uint8_t*)_dst;
-    const uint8_t* src = (const uint8_t*)_src;
-    for (size_t i = 0; i < n / BYTES_PER_MAX_COPY_UNIT; ++i) {
-        *(uint32_t*)dst = *(uint32_t*)src;
-        dst += BYTES_PER_MAX_COPY_UNIT;
-        src += BYTES_PER_MAX_COPY_UNIT;
-    }
-    for (size_t i = 0; i < (n % BYTES_PER_MAX_COPY_UNIT); ++i) {
-        *((char*)dst++) = *((char*)src++);
-    }
-    return orig_dst;
-}
-
-int atoi(const char* str)
-{
-    int ret = 0;
-    while (*str) {
-        ret *= 10;
-        ret += *str - '0';
-    }
-    return ret;
-}
-
-void __attribute__((noreturn)) exit(int status)
-{
-    syscall1(SYS_exit, status);
-    for (;;)
-        ;
-}
-
-#define MINIMUM_ALLOCATION_SIZE (8)
-#define MEM_ALLOCATED (1)
-
-static inline int _is_end(struct mem* p)
-{
-    return p->sz == 0;
-}
-
-static inline int _is_allocated(struct mem* p)
-{
-    return !!(p->flag & MEM_ALLOCATED);
-}
-
-static inline size_t _max(size_t a, size_t b)
-{
-    return a > b ? a : b;
-}
-
-static inline size_t _size(struct mem* from)
-{
-    if (!_is_end(from))
-        return from->sz;
-    
-    size_t sz = curr_brk - (void*)from;
-    if (sz < sizeof(struct mem))
-        return 0;
-
-    return sz - sizeof(struct mem);
-}
-
-static inline struct mem* _next(struct mem* p, size_t sz)
-{
-    return (void*)p + sizeof(struct mem) + sz;
-}
-
-static inline void _union(struct mem* p)
-{
-    if (_is_end(p))
-        return;
-
-    for (struct mem* next = _next(p, p->sz);
-        !(next->flag & MEM_ALLOCATED);
-        next = _next(p, p->sz)) {
-
-        if (_is_end(next)) {
-            p->sz = 0;
-            break;
-        }
-
-        p->sz += sizeof(struct mem);
-        p->sz += next->sz;
-    }
-}
-
-static inline void _cut_block(struct mem* p, size_t mem_size, size_t block_size)
-{
-    if (block_size >= mem_size + sizeof(struct mem) + MINIMUM_ALLOCATION_SIZE) {
-        p->sz = mem_size;
-
-        struct mem* next = _next(p, mem_size);
-        next->flag = 0;
-        next->sz = block_size - mem_size - sizeof(struct mem);
-    }
-}
-
-void* malloc(size_t size)
-{
-    if (size < MINIMUM_ALLOCATION_SIZE)
-        size = MINIMUM_ALLOCATION_SIZE;
-
-    struct mem* p = start_brk;
-    size_t sz = 0;
-    for (;; p = _next(p, p->sz)) {
-        if (_is_allocated(p))
-            continue;
-
-        _union(p);
-
-        sz = _size(p);
-        if (_is_end(p)) {
-            if (sz < size + sizeof(struct mem))
-                sbrk(_max(128 * 1024, size + sizeof(struct mem)));
-
-            sz = p->sz = size;
-            struct mem* next = _next(p, size);
-            next->flag = 0;
-            next->sz = 0;
-
-            break;
-        }
-
-        if (sz >= size)
-            break;
-    }
-
-    p->flag |= MEM_ALLOCATED;
-    _cut_block(p, size, sz);
-
-    return _next(p, 0);
-}
-
-void* realloc(void* ptr, size_t newsize)
-{
-    if (!ptr)
-        return malloc(newsize);
-
-    struct mem* p = ptr - sizeof(struct mem);
-    size_t oldsize = p->sz;
-
-    _union(p);
-    if (_is_end(p)) {
-        if (_size(p) < newsize + sizeof(struct mem))
-            sbrk(_max(128 * 1024, newsize + sizeof(struct mem)));
-
-        p->sz = newsize;
-        struct mem* next = _next(p, newsize);
-        next->flag = 0;
-        next->sz = 0;
-
-        return ptr;
-    }
-
-    if (p->sz >= newsize) {
-        _cut_block(p, newsize, p->sz);
-        return ptr;
-    }
-
-    void* newptr = malloc(newsize);
-    if (!newptr)
-        return NULL;
-    
-    _memcpy(newptr, ptr, oldsize);
-    free(ptr);
-    return newptr;
-}
-
-void free(void* ptr)
-{
-    struct mem* p = ptr - sizeof(struct mem);
-    p->flag &= ~MEM_ALLOCATED;
-    _union(p);
-}
-
-static inline void _swap(void* a, void* b, size_t sz)
-{
-    void* tmp = alloca(sz);
-    _memcpy(tmp, a, sz);
-    _memcpy(a, b, sz);
-    _memcpy(b, tmp, sz);
-}
-
-void qsort(void* arr, size_t len, size_t sz, comparator_t cmp) {
-    if (len <= 1)
-        return;
-
-    char* pivot = alloca(sz);
-    _memcpy(pivot, arr + sz * (rand() % len), sz);
-
-    int i = 0, j = 0, k = len;
-    while (i < k) {
-        int res = cmp(arr + sz * i, pivot);
-        if (res < 0)
-            _swap(arr + sz * i++, arr + sz * j++, sz);
-        else if (res > 0)
-            _swap(arr + sz * i, arr + sz * --k, sz);
-        else
-            i++;
-    }
-
-    qsort(arr, j, sz, cmp);
-    qsort(arr + sz * k, len - k, sz, cmp);
-}
-
-static unsigned int __next_rand;
-int rand(void)
-{
-    return rand_r(&__next_rand);
-}
-
-int rand_r(unsigned int* seedp)
-{
-    *seedp = *seedp * 1103515245 + 12345;
-    return (unsigned int) (*seedp / 65536) % 32768;
-}
-
-void srand(unsigned int seed)
-{
-    __next_rand = seed;
-    rand();
-}
-
-void* bsearch(const void* key, const void* base, size_t num, size_t size, comparator_t cmp)
-{
-    if (num == 0)
-        return NULL;
-
-    size_t mid = num / 2;
-    int result = cmp(key, base + size * mid);
-
-    if (result == 0)
-        return (void*)base + size * mid;
-    
-    if (result > 0) {
-        ++mid;
-        return bsearch(key, base + size * mid, num - mid, size, cmp);
-    }
-    
-    return bsearch(key, base, mid, size, cmp);
-}
-
-int setenv(const char* name, const char* value, int overwrite)
-{
-    size_t i = 0;
-    for (; environ[i]; ++i) {
-        char* eqpos = strchr(environ[i], '=');
-        if (strncmp(name, environ[i], eqpos - environ[i]) == 0) {
-            if (overwrite)
-                goto fill_p;
-            return 0;
-        }
-    }
-
-    if (i + 2 == environ_size) {
-        environ_size *= 2;
-        char** newarr = malloc(environ_size * sizeof(char*));
-        if (!newarr)
-            return -1;
-        
-        _memcpy(newarr, environ, sizeof(char*) * environ_size / 2);
-        free(environ);
-        environ = newarr;
-    }
-    environ[i + 1] = NULL;
-
-fill_p:;
-    char* newenv = NULL;
-    if (asprintf(&newenv, "%s=%s", name, value) < 0)
-        return -1;
-
-    environ[i] = newenv;
-    return 0;
-}

+ 0 - 269
gblibc/src/string.c

@@ -1,269 +0,0 @@
-#include <ctype.h>
-#include <errno.h>
-#include <signal.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-#define BYTES_PER_MAX_COPY_UNIT (sizeof(uint32_t) / sizeof(uint8_t))
-
-static void* _memcpy(void* _dst, const void* _src, size_t n)
-{
-    void* orig_dst = _dst;
-    uint8_t* dst = (uint8_t*)_dst;
-    const uint8_t* src = (const uint8_t*)_src;
-    for (size_t i = 0; i < n / BYTES_PER_MAX_COPY_UNIT; ++i) {
-        *(uint32_t*)dst = *(uint32_t*)src;
-        dst += BYTES_PER_MAX_COPY_UNIT;
-        src += BYTES_PER_MAX_COPY_UNIT;
-    }
-    for (size_t i = 0; i < (n % BYTES_PER_MAX_COPY_UNIT); ++i) {
-        *((char*)dst++) = *((char*)src++);
-    }
-    return orig_dst;
-}
-
-static void* _memset(void* _dst, int c, size_t n)
-{
-    uint8_t* dst = (uint8_t*)_dst;
-    c &= 0xff;
-    int cc = (c + (c << 8) + (c << 16) + (c << 24));
-    for (size_t i = 0; i < n / BYTES_PER_MAX_COPY_UNIT; ++i) {
-        *(uint32_t*)dst = cc;
-        dst += BYTES_PER_MAX_COPY_UNIT;
-    }
-    for (size_t i = 0; i < (n % BYTES_PER_MAX_COPY_UNIT); ++i) {
-        *((char*)dst++) = c;
-    }
-    return dst;
-}
-
-static size_t _strlen(const char* str)
-{
-    size_t n = 0;
-    while (*(str++) != '\0')
-        ++n;
-    return n;
-}
-
-char* strchr(const char* str, int c)
-{
-    const char* p = str;
-    while (*p) {
-        if (*p == c)
-            return (char*)p;
-        ++p;
-    }
-    return NULL;
-}
-
-char* strrchr(const char* str, int c)
-{
-    const char* p = str + _strlen(str) - 1;
-    while (p >= str) {
-        if (*p == c)
-            return (char*)p;
-        --p;
-    }
-    return NULL;
-}
-
-char* strchrnul(const char* str, int c)
-{
-    char* ret = strchr(str, c);
-    if (ret)
-        return ret;
-    return (char*)str + _strlen(str);
-}
-
-char* strcpy(char* dst, const char* src)
-{
-    return _memcpy(dst, src, _strlen(src) + 1);
-}
-
-char* strncpy(char* dst, const char* src, size_t n)
-{
-    size_t len = _strlen(src);
-
-    if (len < n) {
-        _memset(dst + len, 0x00, n - len);
-        _memcpy(dst, src, len);
-    } else {
-        _memcpy(dst, src, n);
-    }
-
-    return dst;
-}
-
-char* stpcpy(char* restrict dst, const char* restrict src)
-{
-    return _memcpy(dst, src, _strlen(src) + 1) + _strlen(src);
-}
-
-char* stpncpy(char* restrict dst, const char* restrict src, size_t n)
-{
-    size_t len = _strlen(src);
-
-    if (len < n) {
-        _memset(dst + len, 0x00, n - len);
-        _memcpy(dst, src, len);
-    } else {
-        _memcpy(dst, src, n);
-    }
-
-    return dst + len;
-}
-
-int strncmp(const char* s1, const char* s2, size_t n)
-{
-    if (n == 0)
-        return 0;
-
-    int c;
-    while (n-- && (c = *s1 - *s2) == 0 && *s1) {
-        ++s1;
-        ++s2;
-    }
-    return c;
-}
-
-int strcmp(const char* s1, const char* s2)
-{
-    return strncmp(s1, s2, __SIZE_MAX__);
-}
-
-int strncasecmp(const char* s1, const char* s2, size_t n)
-{
-    if (n == 0)
-        return 0;
-
-    int c;
-    while (n-- && (c = tolower(*s1) - tolower(*s2)) == 0 && *s1) {
-        ++s1;
-        ++s2;
-    }
-    return c;
-}
-
-int strcasecmp(const char* s1, const char* s2)
-{
-    return strncasecmp(s1, s2, __SIZE_MAX__);
-}
-
-size_t strcspn(const char* str1, const char* str2)
-{
-    size_t ret = 0;
-    while (*str1) {
-        ++ret;
-        for (const char* p = str2; *p; ++p) {
-            if (*str1 == *p)
-                return ret;
-        }
-        ++str1;
-    }
-    return ret;
-}
-
-char* strstr(const char* str1, const char* str2)
-{
-    const char* p = str1;
-
-    while (*p) {
-        if (*p != *str2) {
-            ++p;
-            continue;
-        }
-
-        const char* p1 = p;
-        const char* q = str2;
-        while (*q) {
-            if (*p1 != *q)
-                break;
-            ++p1;
-            ++q;
-        }
-        if (!*q)
-            break;
-        p = p1;
-    }
-
-    if (*p)
-        return (char*)p;
-    return NULL;
-}
-
-char* strpbrk(const char* str1, const char* str2)
-{
-    size_t n = strcspn(str1, str2);
-    if (str1[n])
-        return (char*)str1 + n;
-    return NULL;
-}
-
-char* strerror(int errnum)
-{
-    switch (errnum) {
-    case EPERM:
-        return "Operation not permitted";
-    case ENOENT:
-        return "No such file or directory";
-    case ESRCH:
-        return "No such process";
-    case EINTR:
-        return "Interrupted system call";
-    case EBADF:
-        return "Bad file descriptor";
-    case ECHILD:
-        return "No child process";
-    case ENOMEM:
-        return "Out of memory";
-    case EEXIST:
-        return "File exists";
-    case ENOTDIR:
-        return "Not a directory";
-    case EISDIR:
-        return "Is a directory";
-    case EINVAL:
-        return "Invalid argument";
-    case ENOTTY:
-        return "Not a tty";
-    case EPIPE:
-        return "Broken pipe";
-    default:
-        return "No error information";
-    }
-}
-
-char* strndup(const char* str, size_t n)
-{
-    size_t len = _strlen(str);
-    if (len > n)
-        len = n;
-    char* ret = malloc(len + 1);
-    if (!ret)
-        return NULL;
-    
-    _memcpy(ret, str, len);
-    ret[len] = 0;
-    return ret;
-}
-
-char* strdup(const char* str)
-{
-    return strndup(str, __SIZE_MAX__);
-}
-
-char* strsignal(int sig)
-{
-    switch (sig) {
-    default:
-        return "Unknown signal";
-    case SIGINT:
-        return "Interrupt";
-    case SIGQUIT:
-        return "Quit";
-    case SIGSTOP:
-        return "Stopped (signal)";
-    case SIGPIPE:
-        return "Broken pipe";
-    }
-}

+ 0 - 20
gblibc/src/time.c

@@ -1,20 +0,0 @@
-#include <errno.h>
-#include <sys/time.h>
-#include <syscall.h>
-
-int gettimeofday(struct timeval* tv, struct timezone* tz)
-{
-    if (tz) {
-        errno = -EINVAL;
-        return -1;
-    }
-
-    int ret = syscall2(SYS_gettimeofday, (uint32_t)tv, 0);
-
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-
-    return ret;
-}

+ 0 - 249
gblibc/src/unistd.c

@@ -1,249 +0,0 @@
-#include <errno.h>
-#include <priv-vars.h>
-#include <stdarg.h>
-#include <stdint.h>
-#include <sys/ioctl.h>
-#include <unistd.h>
-#include <syscall.h>
-
-ssize_t read(int fd, void* buf, size_t count)
-{
-    ssize_t ret = syscall3(SYS_read, fd, (uint32_t)buf, count);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-ssize_t write(int fd, const void* buf, size_t count)
-{
-    ssize_t ret = syscall3(SYS_write, fd, (uint32_t)buf, count);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-int dup(int oldfd)
-{
-    int ret = syscall1(SYS_dup, oldfd);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-int dup2(int oldfd, int newfd)
-{
-    int ret = syscall2(SYS_dup2, oldfd, newfd);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-int pipe(int pipefd[2])
-{
-    int ret = syscall1(SYS_pipe, (uint32_t)pipefd);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-int close(int fd)
-{
-    int ret = syscall1(SYS_close, fd);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-_Noreturn void _exit(int code)
-{
-    (void)syscall1(SYS_exit, code);
-    // if syscall failed
-    for (;;);
-}
-
-pid_t fork(void)
-{
-    pid_t ret = syscall0(SYS_fork);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-int execve(const char* pathname, char* const argv[], char* const envp[])
-{
-    int ret = syscall3(SYS_execve, (uint32_t)pathname, (uint32_t)argv, (uint32_t)envp);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-// unsigned int sleep(unsigned int seconds)
-// {
-//     return syscall1(SYS_sleep, seconds);
-// }
-
-int chdir(const char* path)
-{
-    int ret = syscall1(SYS_chdir, (uint32_t)path);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-char* getcwd(char* buf, size_t bufsize)
-{
-    return (char*)syscall2(SYS_getcwd, (uint32_t)buf, bufsize);
-}
-
-pid_t getpid(void)
-{
-    pid_t ret = syscall0(SYS_getpid);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-pid_t getppid(void)
-{
-    pid_t ret = syscall0(SYS_getppid);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-int setpgid(pid_t pid, pid_t pgid)
-{
-    int ret = syscall2(SYS_setpgid, pid, pgid);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-pid_t setsid(void)
-{
-    pid_t ret = syscall0(SYS_setsid);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-pid_t getsid(pid_t pid)
-{
-    pid_t ret = syscall1(SYS_getsid, pid);
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-    return ret;
-}
-
-pid_t tcgetpgrp(int fd)
-{
-    pid_t pgrp;
-    return ioctl(fd, TIOCGPGRP, &pgrp);
-}
-
-int tcsetpgrp(int fd, pid_t pgrp)
-{
-    return ioctl(fd, TIOCSPGRP, &pgrp);
-}
-
-int ioctl(int fd, unsigned long request, ...)
-{
-    int ret = -EINVAL;
-
-    va_list args;
-    va_start(args, request);
-
-    switch (request) {
-    case TIOCGPGRP:
-        ret = syscall3(SYS_ioctl, fd, request, va_arg(args, uint32_t));
-        break;
-    case TIOCSPGRP:
-        ret = syscall3(SYS_ioctl, fd, request, va_arg(args, uint32_t));
-        break;
-    default:
-        break;
-    }
-
-    va_end(args);
-
-    if (ret < 0) {
-        errno = -ret;
-        return -1;
-    }
-
-    return ret;
-}
-
-static inline void* _sys_brk(void* addr)
-{
-    return (void*)syscall1(SYS_brk, (uint32_t)addr);
-}
-
-void** __start_brk_location(void)
-{
-    static void* __start_brk = NULL;
-    return &__start_brk;
-}
-void** __curr_brk_location(void)
-{
-    static void* __curr_brk = NULL;
-    return &__curr_brk;
-}
-
-int brk(void* addr)
-{
-    void* new_brk = _sys_brk(addr);
-    if (new_brk == curr_brk) {
-        errno = 0;
-        return -1;
-    }
-
-    if (new_brk != addr) {
-        errno = ENOMEM;
-        return -1;
-    }
-
-    return 0;
-}
-
-void* sbrk(ssize_t increment)
-{
-    if (brk(curr_brk + increment) == 0)
-        return curr_brk += increment;
-    return (void*)-1;
-}
-
-int isatty(int fd)
-{
-    return tcgetpgrp(fd) != -1;
-}
-
-char** environ;

+ 0 - 12
gblibc/src/wait.c

@@ -1,12 +0,0 @@
-#include <sys/wait.h>
-#include <syscall.h>
-
-pid_t waitpid(pid_t pid, int* code, int options)
-{
-    return syscall3(SYS_waitpid, (uint32_t)pid, (uint32_t)code, (uint32_t)options);
-}
-
-pid_t wait(int* code)
-{
-    return waitpid(-1, code, 0);
-}

+ 0 - 341
pretty-print.py

@@ -5,17 +5,6 @@ from gdb.FrameDecorator import FrameDecorator
 import re
 from os import environ
 
-def parseCompressedPairElement(elem: gdb.Value) -> gdb.Value:
-    return elem[elem.type.fields()[0]]
-
-def parseCompressedPair(cpair: gdb.Value) -> tuple[gdb.Value, gdb.Value]:
-    fields = cpair.type.fields()
-
-    first = cpair[fields[0]]
-    second = cpair[fields[1]]
-
-    return parseCompressedPairElement(first), parseCompressedPairElement(second)
-
 def delegateChildren(val: gdb.Value):
     try:
         for field in val.type.fields():
@@ -33,291 +22,6 @@ def delegateToString(val: gdb.Value):
     except:
         return val
 
-class vectorPrinter:
-    class _iterator:
-        def __init__(self, item, end, idx):
-            self.item = item
-            self.end = end
-            self.size = self.end - self.item
-            self.idx = idx
-
-        def __iter__(self):
-            return self
-
-        def __next__(self):
-            if self.item >= self.end:
-                raise StopIteration
-            key = str(self.idx)
-            iter = self.item.dereference()
-            self.item += 1
-            self.idx += 1
-            return key, iter
-
-    def __init__(self, val):
-        self.val = val
-
-    def to_string(self):
-        return "std::vector of size %d, capacity %d" % (self.val['m_size'], self.val['m_capacity'])
-
-    def display_hint(self):
-        return 'array'
-
-    def children(self):
-        if self.val['m_size'] == 0:
-            return []
-        data, alloc = parseCompressedPair(self.val['m_data'])
-        return self._iterator(data, data + self.val['m_size'], 0)
-
-def _leftmost(node):
-    ret = node
-    while ret['left'] != 0:
-        ret = ret['left'].dereference()
-    return ret
-
-def _next(node):
-    if node['right']:
-        return _leftmost(node['right'].dereference())
-    else:
-        if node['parent'] == 0:
-            return None
-        parent = node['parent'].dereference()
-        if parent['left'] == node.address:
-            return parent
-        ret = node
-        while True:
-            ret = ret['parent'].dereference()
-            if ret['parent'] == 0:
-                return None
-            if ret['parent'].dereference()['left'] == ret.address:
-                break
-        return ret['parent'].dereference()
-
-class rbtreePrinter:
-    def __init__(self, type, val):
-        self.type: gdb.Type = type
-        self.val: gdb.Value = val['tree']
-
-    def to_string(self):
-        return "%s of size %d" % (self.type, self.num_children())
-
-    def display_hint(self):
-        return 'array'
-
-    def num_children(self):
-        size, _ = parseCompressedPair(self.val['size_data'])
-        return size
-
-    def children(self):
-        root, alloc = parseCompressedPair(self.val['root_data'])
-        size, comp = parseCompressedPair(self.val['size_data'])
-
-        # yield '[alloc]', alloc
-        # yield '[comp]', comp
-        # yield '[root]', root
-        if root == 0:
-            return
-
-        nd = _leftmost(root.dereference())
-        for i in range(size):
-            yield str(i), nd['value']
-            nd = _next(nd)
-            if nd == None:
-                break
-
-class stringPrinter:
-    def __init__(self, val: gdb.Value):
-        self.val = val
-
-    def to_string(self):
-        data, alloc = parseCompressedPair(self.val['m_data'])
-        data = data['in']
-
-        if data['stackdata']['end'] == 0:
-            return data['stackdata']['str'].string()
-        return data['heapdata']['m_ptr'].string()
-
-    def display_hint(self):
-        return 'string'
-
-class stringViewPrinter:
-    def __init__(self, val: gdb.Value):
-        self.val = val
-        self.string = val['m_str']
-        self.length = val['m_len']
-
-    def to_string(self):
-        return self.string.string(length=self.length)
-
-    def display_hint(self):
-        return 'string'
-
-class listPrinter:
-    def __init__(self, val):
-        self.val: gdb.Value = val
-        self.type: gdb.Type = val.type
-
-        this_type = self.type.unqualified().strip_typedefs()
-        if this_type.tag == None:
-            this_type = this_type.target()
-
-        self.value_node_type = gdb.lookup_type(this_type.tag + '::node').pointer()
-
-    def to_string(self):
-        size, alloc = parseCompressedPair(self.val['m_pair'])
-        return 'std::list of size %d' % size
-
-    def display_hint(self):
-        return 'array'
-
-    def num_children(self):
-        size, alloc = parseCompressedPair(self.val['m_pair'])
-        return size
-
-    def children(self):
-        head = self.val['m_head']
-
-        node = head['next']
-        idx = 0
-        while node != head.address:
-            nodeval = node.reinterpret_cast(self.value_node_type)
-            yield str(idx), nodeval['value']
-            idx += 1
-            node = node['next']
-
-class listIteratorPrinter:
-    def __init__(self, val):
-        self.val = val
-
-        this_type: gdb.Type = val.type
-        this_type = this_type.unqualified().strip_typedefs()
-
-        if this_type.tag == None:
-            this_type = this_type.target()
-
-        type_tag: str = this_type.tag
-        type_tag = type_tag[:type_tag.rfind('::')]
-
-        self.value_node_type = gdb.lookup_type(type_tag + '::node').pointer()
-
-    def children(self):
-        yield 'addr', self.val['p']
-        if self.val['p'] == 0:
-            return
-
-        nodeptr = self.val['p'].cast(self.value_node_type)
-
-        yield 'value', nodeptr['value']
-
-class rbtreeIteratorPrinter:
-    def __init__(self, val):
-        self.val = val
-
-    def children(self):
-        yield 'addr', self.val['p']
-        if self.val['p'] == 0:
-            return
-
-        yield 'value', self.val['p']['value']
-
-class vectorIteratorPrinter:
-    def __init__(self, val):
-        self.val = val
-
-    def children(self):
-        yield 'value', self.val['m_ptr'].dereference()
-
-class pairPrinter:
-    def __init__(self, val):
-        self.val = val
-
-    def children(self):
-        yield 'first', self.val['first']
-        yield 'second', self.val['second']
-
-class tuplePrinter:
-    def __init__(self, val):
-        self.val = val
-
-    def children(self):
-        i = 0
-        try:
-            cur = self.val
-            while True:
-                yield '<%d>' % i, cur['val']
-                i += 1
-                cur = cur['next']
-        except Exception:
-            if i == 0:
-                yield 'tuple of size 0', ''
-
-class functionPrinter:
-    def __init__(self, val: gdb.Value):
-        self.val = val
-
-    def to_string(self):
-        return self.val.type.name
-
-class referenceWrapperPrinter:
-    def __init__(self, val):
-        self.val = val
-
-    def to_string(self):
-        return "std::reference_wrapper to %x" % self.val['_ptr']
-
-    def children(self):
-        yield 'addr', self.val['_ptr'].cast(gdb.lookup_type('void').pointer())
-        yield 'reference', self.val['_ptr']
-
-class sharedPointerPrinter:
-    def __init__(self, val: gdb.Value):
-        self.val = val
-        self.pointer = val['ptr']
-        self.controlBlock = val['cb']
-
-    def to_string(self):
-        if self.pointer == 0:
-            return 'nullptr of %s' % self.val.type.name
-
-        refCount = self.controlBlock['ref_count']
-        weakCount = self.controlBlock['weak_count']
-        realPointer = self.controlBlock['ptr']
-        return '%s to 0x%x, ref(%d), wref(%d), cb(0x%x), memp(0x%x)' % (
-                self.val.type.name,
-                self.pointer,
-                refCount,
-                weakCount,
-                self.controlBlock,
-                realPointer)
-
-    def children(self):
-        if self.pointer == 0:
-            return []
-
-        content = self.pointer.dereference()
-        return delegateChildren(content)
-
-class uniquePointerPrinter:
-    def __init__(self, val: gdb.Value):
-        self.val = val
-        self.data = val['data']
-
-    def to_string(self):
-        pointer, deleter = parseCompressedPair(self.data)
-        if pointer == 0:
-            return 'nullptr of %s' % self.val.type.name
-
-        return "%s to 0x%x" % (self.val.type.name, pointer)
-
-    def children(self):
-        pointer, deleter = parseCompressedPair(self.data)
-        yield '[deleter]', deleter
-
-        if pointer == 0:
-            return
-
-        for item in delegateChildren(pointer.dereference()):
-            yield item
-
 class NonNull:
     def __init__(self, val: gdb.Value):
         pointer = val['pointer']
@@ -453,51 +157,6 @@ def build_pretty_printer(val: gdb.Value):
     if typename == None:
         return None
 
-    if re.compile(r"^std::pair<.*, .*>$").match(typename):
-        return pairPrinter(val)
-
-    if re.compile(r"^std::tuple<.*>$").match(typename):
-        return tuplePrinter(val)
-
-    if re.compile(r"^std::function<.*>$").match(typename):
-        return functionPrinter(val)
-
-    if re.compile(r"^std::reference_wrapper<.*>$").match(typename):
-        return referenceWrapperPrinter(val)
-
-    if re.compile(r"^std::list<.*, .*>::_iterator<.*?>$").match(typename):
-        return listIteratorPrinter(val)
-
-    if re.compile(r"^std::vector<.*, .*>::_iterator<.*?>$").match(typename):
-        return vectorIteratorPrinter(val)
-
-    if re.compile(r"^std::list<.*, .*>$").match(typename):
-        return listPrinter(val)
-
-    if re.compile(r"^std::vector<.*, .*>$").match(typename):
-        return vectorPrinter(val)
-
-    if re.compile(r"^std::map<.*, .*, .*, .*>$").match(typename):
-        return rbtreePrinter("std::map", val)
-
-    if re.compile(r"^std::set<.*, .*, .*>$").match(typename):
-        return rbtreePrinter("std::set", val)
-
-    if re.compile(r"^std::impl::rbtree<.*, .*, .*>::_iterator<.*?>$").match(typename):
-        return rbtreeIteratorPrinter(val)
-
-    if re.compile(r"^std::basic_string<.*>$").match(typename):
-        return stringPrinter(val)
-
-    if re.compile(r"^types::string_view$").match(typename):
-        return stringViewPrinter(val)
-
-    if re.compile(r"^std::shared_ptr<.*>$").match(typename):
-        return sharedPointerPrinter(val)
-
-    if re.compile(r"^std::unique_ptr<.*>$").match(typename):
-        return uniquePointerPrinter(val)
-
     if re.compile(r"^.*::_access_[a-zA-Z0-9_]*$").match(typename):
         return ThreadLocalPrinter(val)
 

+ 0 - 3
rust-headers.hpp

@@ -1,3 +0,0 @@
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/stat.h>

+ 4 - 7
script/build-img.sh

@@ -16,13 +16,10 @@ else
     $SUDO mount /dev/loop2 build/mnt
 fi
 
-$SUDO cp build/user-space-program/hello-world.out build/mnt/hello
-$SUDO cp build/user-space-program/interrupt-test.out build/mnt/int
-$SUDO cp build/user-space-program/stack-test.out build/mnt/stack
-$SUDO cp build/user-space-program/init.out build/mnt/init
-$SUDO cp build/user-space-program/priv-test.out build/mnt/priv
-$SUDO cp ./busybox build/mnt/busybox
-$SUDO cp ./busybox-minimal build/mnt/busybox_
+$SUDO cp ./user-programs/init.out build/mnt/init
+$SUDO cp ./user-programs/int.out build/mnt/int
+$SUDO cp ./user-programs/busybox build/mnt/busybox
+$SUDO cp ./user-programs/busybox-minimal build/mnt/busybox_
 $SUDO cp ./init_script.sh build/mnt/initsh
 
 # Add your custom files here

+ 0 - 232
src/kernel.ld

@@ -1,232 +0,0 @@
-OUTPUT_FORMAT(elf64-x86-64)
-
-MEMORY
-{
-    LOWDATA       (wx) : org = 0x0500, l = 9 * 256
-    MBR           (wx) : org = 0x0e00, l = 512
-    PAGETABLES    (wx) : org = 0x1000, l = 6 * 4K
-    STAGE1        (wx) : org = 0x7000, l = 4K
-    PHYMEM        (w)  : org = 0xffffff0000000000, len = 512 * 1024M
-    PARRAY        (w)  : org = 0xffffff8000000000, len = 128 * 1024M
-    KBSS          (w)  : org = 0xffffffffc0200000, len = 2M
-    KIMAGE        (wx) : org = 0xffffffffffc00000, len = 2M
-    KPERCPU       (w)  : org = 0x0000000000000000, len = 128K
-}
-
-SECTIONS
-{
-    .low (NOLOAD) :
-    {
-        . += 8; /* skip 0x0 address */
-
-        EARLY_GDT = .;
-        . += 8; /* null descriptor */
-        . += 8; /* 64bit code descriptor */
-        . += 8; /* 64bit data descriptor */
-        . += 8; /* 32bit code descriptor */
-        . += 8; /* 32bit data descriptor */
-        . += 8; /* 16bit code descriptor */
-        . += 8; /* 16bit data descriptor */
-
-        . = ALIGN(16);
-        . += 2;
-        EARLY_GDT_DESCRIPTOR = .;
-
-        . += 6; /* size and base */
-
-        . = ALIGN(16);
-        . += 2;
-        BIOS_IDT_DESCRIPTOR = .;
-
-        . += 6; /* size and base */
-
-        . = ALIGN(16);
-        E820_MEM_MAP_DATA = .;
-
-        . += 1024;
-    } > LOWDATA
-
-    .mbr : AT(0)
-    {
-        KEEP(*(.mbr));
-
-        . = 446; /* avoid the MBR being overwritten */
-
-        . = 510;
-        BYTE(0x55);
-        BYTE(0xaa);
-    } > MBR
-
-    .stage1 : AT(LOADADDR(.mbr) + SIZEOF(.mbr))
-    {
-        KEEP(*(.stage1.smp));
-
-        . = ALIGN(16);
-        *(.stage1)
-
-        . = ALIGN(0x1000);
-    } > STAGE1
-
-    .text :
-        AT(LOADADDR(.stage1) + SIZEOF(.stage1))
-    {
-        TEXT_START = .;
-        *(.text)
-        *(.text*)
-        KEEP(*(.syscall_fns*))
-
-        . = ALIGN(0x1000);
-        TEXT_END = .;
-    } > KIMAGE
-
-    TEXT_PAGES = (TEXT_END - TEXT_START) / 0x1000;
-
-    RAW_SYSCALL_HANDLERS_SIZE = (_raw_syscall_handlers_end - RAW_SYSCALL_HANDLERS);
-
-    .rodata :
-        AT(LOADADDR(.text) + SIZEOF(.text))
-    {
-        RODATA_START = .;
-        *(.rodata)
-        *(.rodata*)
-
-        . = ALIGN(16);
-        start_ctors = .;
-        KEEP(*(.init_array));
-        KEEP(*(SORT_BY_INIT_PRIORITY(.init_array*)));
-        KEEP(*(.ctors));
-        KEEP(*(SORT_BY_INIT_PRIORITY(.ctors*)));
-        end_ctors = .;
-
-        . = ALIGN(16);
-        RAW_SYSCALL_HANDLERS = .;
-        KEEP(*(.raw_syscalls*));
-
-        _raw_syscall_handlers_end = .;
-
-        . = ALIGN(16);
-        _fix_start = .;
-        KEEP(*(.fix));
-        _fix_end = .;
-
-        . = ALIGN(16);
-        BSS_ADDR = .;
-        QUAD(ABSOLUTE(BSS_START));
-        BSS_LENGTH = .;
-        QUAD(BSS_END - BSS_START);
-        FIX_START = .;
-        QUAD(ABSOLUTE(_fix_start));
-        FIX_END = .;
-        QUAD(ABSOLUTE(_fix_end));
-        PERCPU_PAGES = .;
-        QUAD(_PERCPU_PAGES);
-
-        . = ALIGN(0x1000);
-        RODATA_END = .;
-    } > KIMAGE
-
-    RODATA_PAGES = (RODATA_END - RODATA_START) / 0x1000;
-
-    .data : AT(LOADADDR(.rodata) + SIZEOF(.rodata))
-    {
-        DATA_START = .;
-        *(.data)
-        *(.data*)
-
-        *(.got)
-        *(.got.plt)
-
-        . = . + 4;
-        . = ALIGN(0x1000) - 4;
-        LONG(KERNEL_MAGIC);
-        DATA_END = .;
-    } > KIMAGE
-
-    DATA_PAGES = (DATA_END - DATA_START) / 0x1000;
-
-    _PERCPU_DATA_START = .;
-    .percpu 0 : AT(LOADADDR(.data) + SIZEOF(.data))
-    {
-        PERCPU_START = .;
-        QUAD(0); /* Reserved for x86 percpu pointer */
-        QUAD(0);
-
-        *(.percpu .percpu*)
-
-        . = ALIGN(0x1000);
-        PERCPU_END = .;
-    } > KPERCPU
-    _PERCPU_LENGTH = PERCPU_END - PERCPU_START;
-
-    _PERCPU_PAGES = _PERCPU_LENGTH / 0x1000;
-
-    .bss :
-    {
-        BSS_START = .;
-        *(.bss)
-        *(.bss*)
-
-        . = ALIGN(0x1000);
-        BSS_END = .;
-    } > KBSS
-
-    KIMAGE_PAGES = TEXT_PAGES + RODATA_PAGES + _PERCPU_PAGES + DATA_PAGES;
-    BSS_PAGES = (BSS_END - BSS_START) / 0x1000;
-    KERNEL_MAGIC = 0x01145140;
-
-    KIMAGE_32K_COUNT = (KIMAGE_PAGES * 0x1000 + 32 * 1024 - 1) / (32 * 1024);
-
-    .eh_frame :
-        AT(LOADADDR(.percpu) + SIZEOF(.percpu))
-    {
-        KEEP(*(.eh_frame*))
-        . = ALIGN(0x1000);
-    } > KIMAGE
-
-    /* Stabs debugging sections.  */
-    .stab          0 : { KEEP(*(.stab)); }
-    .stabstr       0 : { KEEP(*(.stabstr)); }
-    .stab.excl     0 : { KEEP(*(.stab.excl)); }
-    .stab.exclstr  0 : { KEEP(*(.stab.exclstr)); }
-    .stab.index    0 : { KEEP(*(.stab.index)); }
-    .stab.indexstr 0 : { KEEP(*(.stab.indexstr)); }
-    .comment       0 : { KEEP(*(.comment)); }
-    /* DWARF debug sections.
-       Symbols in the DWARF debugging sections are relative to the beginning
-       of the section so we begin them at 0.  */
-    /* DWARF 1 */
-    .debug          0 : { KEEP(*(.debug)); }
-    .line           0 : { KEEP(*(.line)); }
-    /* GNU DWARF 1 extensions */
-    .debug_srcinfo  0 : { KEEP(*(.debug_srcinfo)); }
-    .debug_sfnames  0 : { KEEP(*(.debug_sfnames)); }
-    /* DWARF 1.1 and DWARF 2 */
-    .debug_aranges  0 : { KEEP(*(.debug_aranges)); }
-    .debug_pubnames 0 : { KEEP(*(.debug_pubnames)); }
-    /* DWARF 2 */
-    .debug_info     0 : { KEEP(*(.debug_info)); }
-    .debug_abbrev   0 : { KEEP(*(.debug_abbrev)); }
-    .debug_line     0 : { KEEP(*(.debug_line)); }
-    .debug_frame    0 : { KEEP(*(.debug_frame)); }
-    .debug_str      0 : { KEEP(*(.debug_str)); }
-    .debug_loc      0 : { KEEP(*(.debug_loc)); }
-    .debug_macinfo  0 : { KEEP(*(.debug_macinfo)); }
-    /* SGI/MIPS DWARF 2 extensions */
-    .debug_weaknames 0 : { KEEP(*(.debug_weaknames)); }
-    .debug_funcnames 0 : { KEEP(*(.debug_funcnames)); }
-    .debug_typenames 0 : { KEEP(*(.debug_typenames)); }
-    .debug_varnames  0 : { KEEP(*(.debug_varnames)); }
-
-    /* DWARF Other */
-    .debug_ranges  0 : { KEEP(*(.debug_ranges)); }
-    .debug_line_str 0 : { KEEP(*(.debug_line_str)); }
-    /* Rust stuff */
-
-    /DISCARD/ :
-    {
-        *(.fini_array*)
-        *(.note*)
-        *(.dtors*)
-        *(.debug_gdb_scripts*)
-    }
-}

+ 2 - 1
src/kernel/cpu.rs

@@ -1,6 +1,7 @@
 use super::mem::{AsMemoryBlock, GlobalPageAlloc};
 use arch::{PercpuArea, CPU};
 use core::{alloc::Layout, pin::Pin, ptr::NonNull};
+use eonix_hal::mm::PAGE_SIZE;
 use eonix_mm::paging::Page;
 use eonix_sync::LazyLock;
 
@@ -17,7 +18,7 @@ pub unsafe fn local_cpu() -> Pin<&'static mut CPU> {
 
 pub fn percpu_allocate(layout: Layout) -> NonNull<u8> {
     // TODO: Use page size defined in `arch`.
-    let page_count = layout.size().div_ceil(arch::PAGE_SIZE);
+    let page_count = layout.size().div_ceil(PAGE_SIZE);
     let page = Page::alloc_at_least_in(page_count, GlobalPageAlloc::early_alloc());
     let page_data = page.as_memblk().as_byte_ptr();
     core::mem::forget(page);

+ 1 - 1
src/kernel/mem/mm_list.rs

@@ -9,9 +9,9 @@ use super::{AsMemoryBlock, MMArea, Page};
 use crate::kernel::constants::{EEXIST, EFAULT, EINVAL, ENOMEM};
 use crate::{prelude::*, sync::ArcSwap};
 use alloc::collections::btree_set::BTreeSet;
-use arch::DefaultPagingMode;
 use core::fmt;
 use core::sync::atomic::{AtomicUsize, Ordering};
+use eonix_hal::mm::DefaultPagingMode;
 use eonix_mm::address::{Addr as _, PAddr};
 use eonix_mm::page_table::{PageAttribute, PagingMode};
 use eonix_mm::paging::PFN;

+ 4 - 4
src/kernel/user/dataflow.rs

@@ -106,7 +106,7 @@ impl CheckedUserPointer {
                 "rep movsb",
                 "3:",
                 "nop",
-                ".pushsection .fix",
+                ".pushsection .fix, \"a\", @progbits",
                 ".align 32",
                 ".quad 2b",  // instruction address
                 ".quad 3b - 2b",  // instruction length
@@ -142,7 +142,7 @@ impl CheckedUserPointer {
                 "rep movsb",
                 "3:",
                 "nop",
-                ".pushsection .fix",
+                ".pushsection .fix, \"a\", @progbits",
                 ".align 32",
                 ".quad 2b",  // instruction address
                 ".quad 3b - 2b",  // instruction length
@@ -178,7 +178,7 @@ impl CheckedUserPointer {
                 "rep stosb",
                 "3:",
                 "nop",
-                ".pushsection .fix",
+                ".pushsection .fix, \"a\", @progbits",
                 ".align 32",
                 ".quad 2b",  // instruction address
                 ".quad 3b - 2b",  // instruction length
@@ -268,7 +268,7 @@ impl<'lt> UserString<'lt> {
                 "loop 2b",
                 "3:",
                 "nop",
-                ".pushsection .fix",
+                ".pushsection .fix, \"a\", @progbits",
                 ".align 32",
                 ".quad 2b",  // instruction address
                 ".quad 4b - 2b",  // instruction length

+ 1 - 1
src/kernel_init.rs

@@ -6,7 +6,7 @@ use crate::{
     },
     kernel_init,
 };
-use arch::DefaultPagingMode;
+use eonix_hal::mm::DefaultPagingMode;
 use eonix_mm::{
     address::{Addr as _, AddrOps as _, PAddr, PRange, VAddr, VRange},
     page_table::{PageAttribute, PagingMode as _, PTE},

+ 0 - 123
src/mbr.S

@@ -1,123 +0,0 @@
-.section .mbr
-.code16
-
-move_mbr:
-    xor %ax, %ax
-    mov %ax, %ds
-    mov %ax, %es
-    mov %ax, %ss
-
-    # move the MBR to 0xe00
-    mov $128, %cx # 512 bytes
-    mov $0x7c00, %si
-    mov $0x0e00, %di
-    rep movsl
-
-    ljmp $0x00, $2f
-
-2:
-    # read the kernel stage1
-    mov $.Lread_data_packet, %si
-    mov $0x42, %ah
-    mov $0x80, %dl
-    int $0x13
-    jc .Lhalt
-
-    # get memory size info and storage it
-    mov $0xe801, %ax
-    int $0x15
-    jc .Lhalt
-
-    cmp $0x86, %ah # unsupported function
-    je .Lhalt
-    cmp $0x80, %ah # invalid command
-    je .Lhalt
-
-    jcxz 2f
-    mov %cx, %ax
-    mov %dx, %bx
-
-2:
-    mov $E820_MEM_MAP_DATA, %esp
-    movzw %ax, %eax
-    mov %eax, 8(%esp)  # 1k blocks
-    movzw %bx, %ebx
-    mov %ebx, 12(%esp) # 64k blocks
-
-    # save the destination address to es:di
-    mov %sp, %di
-    add $16, %di # buffer is 1024 - 16 bytes
-
-    # set default entry size
-    movl $20, 4(%esp)
-
-    # clear %ebx, len
-    xor %ebx, %ebx
-    mov %ebx, (%esp)
-
-2:
-    # set the magic number to edx
-    mov $0x534D4150, %edx
-
-    # set function number to eax
-    mov $0xe820, %eax
-
-    # set default entry size
-    mov $24, %ecx
-
-    int $0x15
-
-    incl (%esp)
-    add $24, %edi
-
-    jc .Lsave_mem_fin
-    cmp $0, %ebx
-    jz .Lsave_mem_fin
-
-    cmp $24, %ecx
-    cmovnz 4(%esp), %ecx
-    mov %ecx, 4(%esp)
-
-    jmp 2b
-
-.Lsave_mem_fin:
-    mov $0x3ff, %ax
-    mov $BIOS_IDT_DESCRIPTOR, %di
-    mov %ax, (%di)
-
-    xor %eax, %eax
-    mov %eax, 2(%di)
-
-    lgdt .Learly_gdt_descriptor
-
-    cli
-    # IDT descriptor is 6 0's. borrow the null gdt entry
-    lidt .Learly_gdt
-
-    # enable protection mode
-    mov %cr0, %eax
-    or $1, %eax
-    mov %eax, %cr0
-
-    ljmp $0x08, $start_32bit
-
-.Lhalt:
-    hlt
-    jmp .
-
-.align 16
-.Learly_gdt:
-    .8byte 0x0                # null selector
-    .8byte 0x00cf9a000000ffff # 32bit code selector
-    .8byte 0x00cf92000000ffff # 32bit data selector
-
-.align 4
-.Learly_gdt_descriptor:
-    .word 0x17 # size
-    .long .Learly_gdt  # address
-
-.align 16
-.Lread_data_packet:
-    .long  0x00080010 # .stage1 takes up 4K, or 8 sectors
-    .long  0x00007000 # read to 0000:7000
-    .8byte 1          # read from LBA 1

+ 0 - 0
busybox → user-programs/busybox


+ 0 - 0
busybox-minimal → user-programs/busybox-minimal


BIN
user-programs/init.out


BIN
user-programs/int.out


+ 0 - 21
user-space-program/CMakeLists.txt

@@ -1,21 +0,0 @@
-cmake_minimum_required(VERSION 3.15)
-project(user_space_program C ASM)
-
-set(CMAKE_C_FLAGS "-nostdlib -nostdinc -m32 -static -W -Wall -mstack-protector-guard=global")
-set(CMAKE_ASM_FLAGS "-nostdlib -static -m32 -mstack-protector-guard=global")
-
-link_libraries(gblibc_32 crt0_32)
-add_link_options("LINKER:-melf_i386")
-
-set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "")
-set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "")
-
-add_executable(hello-world.out hello-world.s)
-add_executable(interrupt-test.out interrupt-test.s)
-add_executable(stack-test.out stack-test.s)
-add_executable(init.out init.c)
-add_executable(priv-test.out priv-test.c)
-
-add_custom_target(user_space_programs
-    DEPENDS hello-world.out interrupt-test.out stack-test.out init.out priv-test.out
-)

+ 0 - 36
user-space-program/basic-lib.h

@@ -1,36 +0,0 @@
-#include <stdint.h>
-#include <sys/types.h>
-
-typedef uint32_t ino_t;
-
-#define GNU_ATTRIBUTE(attr) __attribute__((attr))
-#define NORETURN GNU_ATTRIBUTE(noreturn)
-
-#define O_RDONLY (0)
-#define O_DIRECTORY (0x4)
-
-// dirent file types
-#define DT_UNKNOWN 0
-#define DT_FIFO 1
-#define DT_CHR 2
-#define DT_DIR 4
-#define DT_BLK 6
-#define DT_REG 8
-#define DT_LNK 10
-#define DT_SOCK 12
-#define DT_WHT 14
-
-#define DT_MAX (S_DT_MASK + 1) /* 16 */
-
-struct __attribute__((__packed__)) user_dirent {
-    ino_t d_ino; // inode number
-    uint32_t d_off; // ignored
-    uint16_t d_reclen; // length of this struct user_dirent
-    char d_name[1]; // file name with a padding zero
-    // uint8_t d_type; // file type, with offset of (d_reclen - 1)
-};
-
-// static inline size_t getdents(int fd, struct user_dirent* buf, size_t cnt)
-// {
-//     return syscall(0x08, fd, (uint32_t)buf, cnt);
-// }

+ 0 - 9
user-space-program/configure

@@ -1,9 +0,0 @@
-#!/bin/sh
-
-cp Makefile.src Makefile
-
-make --always-make --dry-run \
-    | grep -wE 'gcc|g\+\+' \
-    | grep -w '\-c' \
-    | jq -nR '[inputs|{directory:".", command:., file: match(" [^ ]+$").string[1:]}]' \
-    > compile_commands.json

+ 0 - 25
user-space-program/hello-world.s

@@ -1,25 +0,0 @@
-.code32
-
-.text
-
-.globl main
-main:
-	movl $0xcbcbcbcb, %eax
-	movl $0xacacacac, %edx
-
-	movl $0x04, %eax
-	movl $1, %ebx
-	movl $_str, %ecx
-	movl $_str_size, %edx
-	movl (%edx), %edx
-	int $0x80
-
-	xorl %eax, %eax
-	ret
-
-.data
-_str:
-	.ascii "Hello, World!\n"
-
-_str_size:
-	.long (_str_size - _str)

+ 0 - 91
user-space-program/init.c

@@ -1,91 +0,0 @@
-#include <assert.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#define print(str) write(STDERR_FILENO, str, _strlen(str))
-
-static size_t _strlen(const char* str) {
-    size_t len = 0;
-    while (str[len] != '\0') {
-        len++;
-    }
-    return len;
-}
-
-static __attribute__((used)) size_t strlen(const char* s) {
-    size_t len = 0;
-    while (*s++)
-        ++len;
-    return len;
-}
-
-static __attribute__((used)) void* memcpy(void* dst, const void* src,
-                                          size_t n) {
-    uint8_t* d = (uint8_t*)dst;
-    const uint8_t* s = (const uint8_t*)src;
-    for (size_t i = 0; i < n; ++i)
-        d[i] = s[i];
-    return dst;
-}
-
-int main(int argc, char** argv) {
-    int fd = 0;
-    // Assumes three file descriptors open.
-    while ((fd = open("/dev/console", 0)) >= 0) {
-        if (fd >= 3) {
-            close(fd);
-            break;
-        }
-    }
-
-    print("***** GBOS INIT SYSTEM *****\n");
-
-_run_sh:;
-    pid_t sh_pid = fork();
-    if (sh_pid < 0) {
-        print("[init] unable to fork(), exiting...\n");
-        return -1;
-    }
-
-    // child
-    if (sh_pid == 0) {
-        pid_t sid = setsid();
-        if (sid < 0) {
-            print("[init] unable to setsid, exiting...\n");
-            return -1;
-        }
-
-        char* shell_argv[128] = {};
-
-        if (argc < 2)
-            shell_argv[0] = "/bin/sh";
-        else
-            shell_argv[0] = argv[1];
-
-        for (int i = 2; i < argc; ++i)
-            shell_argv[i - 1] = argv[i];
-
-        execve(shell_argv[0], shell_argv, environ);
-
-        print("[init] unable to run sh, exiting...\n");
-        return -1;
-    }
-
-    int ret, pid;
-    for (;;) {
-        pid = wait(&ret);
-        char* buf = NULL;
-        assert(asprintf(&buf, "[init] pid%d has exited with code %d\n", pid,
-                        ret) >= 0);
-        print(buf);
-        free(buf);
-        // sh
-        if (pid == sh_pid)
-            goto _run_sh;
-    }
-
-    return 0;
-}

+ 0 - 29
user-space-program/interrupt-test.s

@@ -1,29 +0,0 @@
-.code32
-
-.text
-
-.globl main
-main:
-# fork 1 -> 2
-	movl $0x02, %eax
-	int $0x80
-	movl %eax, %esi
-# fork 2 -> 4
-	movl $0x02, %eax
-	int $0x80
-	movl %eax, %ecx
-# write
-	movl $0x04, %eax
-	movl $1, %ebx
-	movl $__user_interrupt_test_string, %ecx
-	movl $(__user_interrupt_test_string_end - __user_interrupt_test_string), %edx
-	int $0x80
-
-	xorl %eax, %eax
-	ret
-
-.data
-
-__user_interrupt_test_string:
-	.ascii "syscall 0x01 write: hello from user space\n"
-__user_interrupt_test_string_end:

+ 0 - 5
user-space-program/priv-test.c

@@ -1,5 +0,0 @@
-int main(void) {
-    int* ptr = (int*)0x10000;
-    *ptr = 0x114514;
-    return -1;
-}

+ 0 - 16
user-space-program/stack-test.s

@@ -1,16 +0,0 @@
-.code32
-
-.text
-
-.globl main
-.type  main @function
-main:
-	pushl %ebp
-	movl %esp, %ebp
-
-	movl %esp, %eax
-
-	movl %ebp, %esp
-	popl %ebp
-
-	ret