Meta: Add files to repository

This commit is contained in:
Alec Murphy
2025-02-16 15:21:19 -05:00
parent 6d27d43268
commit 52cb92f587
120 changed files with 71820 additions and 0 deletions

28
src/net/devices/virtio.h Normal file
View File

@@ -0,0 +1,28 @@
struct virtio_queue_buf {
u64 address;
u32 length;
u16 flags;
u16 next;
};
struct virtio_avail {
u16 flags;
u16 index;
u16 ring[256];
u16 int_index;
};
struct virtio_used_item {
u32 index;
u32 length;
};
struct virtio_used {
u16 flags;
u16 index;
virtio_used_item ring[256];
u16 int_index;
};
struct virtio_queue {
virtio_queue_buf buffers[256];
virtio_avail available;
u8 padding[3578];
virtio_used used;
};

143
src/net/devices/virtio.jakt Normal file
View File

@@ -0,0 +1,143 @@
import relative parent::os::os { OS }
import relative parent::os::pci { PCI, PCIDevice }
enum VirtIOConfig: u8 {
acknowledge = 1
driver = 2
driver_ok = 4
}
enum VirtIOReg: u16 {
host_features = 0
guest_features = 4
queue_page_frame_number = 8
queue_size = 12
queue_select = 14
queue_notify = 16
status = 18
isr = 19
config = 20
}
class VirtIO {
public pci_device: PCIDevice
public rq_index: i64
public rq_size: u16
public rq: u32
public tq_size: u16
public tq: u32
public fn rx_frame(mut this) throws -> [u8] {
mut frame: [u8] = []
mut queue_notify: bool = false
unsafe {
cpp {
"
#include <../../src/net/devices/virtio.h>
virtio_queue *rq = (virtio_queue*)this->rq;
i64 i = this->rq_index;
i64 used_index = rq->used.index;
if (used_index < i)
used_index += 0x10000;
if (used_index && i != used_index) {
virtio_used_item* item = rq->used.ring;
u8* buffer = (u8*)rq->buffers[item[i % 256].index + 1].address;
i64 length = item[i % 256].length - 10;
for (i64 j = 0; j < length; j++)
frame.push(buffer[j]);
this->rq_index = used_index % 0x10000;
rq->available.index++;
queue_notify = true;
}
"
}
}
if queue_notify {
.pci_device.io_write_u16(offset: VirtIOReg::queue_notify as! u16, value: 0)
}
return frame
}
public fn tx_frame(mut this, anon mut data: [u8]) throws {
mut size = data.size()
unsafe {
cpp {
"
#include <../../src/net/devices/virtio.h>
virtio_queue *tq = (virtio_queue*)this->tq;
int tq_idx = tq->available.index % 256;
int tq_idx2 = tq_idx % 128;
memset((u8*)tq->buffers[tq_idx2 * 2].address, 0, 10);
u8 *buffer = (u8*)tq->buffers[(tq_idx2 * 2) + 1].address;
for (int i = 0; i < size; i++)
buffer[i] = data[i];
tq->buffers[tq_idx2 * 2].length = 10;
tq->buffers[tq_idx2 * 2].flags = 1;
tq->buffers[tq_idx2 * 2].next = (tq_idx2 * 2) + 1;
tq->buffers[(tq_idx2 * 2) + 1].length = size;
tq->buffers[(tq_idx2 * 2) + 1].flags = 0;
tq->buffers[(tq_idx2 * 2) + 1].next = 0;
tq->available.ring[tq_idx] = tq_idx2 * 2;
tq->available.index++;
"
}
}
.pci_device.io_write_u16(offset: VirtIOReg::queue_notify as! u16, value: 1)
}
fn reset_device(this) {
.pci_device.io_write_u8(offset: VirtIOReg::status as! u16, value: 0)
}
fn found_driver(this) throws {
.pci_device.io_write_u8(offset: VirtIOReg::status as! u16,
value: .pci_device.io_read_u8(VirtIOReg::status as! u16) | VirtIOConfig::acknowledge as! u8 | VirtIOConfig::driver as! u8)
}
fn setup_rx_queue(mut this) throws {
.pci_device.io_write_u16(offset: VirtIOReg::queue_select as! u16, value: 0)
.rq_size = .pci_device.io_read_u16(VirtIOReg::queue_size as! u16)
.rq = OS::device_calloc(16384)
.pci_device.io_write_u32(offset: VirtIOReg::queue_page_frame_number as! u16, value: .rq / 4096)
}
fn setup_tx_queue(mut this) throws {
.pci_device.io_write_u16(offset: VirtIOReg::queue_select as! u16, value: 1)
.tq_size = .pci_device.io_read_u16(VirtIOReg::queue_size as! u16)
.tq = OS::device_calloc(16384)
.pci_device.io_write_u32(offset: VirtIOReg::queue_page_frame_number as! u16, value: .tq / 4096)
}
fn init_queue_buffers(this) {
unsafe {
cpp {
"
#include <../../src/net/devices/virtio.h>
virtio_queue *rq = (virtio_queue*)this->rq;
virtio_queue *tq = (virtio_queue*)this->tq;
for (int i = 0; i < 128; i++) {
rq->buffers[i * 2].address = (u64)calloc(1, 16);
rq->buffers[i * 2].length = 10;
rq->buffers[i * 2].flags = 3;
rq->buffers[i * 2].next = (i * 2) + 1;
rq->buffers[(i * 2) + 1].address = (u64)calloc(1, 2048);
rq->buffers[(i * 2) + 1].length = 2048;
rq->buffers[(i * 2) + 1].flags = 2;
rq->buffers[(i * 2) + 1].next = 0;
rq->available.ring[i] = i * 2;
rq->available.ring[i + 128] = i * 2;
tq->buffers[i * 2].address = (u64)calloc(1, 16);
tq->buffers[(i * 2) + 1].address = (u64)calloc(1, 2048);
}
rq->available.index = 1;
"
}
}
}
fn init_ok(this) throws {
.pci_device.io_write_u8(offset: VirtIOReg::status as! u16,
value: .pci_device.io_read_u8(VirtIOReg::status as! u16) | VirtIOConfig::driver_ok as! u8)
.pci_device.io_write_u16(offset: VirtIOReg::queue_notify as! u16, value: 0)
}
public fn init(mut this) throws {
.reset_device()
.found_driver()
.setup_rx_queue()
.setup_tx_queue()
.init_queue_buffers()
.init_ok()
}
}

