-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshare.txt
More file actions
executable file
·9705 lines (7648 loc) · 405 KB
/
share.txt
File metadata and controls
executable file
·9705 lines (7648 loc) · 405 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
filePath .sharing/archiveBuffer/debug.json
```json
{
"lineSpecific": {
"4": "registers ALL",
"3": "memoryRange 0 10"
},
"eachIteration": [
"registers",
"memoryRange 0 63",
"descriptors",
"stack"
]
}
-------------------------------
```
filePath .sharing/archiveBuffer/config.json
```json
{
"stackSize": 32,
"memorySize": 99999,
"hertz": 0,
"locations": [
{
"requirement": "helpInfo",
"path": "src/main/resources/help.jsonc"
},
{
"requirement": "stdlib",
"path": "src/main/resources/lib"
},
{
"requirement": "debug",
"path": "debug.json"
}
]
}
-------------------------------
```
filePath .sharing/archiveBuffer/docs/System-Call-Implementation.md
```markdown
# MVM System Call Implementation
This document details how system calls are implemented in the MVM (Micro Virtual Machine). System calls provide a
mechanism for user-space programs to request services from the kernel.
## System Call Interface
User programs invoke system calls using the `syscall` instruction. The system call ID is passed in register `S1`.
Arguments are passed in registers `S2`, `S3`, and `S4`. The result (if any) is stored in `R2` by the system call
handler.
## System Call Handling
The system call mechanism involves:
1. **`syscall` Instruction:** A user program executes the `syscall` instruction.
2. **Trap:** The VM's execution engine detects the `syscall` instruction. This triggers a trap or interrupt, switching
execution to kernel mode.
3. **System Call Handler (`SystemCallHandler.kt`):** The system call handler:
- Retrieves the system call ID from register `S1`.
- Retrieves any arguments passed by the user program from registers `S2`, `S3`, and `S4`.
- Calls the appropriate kernel function to handle the system call. This is handled in the `SystemCall.execute`
function which uses a `when` statement to call the correct function.
- Stores the return values (if any) in `R2`.
4. **Return to User Mode:** Once the system call is handled, execution returns to the user program.
## Example: `readFile` System Call
Let's trace the steps for `readFile`:
1. **User Program:** A user program calls `readFile` using the `syscall` instruction:
```assembly
lit S1 2 // System call ID for readFile
str S2 "file name.txt" // Address of the filename string
syscall // Make system call
printr R2 // Retrieve the result (address of data)
```
2. **Trap:** The `syscall` instruction causes a trap to the kernel.
3. **System Call Handler:**
- The system call handler in `SystemCallHandler.kt` detects the system call ID (`2`).
- It calls the `readFile` function in `internals.systemCalls.calls.readFile.kt`, passing the filename address (
`filename_address`) from register `S2`.
4. **`readFile` Function (`internals.systemCalls.calls.readFile.kt`):**
```kotlin
fun SystemCall.readFile(nameX: RegisterType) = call("readFile") {
val name = helpers.readRegisterString(nameX)
val out = (vm.vfs.read(name) ?: errors.FileNotFoundException(name)) as String
val spot = helpers.writeClosestString(out)
registers.write(RegisterType.R2, spot)
}
```
- This function interacts with the virtual file system (`vm.vfs`) to read the file's content.
- The function then uses the `writeClosestString` helper function to copy the data into memory.
- The function places the address of the data (from the VFS) on the stack.
5. **Return to User Mode:** The system call handler returns control to the user program. The user program can then
access the data from the address stored in `R2`.
## Key Considerations
* **Error Handling:** Each system call function should implement robust error handling, returning error codes or raising
exceptions. The system call handler should manage these errors appropriately.
* **Concurrency:** You'll need to ensure that system calls are handled concurrently if you have multiple processes
running. Synchronisation mechanisms might be needed if a system call involves shared resources.
* **Kernel Design:** The design of your kernel (in `os/OS.kt`) determines how efficient and robust system calls are.
* **Documentation:** Clearly document each system call, its arguments, return values, and potential error conditions in
your System Call Table and the associated documentation.
This detailed explanation clarifies the system call implementation in the MVM.
The system call handler is a central point where user programs interact with the kernel.
It's a key element in the design of your virtual machine.
Each system call is responsible for managing any necessary resources,
interacting with virtual devices, and performing necessary actions.
Return values are always stored on the stack, which is managed by the VM's runtime environment.
-------------------------------
```
filePath .sharing/archiveBuffer/docs/System-Calls-Table.md
```markdown
# System Call Table
| ID (S1) | System Call Name | Description | Argument 1 | Argument 2 | Argument 3 | Return Value (R2) | Notes |
|---------|------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------|---------------------------------|----------------------|---------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 | `newFile` | Creates a new file (`File Name`) in the VFS. | `File Name` (String pointer) | - | - | - | Throws a VM halting error if file is not found. A work around is planed |
| 2 | `readFile` | Reads data from a file (`File Name`) in the VFS into memory. Returns the Address stored | `File Name` (String pointer) | - | - | File content pointer | - |
| 3 | `writeFile` | Writes data from `File Content` to a file,`File Name` in the VFS. | `File Name` (String pointer) | `File Content` (String Pointer) | | - | Writes `Length` bytes. Returns an error code if the file is not found or writable. |
| 4 | `listFiles` | Lists all files and directories in the VFS. | - | - | - | Array of names (pointer) | **Not yet implemented!!!!** |
| 5 | `deleteFile` | Deletes a file or directory, `Path` from the VFS. | `Path` (String pointer) | - | - | - | Returns an error code if the path does not exist or if deletion fails. The order of deletion is not guaranteed. |
| 6 | `exit` | Terminates the current process with exit code, `Exit Code`. | `Exit Code` (Long) | - | - | - | this is a system-wide halt. Planed to only halt the process |
| 7 | `exec` | Executes a new program, `Program Path` using the host OS. | `Program Path` (String pointer) | - | - | - | - |
| 8 | `fork` | Creates a child process (a copy of the current process, the MVM instance). | - | - | - | Child Process ID (Long) | The child process will have a separate address space but shares the same initial code. |
| 9 | `spawn` | Creates a new process and runs a program file, `KAR Program Path`. | `KAR Program Path` (String pointer) | - | - | Process ID (Long) | The parent process continues execution concurrently with the new child process. |
| 10 | `share_m` | Establishes a shared memory region between the current process and `Wanted Process ID`. Shares memory address's from `Start Address` to `End Address` | `Wanted Process ID` (Long) | `Start Address` (Long) | `End Address` (Long) | Shared Memory ID (Long) | **IMPORTANT** These syscalls are being reworked and are **unstable** \| Returns the ID of the shared memory region. Shared memory regions are managed by the kernel. |
| 11 | `pause_t` | Pauses the specified process, `Process ID`. | `Process ID` (Long) | - | - | - | **IMPORTANT** These syscalls are being reworked and are **unstable** \| The process will remain paused until resumed with `continue_t`. |
| 12 | `continue_t` | Resumes a paused process, `Process ID`. | `Process ID` (Long) | - | - | - | **IMPORTANT** These syscalls are being reworked and are **unstable** \| The process will resume execution from where it left off. |
| 14 | `time` | Gets the current system time in milliseconds. | - | - | - | Time (Long) | - |
| 16 | `getpid` | Gets the process ID of the current process. | - | - | - | Process ID (Long) | - |
| 17 | `getuid` | Gets the user ID of the current process. | - | - | - | User ID (Long) | - |
| 18 | `handleSignals` | Registers a signal handler. When a signal is received, execution jumps to a specified line. | `Signal Number` (Long) | `Jump Address` (Long) | - | - | Signal handling is performed with signals generated from the host OS. The handling of signals in this way is not guaranteed. |
| 19 | `sendSignal` | Sends a signal to another process. | `Target Process` ID (Long) | `Signal Number` (Long) | - | - | Sends a signal to the specified process. The sending and receiving of signals is not guaranteed. |
| 24 | `writeIo` | Writes a null-terminated string to the console. | `String Address` (String Pointer) | - | - | - | The string is printed to the console. |
| 25 | `readIo` | Reads a line from standard input. | - | - | - | String Address (String pointer) | The string is read from standard input, but it allocates memory; make sure to deallocate memory once you're done with it. |
| 26 | `createArray` | Creates a new array. | `Size` (Long) | - | - | Array Address (Long) | - |
| 27 | `arraySet` | Sets an element in an array. | `Array` Address (Long) | `Index` (Long) | `Value` (Long) | - | Performs bounds checking. |
| 28 | `arrayGet` | Gets an element from an array. | `Array` Address (Long) | `Index` (Long) | - | Value (Long) | Performs bounds checking. |
-------------------------------
```
filePath .sharing/archiveBuffer/docs/Informational-Registers.md
```markdown
# Informational Register Table
These registers hold status information and flags. They are not directly manipulated by most instructions, but
instructions may set their values based on the result of an operation.
| Register | Symbol | Name | Implemented | Description | Notes |
|----------|--------|--------------------------|-------------|----------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| I1 | ZF | Zero Flag | Yes | Set to 1 if the result of the last arithmetic or logical operation was zero; otherwise, it's 0. | Reset to 0 after each instruction that can change it (except jumps and branches). |
| I2 | SF | Sign Flag | Yes | Set to 1 if the result of the last arithmetic operation was negative; otherwise, it's 0. | Reset to 0 after each arithmetic operation. |
| I3 | GF | Greater Than Flag | Yes | Set to 0 if the result of the last comparison (`GT`, `LT`) was true; otherwise, it's 1. | Reset after each comparison. |
| I4 | EF | Equal Flag | Yes | Set to 1 if the result of the last comparison (`EQ`) was true; otherwise, it's 0. | Reset after each comparison. |
| I5 | SCSF | System Call Success Flag | No | Set to 1 if the last system call executed successfully; otherwise, it's 0. | Reset after each system call. |
| I6 | ENSF | Error Non-Specific Flag | Somewhat | Set to 1 if a non-specific error (e.g., file not found, memory allocation failure) occurred, otherwise it's 0. | Set by several system calls, instructions, and functions that can result in errors. Resets after handling an error. |
| I7 | ESF | Error Specific Flag | No | Set to a specific error code in the case of an error; otherwise, it's 0. | Set by functions, instructions and system calls. Contains the specific code for the error, which should be looked up. |
| I8 | PC | Program Counter | Yes | Holds the address (line number) of the next instruction to be executed. | Not directly modified by most instructions. Modified by `jmp`, `jz`, `jnz`, function calls and returns. |
| I9 | SIGR | Signal Received | No | Set to the signal received from another process; otherwise, it's 0. | Reset to 0 after handling the signal. |
| I10 | MB | Mailbox ID | No | Holds the ID of the mailbox for inter-process communication. | **IPC is still in development** \| Set when a new connection is made. |
## Notes
- **Resetting Flags:** Many flags are automatically reset after an operation that might modify them. This prevents the
flags from interfering with later operations.
- **Error Handling:** `I6` (ENSF) and `I7` (ESF) are essential parts of your error handling mechanism. Use them to
indicate that an error has occurred. You can check their values to perform fault handling in the program.
-------------------------------
```
filePath .sharing/archiveBuffer/docs/DataTypes.md
```markdown
# MVM Data Types
The Micro Virtual Machine (MVM) supports several fundamental data types. These types are used in instructions, system
calls, and within the standard library functions. The MVM uses a 64-bit architecture, but some instructions and
functions can operate on smaller data types as specified by the `SETTYPE` instruction. All values are stored in memory
as 64-bit Longs unless otherwise specified. The data type stored in the registers is tracked by using the `RegisterData`
class which you can change at any time using the `SETTYPE` instruction. If an instruction or system call that operates
on a smaller data type is used, but the register is a larger type, then the value will be truncated to fit that type.
## Fundamental Data Types
### Integer Types
| Type | Size (bits) | Range | Notes |
|---------|-------------|---------------------------------------------------------|----------------------------------------------------------------------|
| `Byte` | 8 | -128 to 127 | Signed 8-bit integer. |
| `Short` | 16 | -32,768 to 32,767 | Signed 16-bit integer. |
| `Int` | 32 | -2,147,483,648 to 2,147,483,647 | Signed 32-bit integer. |
| `Long` | 64 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | Signed 64-bit integer. This is the default data type for registers. |
### Floating-Point Types
| Type | Size (bits) | Notes |
|----------|-------------|----------------------------------------------------|
| `Float` | 32 | Single-precision floating-point number (IEEE 754). |
| `Double` | 64 | Double-precision floating-point number (IEEE 754). |
### String Type
Strings are represented as null-terminated sequences of characters in memory. Each character occupies one word (64
bits).
### Boolean Type
Boolean values are represented using 64-bit Longs. The integer value of 0 represents false, and 1 represents true.
## Register Data Types
The `SETTYPE` instruction allows you to change the data type stored in a register at runtime. This allows for flexible
use of memory by being able to change data types as needed.
| Data Type | Description | Size (bits) | Example |
|-----------|-----------------------------------------------------------|-------------|-----------------------------|
| `Byte` | 8-bit signed integer | 8 | `settype G1 Byte` |
| `Short` | 16-bit signed integer | 16 | `settype G1 Short` |
| `Int` | 32-bit signed integer | 32 | `settype G1 Int` |
| `Long` | 64-bit signed integer (default for registers). | 64 | `settype G1 Long` (default) |
| `Float` | 32-bit single-precision floating-point number (IEEE 754). | 32 | `settype X1 Float` |
| `Double` | 64-bit double-precision floating-point number (IEEE 754). | 64 | `settype X1 Double` |
## Memory Representation
All values are stored in memory as 64-bit Longs regardless of the data type. This is to ensure consistency throughout
the memory. You can use smaller data types in registers, but memory always works with 64-bit Longs.
This document describes the data types used within the MVM. It's essential to understand these types when writing
assembly code for the MVM.
-------------------------------
```
filePath .sharing/archiveBuffer/docs/Standard-Library.md
```markdown
# MVM Standard Library Overview
The MVM standard library provides reusable functions to enhance MVM programs. These functions handle common tasks and
offer higher-level abstractions. All functions use the stack for arguments and return values. The library is organised
into modules, each focusing on a specific area of functionality.
## Library Modules
The standard library is structured into the following modules:
### String Functions
This module provides string manipulation functions. Functions operate on null-terminated strings, and memory management
is handled automatically. The available functions are:
- `strcmp`: Compares two strings lexicographically. Returns 1 if equal, 0 otherwise.
- `strcat`: Concatenates two strings. Returns the address of the new string.
- `strcpy`: Copies a string from a source to a destination. Returns the destination address.
- `strlen`: Returns the length of a string.
### Array Functions
This module provides array-related functions. The functions support array creation, access, and manipulation. Arrays
created with `createArray` can be cleared using `clean.array`. The available functions are:
- `create`: Creates a new array. Returns the address of the new array.
- `get`: Gets an element from an array. Returns the element's value.
- `size`: Returns the size of an array.
### Maths Functions
This module contains standard mathematical functions. For floating-point functions, operands must be of the same type.
The functions are:
- `min`: Returns the smaller of two values.
- `max`: Returns the larger of two values.
- `inc`: Increments a value by 1.
- `dec`: Decrements a value by 1.
- `neg`: Negates a value.
- `sq`: Squares a value.
### Clean Functions
This module handles clearing parts of memory automatically. The functions are
- `array`: Clears an array.
- `string`: Clears a string.
### IO Functions
This module handles simple I/O operations, including console input and output. The functions are:
- `println`: Prints a string to the console with a newline.
- `readln`: Reads a line of input from standard input and returns its address.
### System Functions
This module is responsible for system-related functions The functions are
- `exit`: Exits the program
### Conversion Functions
This module contains data type conversion functions. The available functions are:
- `asciiToInt`: Converts an ASCII character to its integer representation.
- `strtoint`: Converts a string to a, long.
- `findFirstString`: Finds the first occurrence of a character within a string.
## Calling Standard Library Functions
Standard library functions are called using the `CALL` instruction:
```assembly
call strings.strlen // Call the strlen function
```
Arguments are passed in F registers (F1, F2, etc.), and the return value (if any) is pushed onto the stack.
## Further Information
Refer to the [Standard Library Table](Standard-Library-Table.md) for detailed information on each function, including
argument types and return values.
-------------------------------
```
filePath .sharing/archiveBuffer/docs/Instruction-Set.md
```markdown
# MVM Instruction Set
This document details the MVM (Micro Virtual Machine) instruction set. Instructions are categorised for clarity. The MVM
uses a 64-bit architecture, and all instructions are 64 bits wide unless otherwise specified. Multi-word instructions
use two words. The MVM uses a stack-based architecture for function calls and return values.
## Data Transfer Instructions
These instructions move data between registers and memory.
### LIT
**`lit` `Destination Register` `Value` (Long Literal)**
Loads a 64-bit integer literal `Value` into the `Destination` register
```assembly
lit G1 10 // G1 = 10
```
### XLIT
**`xlit` `Destination Register` `Value` (Double/Float Literal)**
Loads a floating-point literal `Value` into the `Destination` register. The data type (Float or Double) is determined at
runtime based on the data type assigned to the register by the `SETTYPE` instruction.
```assembly
xlit X1 3.14159 // X1 = 3.14159 (as a Double)
```
To load as a single-precision Float:
```assembly
settype X1 Float // Set X1's data type to Float
xlit X1 3.14159 // X1 = 3.14159 (as a Float)
```
### MOV
**`mov` `Source Register` `Destination Register` (Register Value)**
Moves a value from the `Source` register to the `Destination` register.
```assembly
mov G1 G2 // G2 = G1
```
### SWP
**`swp` `Register1` `Register2` (Register Value)**
Swaps the values of `Register1` and `Register2`.
```assembly
swp G1 G2 // G1 <-> G2 (G1 and G2 exchange values)
```
### SETTYPE
**`settype` `Target Register` `DataType` (RegisterDataType)**
Sets the data type of the `Target` register. If the current value is too large or too small for the new data type, it
will be truncated.
```assembly
settype G1 Long // G1 is now a Long
```
The available data types are: `Byte`, `Short`, `Int`, `Long`, `Float`, `Double`.
### STORE
**`store` `Source Register` `MemoryAddress Register` (Register Value)**
Stores the value from the `Source` register into the memory location whose address is in the `MemoryAddress` register.
```assembly
store G1 G2 // Memory[G2] = G1
```
### LOAD
**`load` `MemoryAddress Register` `Destination Register` (Register Value)**
Loads the value from the memory location specified by the `MemoryAddress` register into the `Destination` register.
```assembly
load G2 G1 // G1 = Memory[G2]
```
### PUSH
**`push` `Source Register` (Register Value)**
Pushes the value from the `Source` register onto the stack. The stack grows downwards.
```assembly
push G1 // Push G1 onto the stack
```
### PUSHL
**`pushl` `Value` (Long Literal)**
Pushes the 64-bit integer literal `Value` onto the stack.
```assembly
pushl 100 // Push 100 onto the stack
```
### POP
**`pop` `Destination Register` (Register Value)**
Pops a value from the top of the stack and stores it in the `Destination` register. Handles stack underflow.
```assembly
pop G1 // G1 = top of stack; pop the stack
```
### PEEK
**`peek` `Destination Register` (Register Value)**
Copies the value at the top of the stack into the `Destination` register without removing it from the stack. Handles
stack underflow.
```assembly
peek G1 // G1 = top of stack; stack unchanged
```
## Arithmetic Instructions
These instructions perform arithmetic operations. Results are pushed onto the stack.
### ADD
**`add` `Addend1` `Addend2` `ResultDestination Register` (Register Value)**
Adds `Addend1` and `Addend2`; a result is pushed onto the stack.
```assembly
add G1 G2 R4 // Push G1 + G2 onto stack
```
### SUB
**`sub` `Minuend` `Subtrahend` `ResultDestination Register` (Register Value)**
Subtracts `Subtrahend` from `Minuend`; a result is pushed onto the stack.
```assembly
sub G1 G2 R4 // Push G1 - G2 onto stack
```
### MUL
**`mul` `Multiplier` `Multiplicand` `ResultDestination Register` (Register Value)**
Multiplies `Multiplier` and `Multiplicand`; a result is pushed onto the stack.
```assembly
mul G1 G2 R4 // Push G1 * G2 onto stack
```
### DIV
**`div` `Dividend` `Divisor` `ResultDestination Register` (Register Value)**
Divides `Dividend` by `Divisor` (integer division); a result is pushed onto the stack. Throws an exception if the
divisor is zero.
```assembly
div G1 G2 R4 // Push G1 / G2 onto stack
```
### MOD
**`mod` `Dividend` `Divisor` `ResultDestination Register` (Register Value)**
Calculates the modulo of `Dividend` and `Divisor`; a result is pushed onto the stack. Throws an exception if the divisor
is zero.
```assembly
mod G1 G2 R4 // Push G1 % G2 onto stack
```
### POW
**`pow` `Base` `Exponent` `ResultDestination Register` (Register Value)**
Raises `Base` to the power of `Exponent` (integer exponentiation); a result is pushed onto the stack. Handles potential
overflow.
```assembly
pow G1 G2 R4 // Push G1 ^ G2 onto stack
```
## Bitwise Instructions
These instructions perform bitwise operations. Results are pushed onto the stack.
### AND
**`and` `Operand1` `Operand2` `ResultDestination Register` (Register Value)**
Performs a bitwise AND operation; a result is pushed onto the stack.
```assembly
and G1 G2 R3 // Push G1 & G2 onto stack
```
### OR
**`or` `Operand1` `Operand2` `ResultDestination Register` (Register Value)**
Performs a bitwise OR operation; a result is pushed onto the stack.
```assembly
or G1 G2 R3 // Push G1 | G2 onto stack
```
### XOR
**`xor` `Operand1` `Operand2` `ResultDestination Register` (Register Value)**
Performs a bitwise XOR operation; a result is pushed onto the stack.
```assembly
xor G1 G2 R3 // Push G1 ^ G2 onto stack
```
### NOT
**`not` `Operand` `ResultDestination Register` (Register Value)**
Performs a bitwise NOT operation; a result is pushed onto the stack.
```assembly
not G1 R3 // Push ~G1 onto stack
```
### SHL
**`shl` `Value` `ShiftAmount` `ResultDestination Register` (Register Value)**
Shifts the bits in the `Value` register to the left by the amount specified in the `ShiftAmount` register; a result is
pushed onto the stack.
```assembly
shl G1 G2 R3 // Push G1 << G2 onto stack
```
### SHR
**`shr` `Value` `ShiftAmount` `ResultDestination Register` (Register Value)**
Shifts the bits in the `Value` register to the right by the amount specified in the `ShiftAmount` register; a result is
pushed onto the stack.
```assembly
shr G1 G2 R3 // Push G1 >> G2 onto stack
```
## Control Flow Instructions
These instructions control the flow of execution.
### JMP
**`jmp` `LineNumber` (LineNumber)**
Unconditionally jumps to the specified `LineNumber`.
```assembly
jmp 10 // Jump to line 10
```
### JZ
**`jz` `LineNumber` (LineNumber)**
Jumps to the specified `LineNumber` if the Zero Flag (`I1`) register is zero.
```assembly
jz 20 // Jump to line 20 if I1 == 0
```
### JNZ
**`jnz` `LineNumber` (LineNumber)**
Jumps to the specified `LineNumber` if the Zero Flag (`I1`) register is not zero.
```assembly
jnz 20 // Jump to line 20 if I1 != 0
```
### CALL
**`call` `FunctionName` (FunctionName)**
Calls the function specified by `FunctionName`. Arguments are passed in F registers; the result (if any) is pushed onto
the stack.
```assembly
call maths.pow // Call the pow function
```
### RET
**`ret`**
Returns from a function. The function's return value (if any) should have already been pushed onto the stack.
## Comparison Instructions
These instructions perform comparisons. Results (0 or 1) are pushed onto the stack.
### EQ
**`eq` `Operand1` `Operand2` (Register Value)**
Compares two values for equality. Pushes 1 if equal, 0 if not.
```assembly
eq G1 G2 // Push 1 if G1 == G2, 0 otherwise
```
### GT
**`gt` `Operand1` `Operand2` (Register Value)**
Compares two values; pushes 0 if `Operand1` > `Operand2`, otherwise 1. Sets the Greater Than Flag (`I3`).
```assembly
gt G1 G2 // Push 0 if G1 > G2, 1 otherwise. Set I3 (Greater Than Flag) accordingly.
```
### LT
**`lt` `Operand1` `Operand2` (Register Value)**
Compares two values; pushes 0 if `Operand1` < `Operand2`, otherwise 1. Sets the Greater Than Flag (`I3`).
```assembly
lt G1 G2 // Push 0 if G1 < G2, 1 otherwise. Set I3 (Greater Than Flag) accordingly.
```
## String Instructions
These instructions operate on null-terminated strings in memory. Results are pushed onto the stack.
### STR
**`str` `DestinationAddressRegister` `StringLiteral` (String Literal)**
Stores the `StringLiteral` in memory. The address of the new string is stored in the `DestinationAddressRegister`.
Memory is allocated automatically.
```assembly
str G1 "Hello Reader?!?!" // Store "Hello" at a new memory location; G1 holds the address
```
## I/O Instructions
These instructions handle input and output.
### PRINTS
**`prints`**
Prints the top value on the stack to the console.
```assembly
prints // Print value at top of stack
```
### PRINTR
**`printr` `Register` (Register Value)**
Prints the value of the specified register to the console.
```assembly
printr G1 // Print value of G1
```
## System Calls
These instructions invoke operating system (kernel) functions.
### SYSCALL
**`syscall` `SystemCallID` `Argument1` `Argument2` `Argument3` (SystemCallID, Register Value)**
Executes a system call. Arguments are passed in `S` registers; the system call ID is in `S1`. The result (if any) is
pushed onto the stack. See the [System Call Table](System-Calls-Table.md) for details.
```assembly
lit s1 14 // Get current time (system call ID 14)
syscall // Make the system call; result is on stack
```
## Miscellaneous Instructions
### HELP
**`help` `Topic` (Topic)**
Displays help information for the specified `Topic` (instruction or standard library function).
```assembly
help `"add"` // Display help for the ADD instruction
```
### SLEEP
**`sleep` `Milliseconds` (Milliseconds)**
Pauses execution for the specified `Milliseconds`.
```assembly
sleep G1 // Pause for number of milliseconds in G1
```
## XFloats Instructions
These instructions perform floating-point arithmetic. Results are pushed onto the stack. Operands must be of the same
type (Float or Double).
### XADD
**`xadd` `Addend1` `Addend2` `ResultDestination Register` (Register Value)**
Adds two floating-point values; a result is pushed onto the stack.
```assembly
xadd X1 X2 R5 // Push X1 + X2 onto stack
```
### XSUB
**`xsub` `Minuend` `Subtrahend` `ResultDestination Register` (Register Value)**
Subtracts two floating-point values; a result is pushed onto the stack.
```assembly
xsub X1 X2 R5 // Push X1 - X2 onto stack
```
### XMUL
**`xmul` `Multiplier` `Multiplicand` `ResultDestination Register` (Register Value)**
Multiplies two floating-point values; a result is pushed onto the stack.
```assembly
xmul X1 X2 R5 // Push X1 * X2 onto stack
```
### XDIV
**`xdiv` `Dividend` `Divisor` `ResultDestination Register` (Register Value)**
Divides two floating-point values; a result is pushed onto the stack. Throws an exception if the divisor is zero.
```assembly
xdiv X1 X2 R5 // Push X1 / X2 onto stack
```
### XMOD
**`xmod` `Dividend` `Divisor` `ResultDestination Register` (Register Value)**
Calculates the modulo of two floating-point values; a result is pushed onto the stack. Throws an exception if the
divisor is zero.
```assembly
xmod X1 X2 R5 // Push X1 % X2 onto stack
```
### XPOW
**`xpow` `Base` `Exponent` `ResultDestination Register` (Register Value)**
Raises a floating-point value to a power; a result is pushed onto the stack.
```assembly
xpow X1 X2 R5 // Push X1 ^ X2 onto stack
```
### ITOF
**`itof` `Source Register` `Destination Register` (Register Value)**
Converts a `Long` from the `Source` register to a `Double` and stores it in the `Destination` register.
```assembly
itof G1 X1 // X1 = G1 (as a Double)
```
### FTOI
**`ftoi` `Source Register` `Destination Register` (Register Value)**
Converts a `Double` from the `Source` register to a `Long` and stores it in the `Destination` register.
```assembly
ftoi X1 G1 // G1 = X1 (truncated to a Long)
```
This detailed explanation, for example, provides a clear understanding of each instruction and its usage within the MVM.
Remember to consult the [System Call Table](System-Calls-Table.md) for details on system calls. // Comments are now //
instead of ;
-------------------------------
```
filePath .sharing/archiveBuffer/docs/Standard-Library-Table.md
```markdown
# MVM Standard Library Table
This table lists the functions currently implemented in the MVM standard library. All functions use the stack for
arguments and return values.
| Module | Function Name | Description | Argument 1 (F1) | Argument 2 (F2) | Argument 3 (F3) | Return Value(s) (Stack) | Notes |
|--------------|-------------------|---------------------------------------------------------------------|----------------------------------|--------------------------------------|-----------------|----------------------------------------------|------------------------------------------------------------------------------|
| `strings` | `strlen` | Returns the length of a string. | String Address (Memory Address) | - | - | Length (Long) | Excludes the null terminator. |
| | `strcat` | Concatenates two strings. | String1 Address (Memory Address) | String2 Address (Memory Address) | - | Concatenated String Address (Memory Address) | Allocates memory for the concatenated string. |
| | `strcpy` | Copies a string from one location to another. | Source Address (Memory Address) | Destination Address (Memory Address) | - | Destination Address (Memory Address) | Allocates memory for the copied string. The source string remains unchanged. |
| | `strcmp` | Compares two strings lexicographically. | String1 Address (Memory Address) | String2 Address (Memory Address) | - | Result (0 or 1) | Returns 1 if strings are equal; 0 otherwise. |
| | `asciiToInt` | Converts an ASCII character to its integer representation. | Character Code (Long) | - | - | Integer Value (Long) | Returns -1 if the input is not a valid ASCII character. |
| | `findFirstString` | Finds the index of the first occurrence of a character in a string. | String Address (Memory Address) | Character Code (Long) | - | Index (Long) | Returns -1 if the character is not found. |
| `arrays` | `create` | Creates a new array. | Size (Long) | Data Type (RegisterDataType code) | - | Array Base Address (Long) | Data Type code: 0=Byte, 1=Short, 2=Int, 3=Long, 4=Float, 5=Double. |
| | `get` | Gets an element from an array. | Array Address (Long) | Index (Long) | - | Element Value (Long) | Performs bounds checking. |
| | `size` | Returns the size of an array | Array Address (Long) | Index (Long) | Value (Long) | - | Performs bounds checking. |
| | `append` | Adds a new element to the end of an array | Array Address (Long) | - | - | Length (Long) | - |
| `math` | `sqrt` | Calculates the square root of a number. | Number (Long) | - | - | Result (Long) | Returns 0 if the input is negative. |
| | `pow` | Raises a number to a power. | Base (Long) | Exponent (Long) | - | Result (Long) | Returns 0 on error. |
| | `min` | Returns the minimum of two values. | Value 1 (Long) | Value 2 (Long) | - | Minimum Value (Long) | - |
| | `max` | Returns the maximum of two values. | Value 1 (Long) | Value 2 (Long) | - | Maximum Value (Long) | - |
| | `inc` | Increments a value by 1. | Value (Long) | - | - | Incremented Value (Long) | - |
| | `dec` | Decrements a value by 1. | Value (Long) | - | - | Decremented Value (Long) | - |
| | `neg` | Negates a value. | Value (Long) | - | - | Negated Value (Long) | - |
| | `sq` | Squares a value. | Value (Long) | - | - | Squared Value (Long) | - |
| `io` | `println` | Prints a string to the console with a newline. | String Address (Memory Address) | - | - | - | The string must be null-terminated. |
| | `readln` | Reads a line from standard input. | - | - | - | String Address (Memory Address) | Allocates memory for the string. |
| `conversion` | `asciiToInt` | Converts an ASCII character to an integer. | Character Code (Long) | - | - | Integer Value (Long) | Returns -1 if the input is not a valid ASCII character. |
| | `strtoint` | Converts a string to a Long. | String Address (Memory Address) | - | - | Integer Value (Long) | Returns 0 on error. |
| | `findFirstString` | Finds the index of the first occurrence of a character in a string. | String Address (Memory Address) | Character Code (Long) | - | Index (Long) | Returns -1 if the character is not found. |
-------------------------------
```
filePath .sharing/archiveBuffer/docs/Process-Management.md
```markdown
# MVM Process Management
The MVM (Micro Virtual Machine) kernel manages the creation, execution, and termination of processes.
Processes run concurrently within the VM's emulated environment, using cooperative multitasking.
The kernel uses a round-robin scheduler.
## Process States
A process in the MVM can be in one of the following states:
- **RUNNING:** The process is currently executing instructions.
- **CANCELLED:** The process has terminated by another process.
- **PAUSED:** The process is paused by another process.
## Process Control Block (KProcess)
The kernel represents each process using a `KProcess` object.
This object acts as the process control block (PCB), storing all essential information about the process:
- **`id`:** A unique integer identifier for the process. (Assigned when a process is created).
- **`vm`:** An instance of the `Vm` class, representing the VM's state for this process.
Each process gets its own VM
object.
- **`file`:** A `File` object, the path to the program that the process runs.
- **`instructionMemory`:** A list of `InstructData` objects that represent the instructions in the program.
- **`ipcPermissions`:** A list of mailbox IDs for inter-process communication (IPC) that this process has access to.
- **`parent`:** The ID of the process's parent process (or `null` for the initial process).
- **`thread`:** The Kotlin `Thread` that executes instructions for the process.
This data is stored and managed by the kernel.
## Process Creation (`fork` and `spawn`)
The kernel provides two system calls for creating processes:
- **`fork()`:** Creates a new process, a copy of the current process.
The child process has its own memory space,
registers, and stack, but it starts with the same code as the parent.
returns the child process's PID to
the parent process and 0 to the child process.
The `thread` is determined by the VM itself.
The process is initialised at runtime in `KProcess.init`
- **`spawn(programPath.kar)`:** Creates a new process under the VM using the assembly code, using the file specified by
`programPath.kar`.
It will not inherit the
state of the parent process.
The process is added to the scheduler's ready queue.
## Process Termination (`HALT`)
HALT is added by the OS automatically and is inaccessible to the programmer.
A process terminates by calling the `HALT` key word.
The kernel will remove the process from the scheduler's ready queue.
This is different from the exit system call which exits the entire VM, working on a fix.
## Inter-Process Communication (IPC)
Inter-process communication is managed through mailboxes.
Each process has a list of mailbox IDs (`ipcPermissions`) which it has access to.
The OS manages mailboxes.
Processes communicate by sending (`send`) and receiving (`receive`) messages.
Processes can establish connections with other processes using the `link` system call.
This document provides an overview of process management in the MVM. For detailed information about the `KProcess` class
and system calls,
refer to other sections in this wiki.
Content_copy
Use code with caution.
Markdown
-------------------------------
```
filePath .sharing/archiveBuffer/docs/Scheduler.md
```markdown
# MVM Kernel Scheduler
The MVM (Micro Virtual Machine) kernel uses a scheduler to manage the concurrent execution of multiple processes.
The scheduler employs a round-robin algorithm,
allocating a single instruction cycle to each process before switching to the next.
This approach prioritises simplicity and reliability over complex scheduling strategies.
## Round-Robin Scheduling
The round-robin algorithm is a simple and efficient scheduling technique, particularly well-suited to the MVM's design.
Each process in the ready queue is given a single instruction cycle to execute.
After the instruction completes, the scheduler selects the next process from the ready queue,
effectively creating a circular order of execution.
## Scheduler Data Structures
The scheduler uses the following data structures:
- **Ready Queue:** A queue (`LinkedList`) containing the PIDs of processes ready to run. Processes are added to the
ready queue when they are created or become ready after being blocked.
- **Running Process:** A variable to store the PID of the currently running process.
## Scheduler Algorithm
The scheduler's algorithm is straightforward.
Its function (`eventLoop`) iterates through a list of processes (`keepPcs`),
executing a single instruction per process in a round-robin fashion:
1. **Get Next Process:** Retrieve the next process from the ready queue (using `getNextProcess()`).
2. **Load Process State:** Load the process's state (registers, program counter, etc.) from its PCB (`KProcess`).
3. **Execute Instruction:** Execute a single instruction.
4. **Save Process State:** Save the process's state back into the PCB using the kernels `snapShotManager`.
5. **Add to Ready Queue (if not finished):** Add the process to the back of the ready queue, unless the process has
ended.
This is repeated until all processes in `keepPcs` are finished.
## Handling Process Termination