From a9bd94e910c084988b70a7bc16d59248d3cb5b50 Mon Sep 17 00:00:00 2001
From: Able <abl3theabove@gmail.com>
Date: Sun, 28 Nov 2021 14:50:14 -0600
Subject: [PATCH] wasm work + LICENSE

---
 LICENSE                                     | 373 ++++++++++++++++++++
 ableos/Cargo.lock                           |  85 +++++
 ableos/Cargo.toml                           |   7 +
 ableos/src/allocator/mod.rs                 |   7 +-
 ableos/src/arch/aarch64/mod.rs              |   1 +
 ableos/src/arch/riscv/boards/virt/virt.lds  |  64 ----
 ableos/src/arch/x86_64/drivers/allocator.rs |  37 +-
 ableos/src/arch/x86_64/init.rs              |  12 +-
 ableos/src/arch/x86_64/mod.rs               |  15 +-
 ableos/src/kmain.rs                         |  27 ++
 ableos/src/relib/filesystem/mod.rs          |   0
 ableos/src/relib/network/mod.rs             |   0
 ableos/src/relib/time/kilotime.rs           | 114 +++---
 ableos/src/wasm/mod.rs                      | 101 ++++++
 ableos/src/wasm/rust.wasm                   | Bin 0 -> 174 bytes
 ableos/src/wasm/wasm_sys.rs                 |  77 ++++
 16 files changed, 780 insertions(+), 140 deletions(-)
 create mode 100644 LICENSE
 delete mode 100644 ableos/src/arch/riscv/boards/virt/virt.lds
 create mode 100644 ableos/src/relib/filesystem/mod.rs
 create mode 100644 ableos/src/relib/network/mod.rs
 create mode 100755 ableos/src/wasm/rust.wasm
 create mode 100644 ableos/src/wasm/wasm_sys.rs

diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..a612ad9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+    means each individual or legal entity that creates, contributes to
+    the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+    means the combination of the Contributions of others (if any) used
+    by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+    means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+    means Source Code Form to which the initial Contributor has attached
+    the notice in Exhibit A, the Executable Form of such Source Code
+    Form, and Modifications of such Source Code Form, in each case
+    including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+    means
+
+    (a) that the initial Contributor has attached the notice described
+        in Exhibit B to the Covered Software; or
+
+    (b) that the Covered Software was made available under the terms of
+        version 1.1 or earlier of the License, but not also under the
+        terms of a Secondary License.
+
+1.6. "Executable Form"
+    means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+    means a work that combines Covered Software with other material, in
+    a separate file or files, that is not Covered Software.
+
+1.8. "License"
+    means this document.
+
+1.9. "Licensable"
+    means having the right to grant, to the maximum extent possible,
+    whether at the time of the initial grant or subsequently, any and
+    all of the rights conveyed by this License.
+
+1.10. "Modifications"
+    means any of the following:
+
+    (a) any file in Source Code Form that results from an addition to,
+        deletion from, or modification of the contents of Covered
+        Software; or
+
+    (b) any new file in Source Code Form that contains any Covered
+        Software.
+
+1.11. "Patent Claims" of a Contributor
+    means any patent claim(s), including without limitation, method,
+    process, and apparatus claims, in any patent Licensable by such
+    Contributor that would be infringed, but for the grant of the
+    License, by the making, using, selling, offering for sale, having
+    made, import, or transfer of either its Contributions or its
+    Contributor Version.
+
+1.12. "Secondary License"
+    means either the GNU General Public License, Version 2.0, the GNU
+    Lesser General Public License, Version 2.1, the GNU Affero General
+    Public License, Version 3.0, or any later versions of those
+    licenses.
+
+1.13. "Source Code Form"
+    means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+    means an individual or a legal entity exercising rights under this
+    License. For legal entities, "You" includes any entity that
+    controls, is controlled by, or is under common control with You. For
+    purposes of this definition, "control" means (a) the power, direct
+    or indirect, to cause the direction or management of such entity,
+    whether by contract or otherwise, or (b) ownership of more than
+    fifty percent (50%) of the outstanding shares or beneficial
+    ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+    Licensable by such Contributor to use, reproduce, make available,
+    modify, display, perform, distribute, and otherwise exploit its
+    Contributions, either on an unmodified basis, with Modifications, or
+    as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+    for sale, have made, import, and otherwise transfer either its
+    Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+    or
+
+(b) for infringements caused by: (i) Your and any other third party's
+    modifications of Covered Software, or (ii) the combination of its
+    Contributions with other software (except as part of its Contributor
+    Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+    its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+    Form, as described in Section 3.1, and You must inform recipients of
+    the Executable Form how they can obtain a copy of such Source Code
+    Form by reasonable means in a timely manner, at a charge no more
+    than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+    License, or sublicense it under different terms, provided that the
+    license for the Executable Form does not attempt to limit or alter
+    the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+*                                                                      *
+*  6. Disclaimer of Warranty                                           *
+*  -------------------------                                           *
+*                                                                      *
+*  Covered Software is provided under this License on an "as is"       *
+*  basis, without warranty of any kind, either expressed, implied, or  *
+*  statutory, including, without limitation, warranties that the       *
+*  Covered Software is free of defects, merchantable, fit for a        *
+*  particular purpose or non-infringing. The entire risk as to the     *
+*  quality and performance of the Covered Software is with You.        *
+*  Should any Covered Software prove defective in any respect, You     *
+*  (not any Contributor) assume the cost of any necessary servicing,   *
+*  repair, or correction. This disclaimer of warranty constitutes an   *
+*  essential part of this License. No use of any Covered Software is   *
+*  authorized under this License except under this disclaimer.         *
+*                                                                      *
+************************************************************************
+
+************************************************************************
+*                                                                      *
+*  7. Limitation of Liability                                          *
+*  --------------------------                                          *
+*                                                                      *
+*  Under no circumstances and under no legal theory, whether tort      *
+*  (including negligence), contract, or otherwise, shall any           *
+*  Contributor, or anyone who distributes Covered Software as          *
+*  permitted above, be liable to You for any direct, indirect,         *
+*  special, incidental, or consequential damages of any character      *
+*  including, without limitation, damages for lost profits, loss of    *
+*  goodwill, work stoppage, computer failure or malfunction, or any    *
+*  and all other commercial damages or losses, even if such party      *
+*  shall have been informed of the possibility of such damages. This   *
+*  limitation of liability shall not apply to liability for death or   *
+*  personal injury resulting from such party's negligence to the       *
+*  extent applicable law prohibits such limitation. Some               *
+*  jurisdictions do not allow the exclusion or limitation of           *
+*  incidental or consequential damages, so this exclusion and          *
+*  limitation may not apply to You.                                    *
+*                                                                      *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+  This Source Code Form is subject to the terms of the Mozilla Public
+  License, v. 2.0. If a copy of the MPL was not distributed with this
+  file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+  This Source Code Form is "Incompatible With Secondary Licenses", as
+  defined by the Mozilla Public License, v. 2.0.
diff --git a/ableos/Cargo.lock b/ableos/Cargo.lock
index 25e01df..60b24d7 100644
--- a/ableos/Cargo.lock
+++ b/ableos/Cargo.lock
@@ -16,9 +16,16 @@ dependencies = [
  "spin",
  "uart_16550",
  "volatile 0.2.7",
+ "wasmi",
  "x86_64",
 ]
 
+[[package]]
+name = "autocfg"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
+
 [[package]]
 name = "bit_field"
 version = "0.10.1"
@@ -53,6 +60,12 @@ dependencies = [
  "syn",
 ]
 
+[[package]]
+name = "downcast-rs"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650"
+
 [[package]]
 name = "lazy_static"
 version = "1.4.0"
@@ -62,6 +75,12 @@ dependencies = [
  "spin",
 ]
 
+[[package]]
+name = "libm"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7d73b3f436185384286bd8098d17ec07c9a7d2388a6599f824d8502b529702a"
+
 [[package]]
 name = "linked_list_allocator"
 version = "0.9.1"
@@ -86,6 +105,42 @@ dependencies = [
  "scopeguard",
 ]
 
+[[package]]
+name = "memory_units"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71d96e3f3c0b6325d8ccd83c33b28acb183edcb6c67938ba104ec546854b0882"
+
+[[package]]
+name = "num-integer"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db"
+dependencies = [
+ "autocfg",
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c000134b5dbf44adc5cb772486d335293351644b801551abe8f75c84cfa4aef"
+dependencies = [
+ "autocfg",
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
+dependencies = [
+ "autocfg",
+]
+
 [[package]]
 name = "num_enum"
 version = "0.5.4"
@@ -107,6 +162,12 @@ dependencies = [
  "syn",
 ]
 
+[[package]]
+name = "parity-wasm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be5e13c266502aadf83426d87d81a0f5d1ef45b8027f5a471c360abfe4bfae92"
+
 [[package]]
 name = "paste"
 version = "0.1.18"
@@ -231,6 +292,30 @@ version = "0.4.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e4c2dbd44eb8b53973357e6e207e370f0c1059990df850aca1eca8947cf464f0"
 
+[[package]]
+name = "wasmi"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca00c5147c319a8ec91ec1a0edbec31e566ce2c9cc93b3f9bb86a9efd0eb795d"
+dependencies = [
+ "downcast-rs",
+ "libm",
+ "memory_units",
+ "num-rational",
+ "num-traits",
+ "parity-wasm",
+ "wasmi-validation",
+]
+
+[[package]]
+name = "wasmi-validation"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "165343ecd6c018fc09ebcae280752702c9a2ef3e6f8d02f1cfcbdb53ef6d7937"
+dependencies = [
+ "parity-wasm",
+]
+
 [[package]]
 name = "x86_64"
 version = "0.14.6"
diff --git a/ableos/Cargo.toml b/ableos/Cargo.toml
index 5996595..1b836a3 100644
--- a/ableos/Cargo.toml
+++ b/ableos/Cargo.toml
@@ -18,6 +18,13 @@ spin = "0.5.2"
 linked_list_allocator = "0.9.0"
 lliw = "0.2.0"
 
+[dependencies.wasmi]
+version = "*"
+default-features = false
+features = ["core"]
+
+
+
 [dependencies.lazy_static]
 features = ["spin_no_std"]
 version = "1.0"
diff --git a/ableos/src/allocator/mod.rs b/ableos/src/allocator/mod.rs
index e1e59f5..e52a0b6 100644
--- a/ableos/src/allocator/mod.rs
+++ b/ableos/src/allocator/mod.rs
@@ -8,10 +8,15 @@ pub const HEAP_BASE: usize = 100;
 pub const HEAP_SIZE: usize = HEAP_BASE * HEAP_MULTIPLIER;
 // X86 alloc should be in arch/drivers/x86/alloc.rs
 
+/*
 use crate::arch::drivers::allocator::Dummy;
-
 #[global_allocator]
 static ALLOCATOR: Dummy = Dummy;
+*/
+use linked_list_allocator::LockedHeap;
+
+#[global_allocator]
+pub static ALLOCATOR: LockedHeap = LockedHeap::empty();
 
 #[alloc_error_handler]
 fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! {
diff --git a/ableos/src/arch/aarch64/mod.rs b/ableos/src/arch/aarch64/mod.rs
index bbcf6f1..5b045bb 100644
--- a/ableos/src/arch/aarch64/mod.rs
+++ b/ableos/src/arch/aarch64/mod.rs
@@ -32,6 +32,7 @@ pub extern "C" fn not_main() {
             ptr::write_volatile(UART0, *byte);
         }
     }
+
     //
     // let gpios = Pins::take();
     // let mut led = gpios.p0_31;
diff --git a/ableos/src/arch/riscv/boards/virt/virt.lds b/ableos/src/arch/riscv/boards/virt/virt.lds
deleted file mode 100644
index c471c85..0000000
--- a/ableos/src/arch/riscv/boards/virt/virt.lds
+++ /dev/null
@@ -1,64 +0,0 @@
-OUTPUT_ARCH(riscv64gc)
-
-ENTRY(_boot);
-
-
-SECTIONS {
-    . = 0x80200000;
-    .text : {
-        PROVIDE(__text_start = .);
-        PROVIDE(KERNEL_START = .);
-        *(.init.boot)
-        *(.init.rust)
-        *(.text .text.*)
-        . = ALIGN(4K);
-        PROVIDE(__text_end = .);
-    }
-
-    .data : {
-        PROVIDE(__data_start = .);
-        *(.data .data.* .rodata .rodata.*)
-        . = ALIGN(8);
-        PROVIDE(__tmp_stack_bottom = .);
-        . += 1024 * 1024 * 4;
-        PROVIDE(__tmp_stack_top = .);
-        . += 4096;
-        PROVIDE(__scratch_stack = .);
-        . = ALIGN(8);
-    }
-
-    . = ALIGN(8);
-
-    .sdata : {
-        PROVIDE(__global_pointer$ = .);
-        *(.sdata .sdata.*)       
-        . = ALIGN(4K);
-        PROVIDE(__data_end = .); 
-    }
-
-    PROVIDE(__bss_start = .);
-    .sbss : {
-        *(.sbss .sbss.*);
-    }
-
-    .bss : {
-        *(.bss .bss.*)
-    }
-    . = ALIGN(4K);
-    PROVIDE(__bss_end = .);
-
-    .tdata : {
-        . = ALIGN(4K);
-        PROVIDE(__tdata_start = .);
-        
-        *(.tdata .tdata.*)
-
-        . = ALIGN(4K);
-        PROVIDE(__tdata_end = .);
-    }
-
-    . = ALIGN(2M);
-    PROVIDE(KERNEL_END = .);
-
-    /DISCARD/ : { *(.eh_frame_hdr .eh_frame) }
-}
diff --git a/ableos/src/arch/x86_64/drivers/allocator.rs b/ableos/src/arch/x86_64/drivers/allocator.rs
index d12915c..2b8c708 100644
--- a/ableos/src/arch/x86_64/drivers/allocator.rs
+++ b/ableos/src/arch/x86_64/drivers/allocator.rs
@@ -1,7 +1,13 @@
 use alloc::alloc::{GlobalAlloc, Layout};
 // use core::alloc::{GlobalAlloc, Layout};
+use crate::allocator::{HEAP_SIZE, HEAP_START};
 use core::ptr::null_mut;
-
+use x86_64::{
+    structures::paging::{
+        mapper::MapToError, FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB,
+    },
+    VirtAddr,
+};
 pub struct Dummy;
 
 unsafe impl GlobalAlloc for Dummy {
@@ -13,3 +19,32 @@ unsafe impl GlobalAlloc for Dummy {
         panic!("dealloc should be never called")
     }
 }
+
+pub fn init_heap(
+    mapper: &mut impl Mapper<Size4KiB>,
+    frame_allocator: &mut impl FrameAllocator<Size4KiB>,
+) -> Result<(), MapToError<Size4KiB>> {
+    let page_range = {
+        let heap_start = VirtAddr::new(HEAP_START as u64);
+        let heap_end = heap_start + HEAP_SIZE - 1u64;
+        let heap_start_page = Page::containing_address(heap_start);
+        let heap_end_page = Page::containing_address(heap_end);
+        Page::range_inclusive(heap_start_page, heap_end_page)
+    };
+
+    for page in page_range {
+        let frame = frame_allocator
+            .allocate_frame()
+            .ok_or(MapToError::FrameAllocationFailed)?;
+        let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
+        unsafe { mapper.map_to(page, frame, flags, frame_allocator)?.flush() };
+    }
+
+    unsafe {
+        crate::allocator::ALLOCATOR
+            .lock()
+            .init(HEAP_START, HEAP_SIZE);
+    }
+
+    Ok(())
+}
diff --git a/ableos/src/arch/x86_64/init.rs b/ableos/src/arch/x86_64/init.rs
index 853310c..62f4e66 100644
--- a/ableos/src/arch/x86_64/init.rs
+++ b/ableos/src/arch/x86_64/init.rs
@@ -2,10 +2,10 @@
 use super::{gdt, interrupts};
 use crate::{println, serial_println};
 pub fn init() {
-	gdt::init();
-	interrupts::init_idt();
-	unsafe { interrupts::PICS.lock().initialize() };
-	x86_64::instructions::interrupts::enable();
-	println!("Initialized");
-	serial_println!("Initialized");
+    gdt::init();
+    interrupts::init_idt();
+    unsafe { interrupts::PICS.lock().initialize() };
+    x86_64::instructions::interrupts::enable();
+    println!("Initialized");
+    serial_println!("Initialized");
 }
diff --git a/ableos/src/arch/x86_64/mod.rs b/ableos/src/arch/x86_64/mod.rs
index c5059c2..eb0dea8 100644
--- a/ableos/src/arch/x86_64/mod.rs
+++ b/ableos/src/arch/x86_64/mod.rs
@@ -1,10 +1,10 @@
+use crate::arch::drivers::allocator; // new import
+use bootloader::{entry_point, BootInfo};
 use x86_64::{
     instructions::hlt,
     {structures::paging::Page, VirtAddr},
 };
 
-use bootloader::{entry_point, BootInfo};
-
 pub mod drivers;
 pub mod gdt;
 pub mod init;
@@ -26,6 +26,8 @@ pub fn start(boot_info: &'static BootInfo) -> ! {
     let page_ptr: *mut u64 = page.start_address().as_mut_ptr();
     unsafe { page_ptr.offset(400).write_volatile(0xf021_f077_f065_804e) };
 
+    allocator::init_heap(&mut mapper, &mut frame_allocator).expect("heap initialization failed");
+
     crate::kmain::kernel_main();
 
     // sloop();
@@ -45,12 +47,3 @@ pub fn sloop() -> ! {
         hlt();
     }
 }
-
-/*
-#[cfg(test)]
-pub fn test_runner(tests: &[&dyn Fn()]) {
-    for test in tests {
-        test();
-    }
-}
-*/
diff --git a/ableos/src/kmain.rs b/ableos/src/kmain.rs
index 658bf38..d6ff17a 100644
--- a/ableos/src/kmain.rs
+++ b/ableos/src/kmain.rs
@@ -1,4 +1,5 @@
 #![allow(clippy::empty_loop)]
+
 use crate::{
     arch::{drivers::graphics::GraphicsBuffer, init, sloop},
     driver_traits::graphics::Graphics,
@@ -7,6 +8,7 @@ use crate::{
     relib::math::rand::RAND_HANDLE,
 };
 
+use alloc::{boxed::Box, rc::Rc};
 use lazy_static::lazy_static;
 
 #[no_mangle]
@@ -35,8 +37,33 @@ pub fn kernel_main() -> ! {
         use alloc::{vec, vec::Vec};
         let x: Vec<u8> = vec![1];
         println!("{:?}", x);
+
+        let heap_value = Box::new(41);
+        println!("heap_value at {:p}", heap_value);
+
+        // create a dynamically sized vector
+        let mut vec = Vec::new();
+        for i in 0..500 {
+            vec.push(i);
+        }
+        println!("vec at {:p}", vec.as_slice());
+
+        // create a reference counted vector -> will be freed when count reaches 0
+        let reference_counted = Rc::new(vec![1, 2, 3]);
+        let cloned_reference = reference_counted.clone();
+        println!(
+            "current reference count is {}",
+            Rc::strong_count(&cloned_reference)
+        );
+        core::mem::drop(reference_counted);
+        println!(
+            "reference count is {} now",
+            Rc::strong_count(&cloned_reference)
+        );
     }
 
+    // crate::wasm::evaluate();
+
     /* If AES is present then AES init rng as well
     // Maybe via a cfg
         AES::init_rng();
diff --git a/ableos/src/relib/filesystem/mod.rs b/ableos/src/relib/filesystem/mod.rs
new file mode 100644
index 0000000..e69de29
diff --git a/ableos/src/relib/network/mod.rs b/ableos/src/relib/network/mod.rs
new file mode 100644
index 0000000..e69de29
diff --git a/ableos/src/relib/time/kilotime.rs b/ableos/src/relib/time/kilotime.rs
index 4941da8..c180f9f 100644
--- a/ableos/src/relib/time/kilotime.rs
+++ b/ableos/src/relib/time/kilotime.rs
@@ -4,69 +4,69 @@ use core::fmt::{Display, Error, Formatter};
 #[repr(transparent)]
 pub struct Kilosecond(usize);
 impl Display for Kilosecond {
-	fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
-		let mut reg = self.0;
-		let mut buf = [0u8, 0, 0, 0, 0];
-		let mut n = 0;
-		while n < 8 {
-			if n > 2 {
-				buf[7 - n] = match reg % 10 {
-					0 => b'0',
-					1 => b'1',
-					2 => b'2',
-					3 => b'3',
-					4 => b'4',
-					5 => b'5',
-					6 => b'6',
-					7 => b'7',
-					8 => b'8',
-					9 => b'9',
-					_ => unreachable!["CPU is borken"],
-				};
-			}
-			reg /= 10;
-			n += 1;
-		}
-		for (n, b) in buf.iter().enumerate() {
-			write![f, "{}", *b as char]?;
-			if n == 1 {
-				write![f, "."]?;
-			}
-		}
-		Ok(())
-	}
+    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
+        let mut reg = self.0;
+        let mut buf = [0u8, 0, 0, 0, 0];
+        let mut n = 0;
+        while n < 8 {
+            if n > 2 {
+                buf[7 - n] = match reg % 10 {
+                    0 => b'0',
+                    1 => b'1',
+                    2 => b'2',
+                    3 => b'3',
+                    4 => b'4',
+                    5 => b'5',
+                    6 => b'6',
+                    7 => b'7',
+                    8 => b'8',
+                    9 => b'9',
+                    _ => unreachable!["CPU is borken"],
+                };
+            }
+            reg /= 10;
+            n += 1;
+        }
+        for (n, b) in buf.iter().enumerate() {
+            write![f, "{}", *b as char]?;
+            if n == 1 {
+                write![f, "."]?;
+            }
+        }
+        Ok(())
+    }
 }
 impl core::ops::Add for Kilosecond {
-	type Output = Self;
-	fn add(self, rhs: Self) -> Self {
-		Self(self.0 + rhs.0)
-	}
+    type Output = Self;
+    fn add(self, rhs: Self) -> Self {
+        Self(self.0 + rhs.0)
+    }
 }
 impl core::ops::Sub for Kilosecond {
-	type Output = Self;
-	fn sub(self, rhs: Self) -> Self {
-		Self(self.0 - rhs.0)
-	}
+    type Output = Self;
+    fn sub(self, rhs: Self) -> Self {
+        Self(self.0 - rhs.0)
+    }
 }
 impl From<Time> for Kilosecond {
-	fn from(t: Time) -> Self {
-		Self((t.hour as usize * 3600 + t.minutes as usize * 60 + t.seconds as usize) * 1000)
-	}
+    fn from(t: Time) -> Self {
+        Self((t.hour as usize * 3600 + t.minutes as usize * 60 + t.seconds as usize) * 1000)
+    }
 }
 impl Kilosecond {
-	pub fn from_ms(ms: usize) -> Self {
-		Self(ms)
-	}
-	pub fn from_sec(sec: usize) -> Self {
-		Self(sec * 1000)
-	}
-	pub fn from_minutes(min: usize) -> Self {
-		Self(min * 60 * 1000)
-	}
-	pub fn from_hours(hrs: usize) -> Self {
-		Self(hrs * 60 * 60 * 1000)
-	}
-	pub fn from_days(days: usize) -> Self {
-		Self(days * 24 * 60 * 60 * 1000)
-	}
+    pub fn from_ms(ms: usize) -> Self {
+        Self(ms)
+    }
+    pub fn from_sec(sec: usize) -> Self {
+        Self(sec * 1000)
+    }
+    pub fn from_minutes(min: usize) -> Self {
+        Self(min * 60 * 1000)
+    }
+    pub fn from_hours(hrs: usize) -> Self {
+        Self(hrs * 60 * 60 * 1000)
+    }
+    pub fn from_days(days: usize) -> Self {
+        Self(days * 24 * 60 * 60 * 1000)
+    }
 }
diff --git a/ableos/src/wasm/mod.rs b/ableos/src/wasm/mod.rs
index 8b13789..01fd336 100644
--- a/ableos/src/wasm/mod.rs
+++ b/ableos/src/wasm/mod.rs
@@ -1 +1,102 @@
+// use wabt;
+use wasmi::{
+    Error, Externals, FuncInstance, FuncRef, ImportsBuilder, ModuleImportResolver, ModuleInstance,
+    RuntimeArgs, RuntimeValue, Signature, Trap, ValueType,
+};
 
+mod wasm_sys;
+use alloc::format;
+use wasm_sys::SysCall;
+struct HostFunctions;
+impl HostFunctions {
+    fn check_signature(&self, index: usize, signature: &Signature) -> bool {
+        let (params, ret_ty): (&[ValueType], Option<ValueType>) = match index.into() {
+            SysCall::KILL => (&[], None),
+            SysCall::EMPTY => (&[], None),
+            _ => return false,
+        };
+        signature.params() == params && signature.return_type() == ret_ty
+    }
+}
+impl Externals for HostFunctions {
+    fn invoke_index(
+        &mut self,
+        index: usize,
+        _args: RuntimeArgs,
+    ) -> Result<Option<RuntimeValue>, Trap> {
+        match index.into() {
+            // Take in one arg discard the rest
+            SysCall::KILL => {
+                println!("Program killed");
+                Ok(None)
+            }
+            // Do nothing
+            SysCall::EMPTY => Ok(None),
+            SysCall::EXIT => Ok(None),
+            SysCall::CONSOLE_RESET => Ok(None),
+            SysCall::CONSOLE_IN => Ok(None),
+            SysCall::CONSOLE_OUT => Ok(None),
+            SysCall::CONSOLE_GET_TITLE => Ok(None),
+            SysCall::CONSOLE_SET_TITLE => Ok(None),
+            _ => panic!("Unimplemented function at {}", index),
+        }
+    }
+}
+impl ModuleImportResolver for HostFunctions {
+    fn resolve_func(&self, field_name: &str, signature: &Signature) -> Result<FuncRef, Error> {
+        let index = match field_name {
+            "kill" => SysCall::KILL as usize,
+            "empty" => SysCall::EMPTY as usize,
+            "exit" => SysCall::EXIT as usize,
+            _ => {
+                return Err(Error::Instantiation(format!(
+                    "Export {} not found",
+                    field_name
+                )))
+            }
+        };
+
+        if !self.check_signature(index, signature) {
+            return Err(Error::Instantiation(format!(
+                "Export {} has a bad signature",
+                field_name
+            )));
+        }
+
+        Ok(FuncInstance::alloc_host(
+            Signature::new(&[][..], None),
+            index,
+        ))
+    }
+}
+
+pub fn evaluate() {
+    let wasm_binary = // Spacer
+    include_bytes!("rust.wasm");
+
+    // Load wasm binary and prepare it for instantiation.
+    let module = wasmi::Module::from_buffer(&wasm_binary).expect("failed to load wasm");
+
+    let imports = ImportsBuilder::new().with_resolver("env", &HostFunctions);
+
+    // Instantiate a module with empty imports and
+    // assert that there is no `start` function.
+    let instance = ModuleInstance::new(&module, &imports)
+        .expect("failed to instantiate wasm module")
+        .assert_no_start();
+
+    // Finally, invoke the exported function "test" with no parameters
+    // and empty external function executor.
+    let result: i32 = instance
+        .invoke_export("_start", &[], &mut HostFunctions)
+        // .with_resolver(&mut HostFunctions)
+        .expect("failed to execute export")
+        .unwrap()
+        .try_into()
+        .unwrap();
+
+    println!(
+        "{:?}",
+        result // .unwrap()
+    );
+}
diff --git a/ableos/src/wasm/rust.wasm b/ableos/src/wasm/rust.wasm
new file mode 100755
index 0000000000000000000000000000000000000000..d3da416ab20c48e1073bd77edc5256b64bf2e0c3
GIT binary patch
literal 174
zcmY+7O%8%E7zN*J5e$$(+<65T-hq>RRB0lC7E&4$S8z0s=1<%>o7v64ERF!US1r(j
zt179jzb8XKj(}F=P7`%{)GM29d!ktJ@9dnU&blc)6jE8D2@%XiIungp-)R;iH*03O
mn8j+9m&{RbZ_u#7De=ZxRtn!Ie~IisRPxDP2brhdM;l)1_$o~R

literal 0
HcmV?d00001

diff --git a/ableos/src/wasm/wasm_sys.rs b/ableos/src/wasm/wasm_sys.rs
new file mode 100644
index 0000000..349a521
--- /dev/null
+++ b/ableos/src/wasm/wasm_sys.rs
@@ -0,0 +1,77 @@
+macro_rules! syscall_enum {
+   () => {};
+   (@get_last $Variant:ident) => {
+      Self::$Variant
+   };
+   (@get_last $Variant:ident, $($VariantTail:ident),*) => {
+      syscall_enum![@get_last $($VariantTail),*]
+   };
+   ($($Variant:ident=$Value:expr,)*) => {
+      #[repr(usize)]
+      pub enum SysCall {
+         $($Variant = $Value),*
+      }
+
+      impl core::convert::From<usize> for SysCall {
+         fn from(n: usize) -> Self {
+            match n {
+               $($Value => Self::$Variant),*,
+               _ => syscall_enum![@get_last $($Variant),*]
+            }
+         }
+      }
+   };
+   ($($Variant:ident=$Value:expr),* ) => {
+      syscall_enum!($($Variant=$Value,)* );
+   };
+}
+
+syscall_enum! {
+   KILL=0,              // Provide a PID
+   CONSOLE_RESET=1,     // Reset the console
+   CONSOLE_IN=2,        // Console Input
+   CONSOLE_OUT=3,       // Console output
+   CONSOLE_GET_TITLE=4, // Get the console title
+   CONSOLE_SET_TITLE=5, // Set the console title
+   GET_PID=6,           // Get the proccess ID
+   PROCESS_INFO=7,      // Get information about the process
+   //scheduler Related Syscals
+   GET_PRIORITY=10, // Get scheduler priority
+   SET_PRIORITY=11, // Set scheduler priority
+   //
+   GET_HOSTNAME=12,
+   SET_HOSTNAME=13,
+
+   //File Related syscalls
+   //
+   MAKE_DIRECTORY=22,       //
+   DELETE_DIRECTORY=23,     //
+   RENAME_DIRECTORY=24,     //
+   SET_DIRECTORY_ACCESS=25, //
+   //
+   MAKE_FILE=26,       //
+   DELETE_FILE=27,     //
+   RENAME_FILE=28,     //
+   SET_FILE_ACCESS=29, //
+
+   FILE_READ=30,
+   FILE_WRITE=31,
+
+   SLEEP=32, // Sleep in milliseconds
+   SLEEP_UNTIL=33, // Sleep until this time in milliseconds (if this is below the current time return)
+   NANOSLEEP=34, // Sleep in nanoseconds
+   NANOSLEEP_UNTIL=35, // Sleep until this time nanoseconds (if this is below the current time return)
+   GET_TIME=36,          // Gets the system time (some derivitive of seconds)
+   SET_TIME=37,          // Sets the system time (some derivitive of seconds)
+
+
+   // Socket SysCall
+   SOCKET_BIND=39, // Used by servers to lock a port
+   SOCKET_CONNECT=40,
+   SOCKET_DISCONNECT=41,
+   SOCKET_SEND=42,
+   SOCKET_RECEIVE=43,
+
+   EXIT=50,
+   EMPTY=0xFFFF,
+}