350
src/net/lib/json.jakt Normal file
View File

@@ -0,0 +1,350 @@
/// Expect:
/// - output: "JsonValue::JsonArray([JsonValue::Object([\"id\": JsonValue::Number(0.5), \"displayName\": JsonValue::JsonString(\"Air\"), \"name\": JsonValue::JsonString(\"air\"), \"hardness\": JsonValue::Number(3.9), \"resistance\": JsonValue::Number(0), \"minStateId\": JsonValue::Number(0), \"maxStateId\": JsonValue::Number(0), \"states\": JsonValue::JsonArray([])])])\n"
enum JsonValue {
Null
Bool(bool)
Number(f64)
// FIXME: This variant should be called String
JsonString(String)
// FIXME: This variant should be called Array
JsonArray([JsonValue])
Object([String:JsonValue])
}
fn is_whitespace(anon c: u8) -> bool {
return match c {
b'\t' | b'\n' | b'\r' | b' ' => true
else => false
}
}
class JsonParser {
input: String
index: usize
public fn construct(input: String) throws -> JsonParser {
return JsonParser(input, index: 0)
}
fn eof(this) -> bool {
return .index >= .input.length()
}
public fn parse(mut this) throws -> JsonValue {
// FIXME: Jakt::JsonParser ignores trailing whitespace for some reason.
let value = .parse_helper()
if not .eof() {
// FIXME: "Didn't consume all input"
throw Error::from_errno(9000)
}
return value
}
fn skip_whitespace(mut this) {
while not .eof() {
if not is_whitespace(.input.byte_at(.index)) {
break
}
.index++
}
}
fn consume_and_unescape_string(mut this) throws -> String {
if not .consume_specific(b'"') {
// FIXME: "Expected '"'
throw Error::from_errno(9007)
}
mut builder = StringBuilder::create()
loop {
mut ch = 0u8
mut peek_index = .index
while peek_index < .input.length() {
ch = .input.byte_at(peek_index)
if ch == b'"' or ch == b'\\' {
break
}
// FIXME: This is is_ascii_c0_control()
if ch < 0x20 {
// FIXME: "Error while parsing string"
throw Error::from_errno(9008)
}
peek_index++
}
while peek_index != .index {
builder.append(.input.byte_at(.index))
.index++
}
if .eof() {
break
}
if ch == b'"' {
break
}
if ch != b'\\' {
builder.append(.consume())
continue
}
.ignore()
match .peek() {
b'"' | b'/' | b'\\' | b'n' | b'r' | b't' | b'b' | b'f' => {
let ch = .consume()
builder.append(match ch {
b'n' => b'\n'
b'r' => b'\r'
b't' => b'\t'
b'b' => b'\b'
b'f' => b'\f'
else => ch
})
}
b'u' => {
eprintln("FIXME: Implement unicode literals")
abort()
}
else => {
// FIXME: "Error while parsing string"
throw Error::from_errno(9009)
}
}
}
if not .consume_specific(b'"') {
// FIXME: "Expected '"'"
throw Error::from_errno(9010)
}
return builder.to_string()
}
fn ignore(mut this) {
.index++
}
fn peek(this) -> u8 {
if .eof() {
return 0
}
return .input.byte_at(.index)
}
fn consume(mut this) -> u8 {
let ch = .peek()
.index++
return ch
}
fn consume_specific(mut this, anon expected: u8) -> bool {
if .peek() != expected {
return false
}
.index++
return true
}
fn parse_helper(mut this) throws -> JsonValue {
.skip_whitespace()
return match .peek() {
b'{' => .parse_object()
b'[' => .parse_array()
b'"' => .parse_string()
b'-' => .parse_number()
b'0' | b'1' | b'2' | b'3' | b'4' | b'5' | b'6' | b'7' | b'8' | b'9' => .parse_number()
b'f' => .parse_false()
b't' => .parse_true()
b'n' => .parse_null()
else => .parse_failure(error_message: "Unexpected character")
}
}
fn parse_failure(this, error_message: String) throws -> JsonValue {
throw Error::from_errno(9001)
}
fn parse_array(mut this) throws -> JsonValue {
mut array: [JsonValue] = []
if (not .consume_specific(b'[')) {
// Expected '['
throw Error::from_errno(9014)
}
loop {
.skip_whitespace()
if .peek() == b']' {
break
}
array.push(.parse_helper())
.skip_whitespace()
if .peek() == b']' {
break
}
if not .consume_specific(b',') {
// Expected ','
throw Error::from_errno(9014)
}
.skip_whitespace()
if .peek() == b']' {
// Unexpected ']'
throw Error::from_errno(9014)
}
}
if not .consume_specific(b']') {
// Expected ']'
throw Error::from_errno(9015)
}
return JsonValue::JsonArray(array)
}
fn parse_object(mut this) throws -> JsonValue {
if not .consume_specific(b'{') {
// FIXME: "Expected '{'"
throw Error::from_errno(9002)
}
mut values: [String:JsonValue] = [:]
loop {
.skip_whitespace()
if .peek() == b'}' {
break
}
.skip_whitespace()
let key = .consume_and_unescape_string()
.skip_whitespace()
if not .consume_specific(b':') {
// FIXME: "Expected ':'"
throw Error::from_errno(9003)
}
.skip_whitespace()
let value = .parse_helper()
// FIXME: This should say `values[key] = value`, but the compiler doesn't wrap it in TRY()
values.set(key, value)
.skip_whitespace()
if .peek() == b'}' {
break
}
if not .consume_specific(b',') {
// FIXME: "Expected ','"
throw Error::from_errno(9004)
}
.skip_whitespace()
if .peek() == b'}' {
// FIXME: "Unexpected '}'"
throw Error::from_errno(9005)
}
}
if not .consume_specific(b'}') {
// FIXME: "Expected '}'"
throw Error::from_errno(9006)
}
return JsonValue::Object(values)
}
fn char_to_f64(anon num: u8) throws -> f64 {
// FIXME 1: Shouldn't need this function at all
// FIXME 2: Shouldn't need return in else branch
return match num {
0u8 => 0.0
1u8 => 1.0
2u8 => 2.0
3u8 => 3.0
4u8 => 4.0
5u8 => 5.0
6u8 => 6.0
7u8 => 7.0
8u8 => 8.0
9u8 => 9.0
else => {
// FIXME: "Unexpected number"
throw Error::from_errno(9017)
}
}
}
fn parse_number(mut this) throws -> JsonValue {
// FIXME: This implementation doesn't match JsonParser.cpp
let is_negative = .consume_specific(b'-')
mut decimal_start_index: usize? = None
mut value = 0.0
while not .eof() {
let ch = .peek()
if ch == b'.' {
if decimal_start_index.has_value() {
// FIXME: "Unexpected '.'"
throw Error::from_errno(9016)
}
decimal_start_index = .index++
continue
} else if not (ch >= b'0' and ch <= b'9') {
break
}
if not decimal_start_index.has_value() {
value *= 10.0
value += char_to_f64(ch - b'0')
} else {
mut num = char_to_f64(ch - b'0')
// FIXME: This should really be: `value += pow(10, -decimal_place)*num`, but: there's no pow function and you can't multiply float by usize
let decimal_place = .index - decimal_start_index.value()
for i in 0..decimal_place {
num /= 10.0
}
value += num
}
.index++
}
if is_negative {
value *= -1.0
}
return JsonValue::Number(value)
}
fn parse_string(mut this) throws -> JsonValue {
return JsonValue::JsonString(.consume_and_unescape_string())
}
fn parse_false(mut this) throws -> JsonValue {
if (.consume() != b'f' or .consume() != b'a' or .consume() != b'l' or .consume() != b's' or .consume() != b'e') {
// FIXME: "Expected 'false'"
throw Error::from_errno(9011)
}
return JsonValue::Bool(false)
}
fn parse_true(mut this) throws -> JsonValue {
if (.consume() != b't' or .consume() != b'r' or .consume() != b'u' or .consume() != b'e') {
// FIXME: "Expected 'true'"
throw Error::from_errno(9012)
}
return JsonValue::Bool(true)
}
fn parse_null(mut this) throws -> JsonValue {
if (.consume() != b'n' or .consume() != b'u' or .consume() != b'l' or .consume() != b'l') {
// FIXME: "Expected 'null'"
throw Error::from_errno(9013)
}
return JsonValue::Null
}
}
// fn parse_json(input: String) throws -> JsonValue {
// mut parser = JsonParser::construct(input)
// return parser.parse()
// }
//
// fn main() {
// let value = parse_json(input: "[{\"id\":0.5,\"displayName\":\"Air\",\"name\":\"air\",\"hardness\":3.9,\"resistance\":0,\"minStateId\":0,\"maxStateId\":0,\"states\":[]}]")
// println("{}", value)
// }

147
src/net/lib/util.jakt Normal file
View File

@@ -0,0 +1,147 @@
import relative parent::os::os { OS }
struct Util {
fn get_address_u32_from_ipv4_u8_array(anon array: [u8]) -> u32 {
if array.size() != 4 {
return 0
}
mut address: u32 = (array[3] as! u32 & 0xff) as! u32
address += ((array[2] as! u32 & 0xff) << 8) as! u32
address += ((array[1] as! u32 & 0xff) << 16) as! u32
address += ((array[0] as! u32 & 0xff) << 24) as! u32
return address
}
fn get_hexadecimal_string_from_ipv4_u8_array(anon array: [u8]) throws -> String {
mut s = StringBuilder::create()
unsafe {
cpp {
"char *chars = (char*)calloc(32, 1);
sprintf(chars, \"%02x%02x%02x%02x\", array[0], array[1], array[2], array[3]);
s.append_c_string(chars);
delete(chars);"
}
}
return s.to_string()
}
fn get_md5_string_from_string(anon s: String) throws -> String {
mut sb = StringBuilder::create()
unsafe {
cpp {
"
char* md5 = (char*)os_call((u64)\"@saubari_get_md5_string_from_string\", (u64)s.characters());
sb.append_c_string(md5);
delete(md5);
"
}
}
return sb.to_string()
}
fn get_ipv4_u8_array_from_address_string(anon s: String) throws -> [u8] {
mut address: [u8] = []
let octet_strings = s.split(c'.')
for octet_string in octet_strings {
unsafe {
cpp {
"auto value = octet_string.to_number<u32>();
if (value.has_value()) {
auto result = value.release_value();
address.push(result & 0xff);
}"
}
}
}
return address
}
fn get_ipv4_u8_array_from_address_u32(anon addr: u32) throws -> [u8] {
mut address: [u8] = []
// let source_address: [u8] = [ipv4_packet[12], ipv4_packet[13], ipv4_packet[14], ipv4_packet[15]]
address.push(((addr >> 24) & 0xff) as! u8)
address.push(((addr >> 16) & 0xff) as! u8)
address.push(((addr >> 8) & 0xff) as! u8)
address.push((addr & 0xff) as! u8)
return address
}
fn get_string_from_u8_array(anon array: [u8]) throws -> String {
mut s = StringBuilder::create()
unsafe {
cpp {
"for (int i = 0; i < array.size(); i++) {
s.append(array[i]);
}"
}
}
return s.to_string()
}
fn get_u16_from_u8_array(anon array: [u8], anon offset: i64) -> u16{
return (array[offset] as! u16 << 8) + array[offset + 1] as! u16
}
fn get_u16_from_u8_arrayslice(anon array: ArraySlice<u8>, anon offset: i64) -> u16{
return (array[offset] as! u16 << 8) + array[offset + 1] as! u16
}
fn push_string_to_u8_array(anon mut array: [u8], anon s: String) throws {
for i in 0..s.length() {
unsafe {
cpp {
"array.push(s.characters()[i]);"
}
}
}
}
fn push_u16_to_u8_array(anon mut array: [u8], anon value: u16) throws {
array.push((value >> 8) as! u8)
array.push((value & 0xff) as! u8)
}
fn push_u32_to_u8_array(anon mut array: [u8], anon value: u32) throws {
mut val_u32_to_u8: u32 = 0
val_u32_to_u8 = (value >> 24) & 0xff
array.push(val_u32_to_u8 as! u8)
val_u32_to_u8 = (value >> 16) & 0xff
array.push(val_u32_to_u8 as! u8)
val_u32_to_u8 = (value >> 8) & 0xff
array.push(val_u32_to_u8 as! u8)
array.push((value & 0xff) as! u8)
}
fn get_dictionary_from_json_file(anon json_file: String) throws -> [String:String] {
mut dictionary: [String:String] = Dictionary()
let json_bytes = OS::read_entire_file(json_file)
let json_string = get_string_from_u8_array(json_bytes)
unsafe {
cpp {
"auto json = JsonValue::from_string(json_string).value();
auto const& object = json.as_object();
object.for_each_member([&]([[maybe_unused]] auto& property_name, [[maybe_unused]] const JsonValue& property_value) {
dictionary.set(property_name, property_value.deprecated_to_byte_string());
});"
}
}
return dictionary
}
fn get_dictionary_from_string(anon s: String) throws -> [String:String] {
mut dictionary: [String:String] = Dictionary()
unsafe {
cpp {
"auto json = JsonValue::from_string(s).value();
auto const& object = json.as_object();
object.for_each_member([&]([[maybe_unused]] auto& property_name, [[maybe_unused]] const JsonValue& property_value) {
dictionary.set(property_name, property_value.deprecated_to_byte_string());
});"
}
}
return dictionary
}
fn string_from_file(anon filepath: String) throws -> String {
if filepath.is_empty() or not OS::path_exists(filepath) {
return ""
}
let array = OS::read_entire_file(filepath)
mut s = StringBuilder::create()
unsafe {
cpp {
"for (int i = 0; i < array.size(); i++) {
s.append(array[i]);
}"
}
}
return s.to_string()
}
}

173
src/net/net.jakt Normal file
View File

@@ -0,0 +1,173 @@
import devices::virtio { VirtIO, VirtIOReg }
import lib::util { Util }
import os::os { OS }
import os::pci { PCI, PCIDevice }
import os::time { Time }
import tcpip { TCPIP }
class NetDevices {
public virtio: VirtIO
public fn create(pci_device: PCIDevice) throws -> NetDevices {
return NetDevices(
virtio: VirtIO(pci_device, rq_index: 0, rq_size: 0, rq: 0, tq_size: 0, tq: 0)
)
}
}
class Net {
public device: NetDevices
public mac_address: [u8]
public tcpip: TCPIP
public pci_device: PCIDevice
public fn init(config: [String:String]) throws -> Net {
let pci_device = PCI::find_device_by_class_code(0x020000)
mut net = Net(
device: NetDevices::create(pci_device)
mac_address: []
tcpip: TCPIP(
ipv4_address: Util::get_ipv4_u8_array_from_address_string(config["tcpip.ipv4_address"])
ipv4_netmask: Util::get_ipv4_u8_array_from_address_string(config["tcpip.ipv4_netmask"])
ipv4_network: Util::get_ipv4_u8_array_from_address_string(config["tcpip.ipv4_network"])
ipv4_gateway: Util::get_ipv4_u8_array_from_address_string(config["tcpip.ipv4_gateway"])
dns_server_address: Util::get_ipv4_u8_array_from_address_string(config["tcpip.ipv4_dns_server_address"])
dns_server_port: config["tcpip.ipv4_dns_server_port"].to_number<u32>().value() as! u16
mss_size: config["tcpip.mss_size"].to_number<u32>().value() as! u16
tx_queue: []
ttl: 64
arp_cache: Dictionary()
bound_sockets: Dictionary()
dns_cache: Dictionary()
tcp_sessions: []
pending_dns_lookups: Dictionary()
pending_dns_cached_entries: Dictionary()
pending_icmp_requests: Dictionary()
timestamp_last_arp_request: 0
rx_bytes: 0
rx_frames: 0
tx_bytes: 0
tx_frames: 0
)
pci_device
)
if net.pci_device.vendor_id() == 0x1af4 and net.pci_device.device_id() == 0x1000 {
println("[net] Found device: virtio-net, QEMU")
for i in 0u16..6u16 {
net.mac_address.push(net.pci_device.io_read_u8(VirtIOReg::config as! u16 + i))
}
net.device.virtio.init()
return net
}
println("[net] No supported vendor ids found")
OS::exit()
return net
}
fn process_ethernet_frame(mut this, anon frame: [u8]) throws {
let ethertype: u16 = (frame[12] as! u16 * 256) + frame[13] as! u16
match ethertype {
0x0806 => {
//println("ARP")
.tcpip.process_arp_packet(.mac_address, frame)
}
0x0800 => {
//println("IPv4")
.tcpip.process_ipv4_packet(.mac_address, frame)
}
0x86dd => {
//.tcpip.process_ipv6_packet(frame)
}
0x8035 => {
//.tcpip.process_rarp_packet(frame)
}
else => {
// unsupported
}
}
}
public fn process_events(mut this) throws {
mut received_frame = .rx_frame()
if received_frame.size() > 0 {
.tcpip.rx_bytes += received_frame.size() as! u64
.tcpip.rx_frames++
.process_ethernet_frame(received_frame)
}
.tcpip.tcp_transmit_pending_data_for_existing_sessions()
for frame in .tcpip.tx_queue {
.tx_frame(frame)
}
if .tcpip.tx_queue.size() > 0 {
.tcpip.tx_queue.shrink(0)
}
.tcpip.tcp_process_bind_request()
.tcpip.tcp_process_client_socket_request(.mac_address)
.tcpip.tcp_process_client_received_data()
.tcpip.tcp_process_client_send_requests(.mac_address)
.tcpip.dns_process_client_request(.mac_address)
.tcpip.icmp_process_client_request(.mac_address)
.tcpip.netinfo_process_client_request(.mac_address)
}
fn rx_frame(mut this) throws -> [u8] {
mut frame: [u8] = []
if .pci_device.vendor_id() == 0x1af4 and .pci_device.device_id() == 0x1000 {
frame = .device.virtio.rx_frame()
}
return frame
}
fn tx_frame(mut this, anon mut data: [u8]) throws {
if data.size() < 1 {
return
}
while data.size() < 60 {
data.push(0u8)
}
.tcpip.tx_bytes += data.size() as! u64
.tcpip.tx_frames++
if .pci_device.vendor_id() == 0x1af4 and .pci_device.device_id() == 0x1000 {
.device.virtio.tx_frame(data)
}
}
}
fn main() {
println("$WW,1$")
mut config = Util::get_dictionary_from_json_file("M:/System/Config/Net.json")
mut net = Net::init(config)
println("[net] PCI device is {}", net.pci_device)
print("[net] MAC address is ")
for i in 0u16..5u16 {
print("{:0>2x}:", net.mac_address[i])
}
println("{:0>2x}", net.mac_address[5])
print("[net] IPv4 address is ")
for i in 0u16..3u16 {
print("{:d}.", net.tcpip.ipv4_address[i])
}
println("{:d}", net.tcpip.ipv4_address[3])
println(" ")
// Update the ARP cache entry for IPv4 gateway address
net.tcpip.send_arp_request(net.mac_address, net.tcpip.ipv4_gateway)
mut prev_rx_frames = net.tcpip.rx_frames
mut prev_tx_frames = net.tcpip.tx_frames
mut prev_jiffies = Time::jiffies()
while true {
net.process_events()
if (prev_rx_frames != net.tcpip.rx_frames) or (prev_tx_frames != net.tcpip.tx_frames) {
prev_rx_frames = net.tcpip.rx_frames
prev_tx_frames = net.tcpip.tx_frames
prev_jiffies = Time::jiffies()
}
if Time::jiffies() < prev_jiffies + 250 {
Time::sleep(0)
} else {
Time::sleep(1)
}
}
OS::exit()
}

29
src/net/os/ioport.jakt Normal file
View File

@@ -0,0 +1,29 @@
import extern c "ioport.h" {
extern fn ioport_read_u8(address: u16) -> u8
extern fn ioport_read_u16(address: u16) -> u16
extern fn ioport_read_u32(address: u16) -> u32
extern fn ioport_write_u8(address: u16, value: u8)
extern fn ioport_write_u16(address: u16, value: u16)
extern fn ioport_write_u32(address: u16, value: u32)
}
struct IOPort {
fn read_u8(anon address: u16) throws -> u8 {
return ioport_read_u8(address)
}
fn read_u16(anon address: u16) throws -> u16 {
return ioport_read_u16(address)
}
fn read_u32(anon address: u16) throws -> u32 {
return ioport_read_u32(address)
}
fn write_u8(address: u16, value: u8) {
return ioport_write_u8(address, value)
}
fn write_u16(address: u16, value: u16) {
return ioport_write_u16(address, value)
}
fn write_u32(address: u16, value: u32) {
return ioport_write_u32(address, value)
}
}

154
src/net/os/os.jakt Normal file
View File

@@ -0,0 +1,154 @@
import extern c "os.h" {
extern fn os_blink(frequency: raw c_char) -> bool
extern fn os_call(function_name: u64, arg: u64) -> u64
extern fn os_device_calloc(size: u32) -> u32
extern fn os_exit()
extern fn os_file_picker(path: raw c_char, glob: raw c_char)
extern fn os_files_list(path: raw c_char)
extern fn os_is_vm() -> bool
extern fn os_path_exists(anon path: raw c_char) -> bool
extern fn os_pc_speaker(frequency: raw c_char)
extern fn os_random() -> u64
extern fn os_screenshot()
extern fn os_to_uppercase(anon input_string: raw c_char) -> raw c_char
}
struct OS {
fn blink(frequency: f64 = 2.5) throws -> bool {
let frequency_as_string = format("{}", frequency)
return os_blink(frequency: frequency_as_string.c_string())
}
fn call(anon function_name: String, anon arg: String) throws -> u64 {
mut res: u64 = 0
unsafe {
cpp {
"
res = os_call((u64)function_name.characters(), (u64)arg.characters());
"
}
}
return res
}
fn device_calloc(anon size: u32) throws -> u32 {
return os_device_calloc(size)
}
fn device_copy_buffer(anon buffer: [u8]) -> u32 {
mut address: u32 = 0
mut size = buffer.size()
unsafe {
cpp {
"u8 *data = (u8*)os_device_calloc(size);
for (int i = 0; i < size; i++)
data[i] = buffer[i];
address = (uintptr_t)data;"
}
}
return address
}
fn exit() {
os_exit()
}
fn file_picker(path: String, glob: String) throws -> String {
mut s = StringBuilder::create()
unsafe {
cpp {
"char const *chars = os_file_picker(path.characters(), glob.characters());
s.append_c_string(chars);
delete(chars);"
}
}
return s.to_string()
}
fn files_list(path: String) throws -> [String] {
mut s = StringBuilder::create()
unsafe {
cpp {
"char const *chars = os_files_list(path.characters());
if (chars) {
s.append_c_string(chars);
delete(chars);
}"
}
}
return s.to_string().split(c'|')
}
fn path_exists(anon path: String) -> bool {
return os_path_exists(path.c_string())
}
fn is_vm() -> bool {
return os_is_vm()
}
fn pc_speaker(frequency: f64) throws {
let frequency_as_string = format("{}", frequency)
os_pc_speaker(frequency: frequency_as_string.c_string())
}
fn put_char(ch: u8) {
unsafe {
cpp {
"putchar(ch);"
}
}
}
fn random() -> u64 {
return os_random()
}
fn read_entire_file(anon filename: String) throws -> [u8] {
mut size = 0
mut buffer: [u8] = []
unsafe {
cpp {
"u8 *data = os_read_entire_file(filename.characters(), &size);
for (int i = 0; i < size; i++)
buffer.push(data[i]);
free(data);"
}
}
return buffer
}
fn read_device_memory(address: u32, size: i64) throws -> [u8] {
mut buffer: [u8] = [];
unsafe {
cpp {
"u8 *device_memory = (u8*)address;
for (int i = 0; i < size; i++)
buffer.push(device_memory[i]);"
}
}
return buffer
}
fn read_u16_from_device_memory(anon address: u32) throws -> u16 {
mut value: u16 = 0
unsafe {
cpp {
"value = *(u16*)address;"
}
}
return value
}
fn screenshot() {
os_screenshot()
}
fn to_uppercase(anon input_string: String) throws -> String {
mut s = StringBuilder::create()
unsafe {
cpp {
"char const *chars = os_to_uppercase(input_string.characters());
s.append_c_string(chars);
delete(chars);"
}
}
return s.to_string()
}
fn write_entire_file(filename: String, buffer: [u8]) {
mut size = buffer.size()
unsafe {
cpp {
"unsigned char *data = (unsigned char *)malloc(size);
for (int i = 0; i < size; i++)
data[i] = buffer[i];
os_write_entire_file(filename.characters(), data, size);
free(data);"
}
}
}
}

103
src/net/os/pci.jakt Normal file
View File

@@ -0,0 +1,103 @@
import ioport { IOPort }
import extern c "pci.h" {
extern fn pci_find(anon class_code: i64) -> i64
extern fn pci_read_u8(anon bus: i64, anon device: i64, anon fun: i64, anon offset: i64) -> u8
extern fn pci_read_u16(anon bus: i64, anon device: i64, anon fun: i64, anon offset: i64) -> u16
extern fn pci_read_u32(anon bus: i64, anon device: i64, anon fun: i64, anon offset: i64) -> u32
extern fn pci_write_u8(anon bus: i64, anon device: i64, anon fun: i64, anon offset: i64, anon value: u8)
extern fn pci_write_u16(anon bus: i64, anon device: i64, anon fun: i64, anon offset: i64, anon value: u16)
extern fn pci_write_u32(anon bus: i64, anon device: i64, anon fun: i64, anon offset: i64, anon value: u32)
}
struct PCIDevice {
bus: i64
device: i64
fun: i64
pci_vendor_id: u16
pci_device_id: u16
bar: [u32]
public fn enable_bus_master(mut this) {
.set_command(.command() | 0x4)
}
public fn read_u8(this, anon offset: i64) -> u8 {
return pci_read_u8(.bus, .device, .fun, offset)
}
public fn read_u16(this, anon offset: i64) -> u16 {
return pci_read_u16(.bus, .device, .fun, offset)
}
public fn read_u32(this, anon offset: i64) -> u32 {
return pci_read_u32(.bus, .device, .fun, offset)
}
public fn write_u8(this, offset: i64, value: u8) {
pci_write_u8(.bus, .device, .fun, offset, value)
}
public fn write_u16(this, offset: i64, value: u16) {
pci_write_u16(.bus, .device, .fun, offset, value)
}
public fn write_u32(this, offset: i64, value: u32) {
pci_write_u32(.bus, .device, .fun, offset, value)
}
public fn io_read_u8(this, anon offset: u16) throws -> u8 {
return IOPort::read_u8(.bar[0] as! u16 + offset)
}
public fn io_read_u16(this, anon offset: u16) throws -> u16 {
return IOPort::read_u16(.bar[0] as! u16 + offset)
}
public fn io_read_u32(this, anon offset: u16) throws -> u32 {
return IOPort::read_u32(.bar[0] as! u16 + offset)
}
public fn io_write_u8(this, offset: u16, value: u8) {
IOPort::write_u8(address: .bar[0] as! u16 + offset, value)
}
public fn io_write_u16(this, offset: u16, value: u16) {
IOPort::write_u16(address: .bar[0] as! u16 + offset, value)
}
public fn io_write_u32(this, offset: u16, value: u32) {
IOPort::write_u32(address: .bar[0] as! u16 + offset, value)
}
public fn vendor_id(this) -> u16 {
return .pci_vendor_id
}
public fn device_id(this) -> u16 {
return .pci_device_id
}
public fn command(this) -> u16 {
return pci_read_u16(.bus, .device, .fun, 0x4)
}
public fn set_command(this, anon value: u16) {
pci_write_u16(.bus, .device, .fun, offset: 0x4, value)
}
public fn status(this) -> u16 {
return pci_read_u16(.bus, .device, .fun, 0x6)
}
}
fn lookup_bar(bus: i64, device: i64, fun: i64, anon index: i64) -> u32 {
if index < 0 or index > 5 {
return 0xFFFFFFFF
}
return pci_read_u32(bus, device, fun, 0x10 + (index * 4)) & 0xFFFFFFFC
}
struct PCI {
public fn find_device_by_class_code(anon class_code: i64) throws -> PCIDevice {
let result = pci_find(class_code)
if result < 0 {
eprintln("error: device not found")
throw Error::from_errno(1)
}
let bus = (result >> 16) & 0xff
let device = (result >> 8) & 0xff
let fun = result & 0xff
let pci_vendor_id = pci_read_u16(bus, device, fun, 0x0)
let pci_device_id = pci_read_u16(bus, device, fun, 0x2)
mut bar: [u32] = []
for i in 0..5 {
bar.push(lookup_bar(bus, device, fun, i))
}
return PCIDevice(bus, device, fun, pci_vendor_id, pci_device_id, bar)
}
}

94
src/net/os/time.jakt Normal file
View File

@@ -0,0 +1,94 @@
import extern c "time.h" {
extern fn time_busy(anon duration: i64)
extern fn time_jiffies() -> i64
extern fn time_now() -> i64
extern fn time_sleep(anon duration: i64)
}
struct Time {
fn busy(anon duration: i64) {
time_busy(duration)
}
fn jiffies() throws -> i64 {
return time_jiffies()
}
fn now() throws -> i64 {
return time_now()
}
fn cdate_to_unix(anon cdate: i64) -> i64 {
// (cdate - Str2Date("1/1/1970") / CDATE_FREQ + NIST_TIME_OFFSET
return (cdate - 3090344933588992) / 49710 + 8575
}
fn unix_to_cdate(anon unix: i64) -> i64 {
// (unix - NIST_TIME_OFFSET) * CDATE_FREQ + Str2Date("1/1/1970")
return (unix - 8575) * 49710 + 3090344933588992
}
fn sleep(anon duration: i64) {
time_sleep(duration)
}
fn timestamp_from_unix(anon timestamp: i64) -> String {
let SECS_PER_DAY = 86400
let DAYS_PER_YEAR = 365
let DAYS_PER_LYEAR = 366
let DAYS_PER_LYEAR_PERIOD = 146097
let YEARS_PER_LYEAR_PERIOD = 400
mut days = timestamp / SECS_PER_DAY
mut remainder = timestamp - (days * SECS_PER_DAY)
if timestamp < 0 and remainder == 0 {
days++
remainder -= SECS_PER_DAY
}
mut cur_year = 0
mut months: [i64] = []
mut tmp_days = 0
let month_tab = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ]
let month_tab_leap = [ -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ]
tmp_days = days;
if tmp_days >= DAYS_PER_LYEAR_PERIOD or tmp_days <= -DAYS_PER_LYEAR_PERIOD {
cur_year += YEARS_PER_LYEAR_PERIOD * (tmp_days / DAYS_PER_LYEAR_PERIOD);
tmp_days -= DAYS_PER_LYEAR_PERIOD * (tmp_days / DAYS_PER_LYEAR_PERIOD);
}
while tmp_days >= DAYS_PER_LYEAR {
cur_year++;
if cur_year % 4 == 0 {
tmp_days -= DAYS_PER_LYEAR;
} else {
tmp_days -= DAYS_PER_YEAR;
}
}
if cur_year % 4 == 0 {
months = month_tab_leap
} else {
months = month_tab
}
mut i = 11
while i > 0 {
if tmp_days > months[i] {
break;
}
i--
}
let year = 1970 + cur_year
let month = i + 1
let day = tmp_days - months[i]
let hours = remainder / 3600
let minutes = (remainder - hours * 3600) / 60
let seconds = remainder % 60
mut sb = StringBuilder::create()
sb.clear()
sb.appendff("{:0>4d}-{:0>2d}-{:0>2d}T{:0>2d}:{:0>2d}:{:0>2d}.000Z", year, month, day, hours, minutes, seconds)
return sb.to_string()
}
fn timestamp_from_cdate(anon cdate: i64) -> String {
return timestamp_from_unix(cdate_to_unix(cdate))
}
}

1671
src/net/tcpip.jakt Normal file

File diff suppressed because it is too large Load Diff