From 8838beda5e21585b1b39a25446e33e9dcb9fbe4f Mon Sep 17 00:00:00 2001 From: Santiago Lo Coco Date: Sun, 31 Oct 2021 23:18:54 -0300 Subject: [PATCH] Reformat code Co-authored-by: Ezequiel Bellver Co-authored-by: Juan Barmasch --- .gitignore | 1 + Kernel/Makefile | 2 +- Kernel/{ => drivers}/include/keyboard.h | 4 +- Kernel/{ => drivers}/include/naiveConsole.h | 0 Kernel/{ => drivers}/include/time.h | 5 +- Kernel/{ => drivers}/include/video.h | 2 - Kernel/drivers/keyboard.c | 197 +++---- Kernel/drivers/naiveConsole.c | 113 ++-- Kernel/drivers/time.c | 86 ++- Kernel/drivers/video.c | 141 +++-- Kernel/include/defs.h | 7 - Kernel/include/idtLoader.h | 6 - Kernel/include/memManager.h | 24 - Kernel/include/pcb.h | 20 - Kernel/include/queue.h | 8 - Kernel/interruptions/exceptions.c | 18 +- Kernel/interruptions/idtLoader.c | 36 +- Kernel/interruptions/include/exceptions.h | 15 + Kernel/interruptions/include/idtLoader.h | 10 + .../{ => interruptions}/include/interrupts.h | 5 +- Kernel/interruptions/include/systemCalls.h | 19 + .../include/systemCallsLib.h} | 6 +- Kernel/interruptions/irqDispatcher.c | 24 +- Kernel/interruptions/systemCalls.c | 32 +- Kernel/interruptions/systemCallsDispatcher.c | 16 +- Kernel/kernel.c | 266 ++++----- Kernel/lib.c | 108 ++-- Kernel/moduleLoader.c | 28 +- Kernel/{ => tests}/include/test_util.h | 0 Kernel/utils/include/memManager.h | 14 + Kernel/utils/include/pcb.h | 9 + Kernel/{ => utils}/include/pipe.h | 2 +- Kernel/{ => utils}/include/pipeLib.h | 0 Kernel/{ => utils}/include/scheduler.h | 6 +- Kernel/{ => utils}/include/schedulerLib.h | 0 Kernel/{ => utils}/include/sem.h | 3 +- Kernel/{ => utils}/include/semLib.h | 1 - Kernel/utils/memManagerBuddy.c | 304 +++++----- Kernel/utils/memManagerFRT4.c | 534 +++++++++--------- Kernel/utils/pcb.c | 32 -- Kernel/utils/pipe.c | 74 +-- Kernel/utils/queue.c | 51 -- Kernel/utils/scheduler.c | 138 +++-- Kernel/utils/sem.c | 71 ++- Userland/SampleCodeModule/Makefile | 95 ++-- Userland/SampleCodeModule/_loader.c | 21 +- Userland/SampleCodeModule/bottler/bottler.c | 99 ++-- Userland/SampleCodeModule/include/system.h | 4 - Userland/SampleCodeModule/libc.c | 251 ++++---- Userland/SampleCodeModule/sampleCodeModule.c | 11 +- Userland/SampleCodeModule/shell/Makefile | 20 - Userland/SampleCodeModule/shell/shell.c | 78 ++- 52 files changed, 1348 insertions(+), 1669 deletions(-) rename Kernel/{ => drivers}/include/keyboard.h (68%) rename Kernel/{ => drivers}/include/naiveConsole.h (100%) rename Kernel/{ => drivers}/include/time.h (80%) rename Kernel/{ => drivers}/include/video.h (75%) delete mode 100644 Kernel/include/idtLoader.h delete mode 100644 Kernel/include/memManager.h delete mode 100644 Kernel/include/pcb.h delete mode 100644 Kernel/include/queue.h create mode 100644 Kernel/interruptions/include/exceptions.h create mode 100644 Kernel/interruptions/include/idtLoader.h rename Kernel/{ => interruptions}/include/interrupts.h (90%) create mode 100644 Kernel/interruptions/include/systemCalls.h rename Kernel/{include/systemCalls.h => interruptions/include/systemCallsLib.h} (50%) rename Kernel/{ => tests}/include/test_util.h (100%) create mode 100644 Kernel/utils/include/memManager.h create mode 100644 Kernel/utils/include/pcb.h rename Kernel/{ => utils}/include/pipe.h (90%) rename Kernel/{ => utils}/include/pipeLib.h (100%) rename Kernel/{ => utils}/include/scheduler.h (81%) rename Kernel/{ => utils}/include/schedulerLib.h (100%) rename Kernel/{ => utils}/include/sem.h (83%) rename Kernel/{ => utils}/include/semLib.h (92%) delete mode 100644 Kernel/utils/queue.c delete mode 100644 Userland/SampleCodeModule/shell/Makefile diff --git a/.gitignore b/.gitignore index 0559938..f64f668 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ index.html .bashrc .vscode/* +.idea/ #Binary Files *.bin diff --git a/Kernel/Makefile b/Kernel/Makefile index 4485fc2..e672529 100644 --- a/Kernel/Makefile +++ b/Kernel/Makefile @@ -32,7 +32,7 @@ $(KERNEL_ELF): $(STATICLIBS) $(ALL_OBJECTS) $(LD) $(LDFLAGS) -T kernel.ld --oformat=elf64-x86-64 -o $@ $^ %.o: %.c - $(GCC) $(GCCFLAGS) -I./include -I./drivers -I./interruptions -I./utils -I./tests $(MFLAG) -c $< -o $@ + $(GCC) $(GCCFLAGS) -I./include -I./drivers/include -I./interruptions/include -I./utils/include -I./tests/include $(MFLAG) -c $< -o $@ %.o : %.asm $(ASM) $(ASMFLAGS) $< -o $@ diff --git a/Kernel/include/keyboard.h b/Kernel/drivers/include/keyboard.h similarity index 68% rename from Kernel/include/keyboard.h rename to Kernel/drivers/include/keyboard.h index 8fb824f..184b06c 100644 --- a/Kernel/include/keyboard.h +++ b/Kernel/drivers/include/keyboard.h @@ -2,7 +2,9 @@ #define KEYBOARD_H #include -#include "schedulerLib.h" +#include "../../utils/include/schedulerLib.h" + +#define SIZE 1 void keyboard_handler(); unsigned char getKeyFromBuffer(); diff --git a/Kernel/include/naiveConsole.h b/Kernel/drivers/include/naiveConsole.h similarity index 100% rename from Kernel/include/naiveConsole.h rename to Kernel/drivers/include/naiveConsole.h diff --git a/Kernel/include/time.h b/Kernel/drivers/include/time.h similarity index 80% rename from Kernel/include/time.h rename to Kernel/drivers/include/time.h index 4299a09..49ac3c5 100755 --- a/Kernel/include/time.h +++ b/Kernel/drivers/include/time.h @@ -1,5 +1,5 @@ -#ifndef _TIME_H_ -#define _TIME_H_ +#ifndef TIME_H +#define TIME_H void timer_handler(); int ticks_elapsed(); @@ -14,7 +14,6 @@ int seconds_elapsed(); int getTimeGen(char option); int getTime(char option); -// void wait(long seconds); long getTimeOfDay(); #endif diff --git a/Kernel/include/video.h b/Kernel/drivers/include/video.h similarity index 75% rename from Kernel/include/video.h rename to Kernel/drivers/include/video.h index 51aef60..cb60e45 100644 --- a/Kernel/include/video.h +++ b/Kernel/drivers/include/video.h @@ -3,13 +3,11 @@ #include -void moveToWindowVideo(char window); int printStringLen(int color, const char * string, int maxLen); void new_line(); void backspace(); void clear(); void increment(); -void changeWindow(); void scroll(); #endif \ No newline at end of file diff --git a/Kernel/drivers/keyboard.c b/Kernel/drivers/keyboard.c index 2d9ed52..ba3bfa8 100644 --- a/Kernel/drivers/keyboard.c +++ b/Kernel/drivers/keyboard.c @@ -5,10 +5,9 @@ static unsigned char kbdus_sh[250]; // static unsigned char kbdsp_sh[250]; // static unsigned char kbdsp[250]; -#define SIZE 1 unsigned char buffer[SIZE] = {0}; -unsigned char * current = buffer; -unsigned char * last = buffer; +unsigned char *current = buffer; +unsigned char *last = buffer; void saveChar(unsigned char c) { *last++ = c; @@ -24,35 +23,26 @@ void testKeyboardInterrupt(unsigned char c) { if (c == 0x2A || c == 0x36) { flag = 0; return; - } - else if (c == 0xAA || c == 0xB6) { + } else if (c == 0xAA || c == 0xB6) { flag = 1; return; - } - - else if (c == 0x3A) { + } else if (c == 0x3A) { flag = ~(flag | 0xFE); + } else if (c == 0x38) { + flagChangeAlt = 0; + } else if (c == 0x3B) { + flagChangeF1 = 0; } - else if (c == 0x38) { - flagChangeAlt = 0; - } - else if (c == 0x3B) { - flagChangeF1 = 0; - } - if (flagChangeAlt == 0 && flagChangeF1 == 0) { flagChangeAlt = 1; flagChangeF1 = 1; saveChar('\v'); return; - } - - else if (c == 0xB8) { + } else if (c == 0xB8) { flagChangeAlt = 1; return; - } - else if (c == 0xBB) { + } else if (c == 0xBB) { flagChangeF1 = 1; return; } @@ -60,23 +50,22 @@ void testKeyboardInterrupt(unsigned char c) { if (flag == 0) { c = kbdus_sh[c]; if (c != 0) - saveChar(c); - } - else { + saveChar(c); + } else { c = kbdus[c]; if (c != 0) - saveChar(c); + saveChar(c); } } unsigned char getKeyFromBuffer() { - if (current - buffer == SIZE) { - current = buffer; - } + if (current - buffer == SIZE) { + current = buffer; + } - char aux = *current; - *current++ = 0; - return aux; + char aux = *current; + *current++ = 0; + return aux; } void keyboard_handler() { @@ -125,42 +114,42 @@ void keyboard_handler() { // }; static unsigned char kbdus[250] = { - 0, 27, '1', '2', '3', '4', '5', '6', '7', '8', /* 9 */ - '9', '0', '-', '=', '\b', /* Backspace */ - '\t', /* Tab */ - 'q', 'w', 'e', 'r', /* 19 */ - 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n', /* Enter key */ - 0, /* 29 - Control */ - 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* 39 */ - '\'', '`', 0, /* Left shift */ - '\\', 'z', 'x', 'c', 'v', 'b', 'n', /* 49 */ - 'm', ',', '.', '/', 0, /* Right shift */ - '*', - 0, /* Alt */ - ' ', /* Space bar */ - 0, /* Caps lock */ - 0, /* 59 - F1 key ... > */ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, /* < ... F10 */ - 0, /* 69 - Num lock*/ - 0, /* Scroll Lock */ - 0, /* Home key */ - 0, /* Up Arrow */ - 0, /* Page Up */ - '-', - 0, /* Left Arrow */ - 0, - 0, /* Right Arrow */ - '+', - 0, /* 79 - End key*/ - 0, /* Down Arrow */ - 0, /* Page Down */ - 0, /* Insert Key */ - 0, /* Delete Key */ - 0, 0, 0, - 0, /* F11 Key */ - 0, /* F12 Key */ - 0, /* All other keys are undefined */ + 0, 27, '1', '2', '3', '4', '5', '6', '7', '8', /* 9 */ + '9', '0', '-', '=', '\b', /* Backspace */ + '\t', /* Tab */ + 'q', 'w', 'e', 'r', /* 19 */ + 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n', /* Enter key */ + 0, /* 29 - Control */ + 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* 39 */ + '\'', '`', 0, /* Left shift */ + '\\', 'z', 'x', 'c', 'v', 'b', 'n', /* 49 */ + 'm', ',', '.', '/', 0, /* Right shift */ + '*', + 0, /* Alt */ + ' ', /* Space bar */ + 0, /* Caps lock */ + 0, /* 59 - F1 key ... > */ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, /* < ... F10 */ + 0, /* 69 - Num lock*/ + 0, /* Scroll Lock */ + 0, /* Home key */ + 0, /* Up Arrow */ + 0, /* Page Up */ + '-', + 0, /* Left Arrow */ + 0, + 0, /* Right Arrow */ + '+', + 0, /* 79 - End key*/ + 0, /* Down Arrow */ + 0, /* Page Down */ + 0, /* Insert Key */ + 0, /* Delete Key */ + 0, 0, 0, + 0, /* F11 Key */ + 0, /* F12 Key */ + 0, /* All other keys are undefined */ }; // static unsigned char kbdsp_sh[250] = @@ -204,41 +193,41 @@ static unsigned char kbdus[250] = { // }; static unsigned char kbdus_sh[250] = -{ - 0, 27, '!', '\"', '#', 0 /* shift+4 */, '%', '&', '/', '(', /* 9 */ - ')', '=', '?', '`', '\b', /* Backspace */ - '\t', /* Tab */ - 'Q', 'W', 'E', 'R', /* 19 */ - 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '\n', /* Enter key */ - 0, /* 29 - Control */ - 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', /* 39 */ - '\'', '>', 0, /* Left shift */ - '|', 'Z', 'X', 'C', 'V', 'B', 'N', /* 49 */ - 'M', ';', ':', '_', 0, /* Right shift */ - '*', - 0, /* Alt */ - ' ', /* Space bar */ - 0, /* Caps lock */ - 0, /* 59 - F1 key ... > */ - 0, 0, 0, 0, 0, 0, 0, 0, - 0, /* < ... F10 */ - 0, /* 69 - Num lock*/ - 0, /* Scroll Lock */ - 0, /* Home key */ - 0, /* Up Arrow */ - 0, /* Page Up */ - '-', - 0, /* Left Arrow */ - 0, - 0, /* Right Arrow */ - '+', - 0, /* 79 - End key*/ - 0, /* Down Arrow */ - 0, /* Page Down */ - 0, /* Insert Key */ - 0, /* Delete Key */ - 0, 0, '>', - 0, /* F11 Key */ - 0, /* F12 Key */ - 0, /* All other keys are undefined */ -}; \ No newline at end of file + { + 0, 27, '!', '\"', '#', 0 /* shift+4 */, '%', '&', '/', '(', /* 9 */ + ')', '=', '?', '`', '\b', /* Backspace */ + '\t', /* Tab */ + 'Q', 'W', 'E', 'R', /* 19 */ + 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '\n', /* Enter key */ + 0, /* 29 - Control */ + 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', /* 39 */ + '\'', '>', 0, /* Left shift */ + '|', 'Z', 'X', 'C', 'V', 'B', 'N', /* 49 */ + 'M', ';', ':', '_', 0, /* Right shift */ + '*', + 0, /* Alt */ + ' ', /* Space bar */ + 0, /* Caps lock */ + 0, /* 59 - F1 key ... > */ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, /* < ... F10 */ + 0, /* 69 - Num lock*/ + 0, /* Scroll Lock */ + 0, /* Home key */ + 0, /* Up Arrow */ + 0, /* Page Up */ + '-', + 0, /* Left Arrow */ + 0, + 0, /* Right Arrow */ + '+', + 0, /* 79 - End key*/ + 0, /* Down Arrow */ + 0, /* Page Down */ + 0, /* Insert Key */ + 0, /* Delete Key */ + 0, 0, '>', + 0, /* F11 Key */ + 0, /* F12 Key */ + 0, /* All other keys are undefined */ + }; \ No newline at end of file diff --git a/Kernel/drivers/naiveConsole.c b/Kernel/drivers/naiveConsole.c index d1e05e3..94b3280 100644 --- a/Kernel/drivers/naiveConsole.c +++ b/Kernel/drivers/naiveConsole.c @@ -1,95 +1,74 @@ #include -static uint32_t uintToBase(uint64_t value, char * buffer, uint32_t base); +static uint32_t uintToBase(uint64_t value, char *buffer, uint32_t base); -static char buffer[64] = { '0' }; -static uint8_t * const video = (uint8_t*)0xB8000; -static uint8_t * currentVideo = (uint8_t*)0xB8000; +static char buffer[64] = {'0'}; +static uint8_t *const video = (uint8_t *) 0xB8000; +static uint8_t *currentVideo = (uint8_t *) 0xB8000; static const uint32_t width = 80; -static const uint32_t height = 25 ; +static const uint32_t height = 25; -void ncPrint(const char * string) -{ - int i; - - for (i = 0; string[i] != 0; i++) - ncPrintChar(string[i]); +void ncPrint(const char *string) { + for (int i = 0; string[i] != 0; i++) + ncPrintChar(string[i]); } -void ncPrintChar(char character) -{ - *currentVideo = character; - currentVideo += 2; +void ncPrintChar(char character) { + *currentVideo = character; + currentVideo += 2; } -void ncNewline() -{ - do - { - ncPrintChar(' '); - } - while((uint64_t)(currentVideo - video) % (width * 2) != 0); +void ncNewline() { + do { + ncPrintChar(' '); + } while ((uint64_t)(currentVideo - video) % (width * 2) != 0); } -void ncPrintDec(uint64_t value) -{ - ncPrintBase(value, 10); +void ncPrintDec(uint64_t value) { + ncPrintBase(value, 10); } -void ncPrintHex(uint64_t value) -{ - ncPrintBase(value, 16); +void ncPrintHex(uint64_t value) { + ncPrintBase(value, 16); } -void ncPrintBin(uint64_t value) -{ - ncPrintBase(value, 2); +void ncPrintBin(uint64_t value) { + ncPrintBase(value, 2); } -void ncPrintBase(uint64_t value, uint32_t base) -{ +void ncPrintBase(uint64_t value, uint32_t base) { uintToBase(value, buffer, base); ncPrint(buffer); } -void ncClear() -{ - int i; - - for (i = 0; i < height * width; i++) - video[i * 2] = ' '; - currentVideo = video; +void ncClear() { + for (int i = 0; i < height * width; i++) + video[i * 2] = ' '; + currentVideo = video; } -static uint32_t uintToBase(uint64_t value, char * buffer, uint32_t base) -{ - char *p = buffer; - char *p1, *p2; - uint32_t digits = 0; +static uint32_t uintToBase(uint64_t value, char *buffer, uint32_t base) { + char *p = buffer; + char *p1, *p2; + uint32_t digits = 0; - //Calculate characters for each digit - do - { - uint32_t remainder = value % base; - *p++ = (remainder < 10) ? remainder + '0' : remainder + 'A' - 10; - digits++; - } - while (value /= base); + do { + uint32_t remainder = value % base; + *p++ = (remainder < 10) ? remainder + '0' : remainder + 'A' - 10; + digits++; + } while (value /= base); - // Terminate string in buffer. - *p = 0; + *p = 0; - //Reverse string in buffer. - p1 = buffer; - p2 = p - 1; - while (p1 < p2) - { - char tmp = *p1; - *p1 = *p2; - *p2 = tmp; - p1++; - p2--; - } + p1 = buffer; + p2 = p - 1; + while (p1 < p2) { + char tmp = *p1; + *p1 = *p2; + *p2 = tmp; + p1++; + p2--; + } - return digits; + return digits; } diff --git a/Kernel/drivers/time.c b/Kernel/drivers/time.c index 71a0d48..d21d3c7 100755 --- a/Kernel/drivers/time.c +++ b/Kernel/drivers/time.c @@ -1,77 +1,55 @@ -#include +#include "time.h" static unsigned long ticks = 0; void timer_handler() { - ticks++; + ticks++; } int ticks_elapsed() { - return ticks; + return ticks; } int seconds_elapsed() { - // return ticks / 18; - return ticks / 18; + return ticks / 18; } int getTime(char option) { - switch(option) { - case SECONDS: - return getTimeGen(SECONDS); - case MINUTES: - return getTimeGen(MINUTES); - case HOURS: - return getTimeGen(HOURS); - case DAY: - return getTimeGen(DAY); - case MONTH: - return getTimeGen(MONTH); - case YEAR: - return getTimeGen(YEAR); - default: return -1; - } + switch (option) { + case SECONDS: + return getTimeGen(SECONDS); + case MINUTES: + return getTimeGen(MINUTES); + case HOURS: + return getTimeGen(HOURS); + case DAY: + return getTimeGen(DAY); + case MONTH: + return getTimeGen(MONTH); + case YEAR: + return getTimeGen(YEAR); + default: + return -1; + } } -// TODO -/* void wait(long seconds) { - // int initialSeconds = getTimeGen(SECONDS); - // int initialMinutes = getTimeGen(MINUTES); - // int runSeconds = 0; - // if (initialSeconds + seconds >= 60) { - - // } - // int newSeconds = 0; - // while ((newSeconds = getTimeGen(SECONDS) - initialSeconds) < seconds) - // haltcpu(); - // while (initialSeconds - seconds != initialSeconds) { - - // } - // while (seconds_elapsed() < seconds); -} */ - static long getTimeFrom2000() { - long years = 00 * 31557600; - long months = 1 * 2629800; - long days = 1 * 86400; + long years = 00 * 31557600; + long months = 1 * 2629800; + long days = 1 * 86400; - // long aux = years + months + days; - - return years + months + days; + return years + months + days; } long getTimeOfDay() { - // long years = getTimeGen(YEAR) - 1970; + long years = getTimeGen(YEAR) * 31557600; + long months = getTimeGen(MONTH) * 2629800; + long days = getTimeGen(DAY) * 86400; + long hours = getTimeGen(HOURS) * 3600; + long minutes = getTimeGen(MINUTES) * 60; + long seconds = getTimeGen(SECONDS); - // obtengo los segundos actuales (sumando todas las variables) y los resto por los de 1970? - long years = getTimeGen(YEAR) * 31557600; - long months = getTimeGen(MONTH) * 2629800; - long days = getTimeGen(DAY) * 86400; - long hours = getTimeGen(HOURS) * 3600; - long minutes = getTimeGen(MINUTES) * 60; - long seconds = getTimeGen(SECONDS); + long total = years + months + days + hours + minutes + seconds; - long total = years + months + days + hours + minutes + seconds; - - return total - getTimeFrom2000(); + return total - getTimeFrom2000(); } \ No newline at end of file diff --git a/Kernel/drivers/video.c b/Kernel/drivers/video.c index cc5811d..4959da4 100644 --- a/Kernel/drivers/video.c +++ b/Kernel/drivers/video.c @@ -1,8 +1,6 @@ -#include #include "video.h" -static uint8_t * const video = (uint8_t *) 0xB8000; -// static uint8_t * currentVideo = (uint8_t *) 0xB8000; +static uint8_t *const video = (uint8_t *) 0xB8000; static const int width = 80; static const int height = 25; static int currentX = 0; @@ -12,95 +10,92 @@ int limitX[2] = {0, 80}; int limitY[2] = {0, 25}; void increment() { - currentX++; - if (currentX == limitX[1]) { - currentY++; - currentX = limitX[0]; - if (currentY >= limitY[1]) { - scroll(); - currentY = limitY[1] - 1; - } - } + currentX++; + if (currentX == limitX[1]) { + currentY++; + currentX = limitX[0]; + if (currentY >= limitY[1]) { + scroll(); + currentY = limitY[1] - 1; + } + } } -char checkIfEscapeSequence(const char * bufferAux) { - if (*bufferAux == '\e') { - bufferAux++; - if (*bufferAux == '\f') { - bufferAux++; - clear(); - } - return 1; - } - return 0; +char checkIfEscapeSequence(const char *bufferAux) { + if (*bufferAux == '\e') { + bufferAux++; + if (*bufferAux == '\f') { + clear(); + } + return 1; + } + return 0; } void scroll() { - for (int i = limitY[0]; i < limitY[1] - 1; i++) { - for (int j = limitX[0]; j < limitX[1]; j++) { - *(video + i * width * 2 + j * 2) = *(video + (i + 1) * width * 2 + j * 2); - *(video + i * width * 2 + j * 2 + 1) = *(video + (i + 1) * width * 2 + j * 2 + 1); - } - } - for (int j = limitX[0]; j < limitX[1]; j++) { - *(video + (limitY[1] - 1) * width * 2 + j * 2) = ' '; - } + for (int i = limitY[0]; i < limitY[1] - 1; i++) { + for (int j = limitX[0]; j < limitX[1]; j++) { + *(video + i * width * 2 + j * 2) = *(video + (i + 1) * width * 2 + j * 2); + *(video + i * width * 2 + j * 2 + 1) = *(video + (i + 1) * width * 2 + j * 2 + 1); + } + } + for (int j = limitX[0]; j < limitX[1]; j++) { + *(video + (limitY[1] - 1) * width * 2 + j * 2) = ' '; + } } -int printStringLen(int color, const char * string, int maxLen) { - int i = 0; - - while (*string != '\0' && i <= maxLen) { - if (*string == '\n') { - new_line(); - string++; - i++; - continue; - } - else if (*string == '\b') { - backspace(); - return i; - } - else if (checkIfEscapeSequence(string)) { - return i; - } +int printStringLen(int color, const char *string, int maxLen) { + int i = 0; + + while (*string != '\0' && i <= maxLen) { + if (*string == '\n') { + new_line(); + string++; + i++; + continue; + } else if (*string == '\b') { + backspace(); + return i; + } else if (checkIfEscapeSequence(string)) { + return i; + } *(video + currentY * width * 2 + currentX * 2) = *string++; *(video + currentY * width * 2 + currentX * 2 + 1) = color; - increment(); - i++; + increment(); + i++; } - return i; + return i; } void backspace() { - if (video + currentY * width * 2 + currentX * 2 > video) { - currentX--; - if (currentX < limitX[0]) { - currentX = limitX[1]; - if (currentY > limitY[0]) - currentY--; - } - } - *(video + currentY * width * 2 + currentX * 2) = ' '; + if (video + currentY * width * 2 + currentX * 2 > video) { + currentX--; + if (currentX < limitX[0]) { + currentX = limitX[1]; + if (currentY > limitY[0]) + currentY--; + } + } + *(video + currentY * width * 2 + currentX * 2) = ' '; } void new_line() { - currentX = limitX[0]; - currentY++; - if (currentY == limitY[1]) { - scroll(); - currentY = limitY[1] - 1; - } + currentX = limitX[0]; + currentY++; + if (currentY == limitY[1]) { + scroll(); + currentY = limitY[1] - 1; + } } void clear() { - currentX = limitX[0]; - currentY = limitY[0]; - for (int i = limitY[0]; i < limitY[1]; i++) { - for (int j = limitX[0]; j < limitX[1]; j++) { - *(video + i * width * 2 + j * 2) = ' '; - } - } + currentX = limitX[0]; + currentY = limitY[0]; + for (int i = limitY[0]; i < limitY[1]; i++) { + for (int j = limitX[0]; j < limitX[1]; j++) { + *(video + i * width * 2 + j * 2) = ' '; + } + } } \ No newline at end of file diff --git a/Kernel/include/defs.h b/Kernel/include/defs.h index afda74a..ae7a6bd 100755 --- a/Kernel/include/defs.h +++ b/Kernel/include/defs.h @@ -1,12 +1,6 @@ -/*************************************************** - Defs.h -****************************************************/ - #ifndef _defs_ #define _defs_ - -/* Flags para derechos de acceso de los segmentos */ #define ACS_PRESENT 0x80 /* segmento presente en memoria */ #define ACS_CSEG 0x18 /* segmento de codigo */ #define ACS_DSEG 0x10 /* segmento de datos */ @@ -16,7 +10,6 @@ #define ACS_INT_386 0x0E /* Interrupt GATE 32 bits */ #define ACS_INT ( ACS_PRESENT | ACS_INT_386 ) - #define ACS_CODE (ACS_PRESENT | ACS_CSEG | ACS_READ) #define ACS_DATA (ACS_PRESENT | ACS_DSEG | ACS_WRITE) #define ACS_STACK (ACS_PRESENT | ACS_DSEG | ACS_WRITE) diff --git a/Kernel/include/idtLoader.h b/Kernel/include/idtLoader.h deleted file mode 100644 index 764d58d..0000000 --- a/Kernel/include/idtLoader.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef __IDT_LOADER_H__ -#define __IDT_LOADER_H__ - -void load_idt(); - -#endif diff --git a/Kernel/include/memManager.h b/Kernel/include/memManager.h deleted file mode 100644 index ffcef2a..0000000 --- a/Kernel/include/memManager.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef MEM_MANAGER_H -#define MEM_MANAGER_H - -#include - -// typedef struct MemoryManagerCDT * MemoryManagerADT; - -// MemoryManagerADT createMemoryManager(void *const restrict memoryForMemoryManager, void *const restrict managedMemory); -// void *allocMemory(MemoryManagerADT const restrict memoryManager, const size_t memoryToAllocate); - -// char initMemoryManager(void *const restrict memoryForMemoryManager, void *const restrict managedMemory); -void initMemoryManager(void * managedMemory); -void * memMalloc(unsigned nbytes); -void memFree(void *ap); -// void * memMalloc(const size_t memoryToAllocate); -void * pvPortMalloc(size_t xWantedSize); -void vPortFree( void *pv ); -size_t xPortGetFreeHeapSize( void ); - -// SACAR DPS -char testOne(); -char testTwo(); - -#endif \ No newline at end of file diff --git a/Kernel/include/pcb.h b/Kernel/include/pcb.h deleted file mode 100644 index 544d749..0000000 --- a/Kernel/include/pcb.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef PCB_H -#define PCB_H - -#include -#include - -#define MAX_PROCESSES 2 - -uint64_t loadProcess(uint64_t rsp, void (*fn), uint64_t rbp); -uint64_t preserveStack(uint64_t rsp); -void newProcess(void (*fn)); -void newStack(uint64_t rsp); -void cleanProcesses(); - -void * _initialize_stack_frame(void * rip, const void * rsp); - -void saveSampleRSP(uint64_t rsp); -uint64_t getSampleRSP(); - -#endif \ No newline at end of file diff --git a/Kernel/include/queue.h b/Kernel/include/queue.h deleted file mode 100644 index 9f585c1..0000000 --- a/Kernel/include/queue.h +++ /dev/null @@ -1,8 +0,0 @@ -// #include "scheduler.h" - -// typedef struct queueCDT * queueADT; - -// void queue(queueADT * my_queue, processADT * process); -// char isEmpty(queueADT * my_queue); -// processADT * dequeue(queueADT * my_queue); -// queueADT createQueue(); \ No newline at end of file diff --git a/Kernel/interruptions/exceptions.c b/Kernel/interruptions/exceptions.c index 2eb7400..b8e71e7 100755 --- a/Kernel/interruptions/exceptions.c +++ b/Kernel/interruptions/exceptions.c @@ -1,17 +1,8 @@ -#include "lib.h" -#include "time.h" -#include "naiveConsole.h" -#include "pcb.h" -#include "video.h" -#include "keyboard.h" -#include "interrupts.h" +#include "exceptions.h" static void * const sampleCodeAddress = (void *) 0x400000; typedef int (* fn)(); -#define ZERO_EXCEPTION_ID 0 -#define INVALID_OPCODE_ID 6 - static void zero_division(); static void invalid_opcode(); @@ -42,12 +33,6 @@ static char * regsNames[] = { void printRegs() { uint64_t * regs = stackFrame; - - // 8 bytes = 64 bits = 2^64 - // máximo: 18.446.744.073.709.551.616 / 2 - // máximo: 9.223.372.036.854.775.808 entonces de 0 a 18 - // dejo el primero para un - - char buffer[20]; for (int i = 0; i < 15; i++) { @@ -95,7 +80,6 @@ static void startOver() { } static void genericException(char * string, int len) { - // moveToWindowVideo(-1); clear(); printStringLen(15, string, len); printRegs(); diff --git a/Kernel/interruptions/idtLoader.c b/Kernel/interruptions/idtLoader.c index 5a2c1c0..db45ef8 100755 --- a/Kernel/interruptions/idtLoader.c +++ b/Kernel/interruptions/idtLoader.c @@ -1,12 +1,8 @@ -#include -#include -#include -#include +#include "idtLoader.h" -#pragma pack(push) /* Push de la alineación actual */ -#pragma pack (1) /* Alinear las siguiente estructuras a 1 byte */ +#pragma pack(push) +#pragma pack (1) -/* Descriptor de interrupcion */ typedef struct { uint16_t offset_l, selector; uint8_t cero, access; @@ -14,29 +10,25 @@ typedef struct { uint32_t offset_h, other_cero; } DESCR_INT; -#pragma pack(pop) /* Reestablece la alinceación actual */ +#pragma pack(pop) -DESCR_INT * idt = (DESCR_INT *) 0; // IDT de 255 entradas +DESCR_INT *idt = (DESCR_INT *) 0; -static void setup_IDT_entry (int index, uint64_t offset); +static void setup_IDT_entry(int index, uint64_t offset); void load_idt() { + setup_IDT_entry(0x20, (uint64_t) &_irq00Handler); + setup_IDT_entry(0x21, (uint64_t) &_irq01Handler); + setup_IDT_entry(0x00, (uint64_t) &_exception0Handler); + setup_IDT_entry(0x06, (uint64_t) &_exception6Handler); - setup_IDT_entry (0x20, (uint64_t)&_irq00Handler); - setup_IDT_entry (0x21, (uint64_t)&_irq01Handler); - setup_IDT_entry (0x00, (uint64_t)&_exception0Handler); - setup_IDT_entry (0x06, (uint64_t)&_exception6Handler); + setup_IDT_entry(0x80, (uint64_t) &_systemCallsHandler); - setup_IDT_entry (0x80, (uint64_t)&_systemCallsHandler); - // setup_IDT_entry (0x81, (uint64_t)&_switchContext); - - picMasterMask(0xFC); - picSlaveMask(0xFF); - - // _sti(); + picMasterMask(0xFC); + picSlaveMask(0xFF); } -static void setup_IDT_entry (int index, uint64_t offset) { +static void setup_IDT_entry(int index, uint64_t offset) { idt[index].selector = 0x08; idt[index].offset_l = offset & 0xFFFF; idt[index].offset_m = (offset >> 16) & 0xFFFF; diff --git a/Kernel/interruptions/include/exceptions.h b/Kernel/interruptions/include/exceptions.h new file mode 100644 index 0000000..a8c88a7 --- /dev/null +++ b/Kernel/interruptions/include/exceptions.h @@ -0,0 +1,15 @@ +#ifndef EXCEPTIONS_H +#define EXCEPTIONS_H + +#include "lib.h" +#include "time.h" +#include "naiveConsole.h" +#include "pcb.h" +#include "video.h" +#include "keyboard.h" +#include "interrupts.h" + +#define ZERO_EXCEPTION_ID 0 +#define INVALID_OPCODE_ID 6 + +#endif \ No newline at end of file diff --git a/Kernel/interruptions/include/idtLoader.h b/Kernel/interruptions/include/idtLoader.h new file mode 100644 index 0000000..3e00390 --- /dev/null +++ b/Kernel/interruptions/include/idtLoader.h @@ -0,0 +1,10 @@ +#ifndef IDT_LOADER_H +#define IDT_LOADER_H + +#include +#include +#include + +void load_idt(); + +#endif diff --git a/Kernel/include/interrupts.h b/Kernel/interruptions/include/interrupts.h similarity index 90% rename from Kernel/include/interrupts.h rename to Kernel/interruptions/include/interrupts.h index c67b289..ef6f608 100755 --- a/Kernel/include/interrupts.h +++ b/Kernel/interruptions/include/interrupts.h @@ -1,7 +1,8 @@ #ifndef INTERRUPS_H_ #define INTERRUPS_H_ -#include +#include "idtLoader.h" +#include void _irq00Handler(void); void _irq01Handler(void); @@ -27,4 +28,4 @@ void picSlaveMask(uint8_t mask); void haltcpu(void); -#endif /* INTERRUPS_H_ */ +#endif diff --git a/Kernel/interruptions/include/systemCalls.h b/Kernel/interruptions/include/systemCalls.h new file mode 100644 index 0000000..4ececd3 --- /dev/null +++ b/Kernel/interruptions/include/systemCalls.h @@ -0,0 +1,19 @@ +#ifndef SYSCALLS_H +#define SYSCALLS_H + +#include "video.h" +#include "keyboard.h" +#include "time.h" +#include "pcb.h" +#include "pipeLib.h" +#include "schedulerLib.h" +#include "systemCallsLib.h" + +#define STDIN 0 +#define STDOUT 1 +#define STDERR 2 + +#define STDOUT_COLOR 0x0f +#define STDERR_COLOR 0x04 + +#endif \ No newline at end of file diff --git a/Kernel/include/systemCalls.h b/Kernel/interruptions/include/systemCallsLib.h similarity index 50% rename from Kernel/include/systemCalls.h rename to Kernel/interruptions/include/systemCallsLib.h index 048cac4..150d80f 100644 --- a/Kernel/include/systemCalls.h +++ b/Kernel/interruptions/include/systemCallsLib.h @@ -1,11 +1,9 @@ -#ifndef SYSCALLS_H -#define SYSCALLS_H +#ifndef SYSCALLSLIB_H +#define SYSCALLSLIB_H #include uint64_t write(uint64_t, uint64_t, uint64_t); uint64_t read(uint64_t, uint64_t, uint64_t); -uint64_t getTime(uint64_t, uint64_t, uint64_t); -void createProcess(); #endif \ No newline at end of file diff --git a/Kernel/interruptions/irqDispatcher.c b/Kernel/interruptions/irqDispatcher.c index 9c6d37c..2a7c886 100755 --- a/Kernel/interruptions/irqDispatcher.c +++ b/Kernel/interruptions/irqDispatcher.c @@ -1,26 +1,26 @@ -#include #include static void int_20(); static void int_21(); void keyboard_handler(); +void timer_handler(); void irqDispatcher(uint64_t irq) { - switch (irq) { - case 0: - int_20(); - break; - case 1: - int_21(); - break; - } - return; + switch (irq) { + case 0: + int_20(); + break; + case 1: + int_21(); + break; + } + return; } void int_20() { - timer_handler(); + timer_handler(); } void int_21() { - keyboard_handler(); + keyboard_handler(); } diff --git a/Kernel/interruptions/systemCalls.c b/Kernel/interruptions/systemCalls.c index dd5b61c..bd94a66 100644 --- a/Kernel/interruptions/systemCalls.c +++ b/Kernel/interruptions/systemCalls.c @@ -1,27 +1,14 @@ -#include -#include "video.h" -#include "keyboard.h" -#include "time.h" -#include "pcb.h" -#include "pipeLib.h" -#include "schedulerLib.h" - -#define STDIN 0 -#define STDOUT 1 -#define STDERR 2 - -#define STDOUT_COLOR 0x0f -#define STDERR_COLOR 0x04 +#include "systemCalls.h" uint64_t write(uint64_t fd, uint64_t buffer, uint64_t length) { - char * bufferAux = (char *) buffer; + char *bufferAux = (char *) buffer; int color = STDOUT_COLOR; fd = getFdOut(); if (fd != STDOUT) { int i = 0; - while (bufferAux[i] != '\0' && i <= length) { + while (bufferAux[i] != '\0' && i <= length) { writePipe(fd, bufferAux[i++]); } return i; @@ -31,7 +18,7 @@ uint64_t write(uint64_t fd, uint64_t buffer, uint64_t length) { } uint64_t read(uint64_t fd, uint64_t buffer, uint64_t length) { - char * bufferAux = (char *) buffer; + char *bufferAux = (char *) buffer; int readBytes = 0; if (!isForeground()) @@ -56,8 +43,7 @@ uint64_t read(uint64_t fd, uint64_t buffer, uint64_t length) { bufferAux++; // blockIO(); } - } - else { + } else { while (length-- > 0) { *bufferAux = readPipe(fd); if (*bufferAux == 0) @@ -67,9 +53,5 @@ uint64_t read(uint64_t fd, uint64_t buffer, uint64_t length) { } } - return readBytes; -} - -// void createProcess(void (*fn)) { -// newProcess(fn); -// } \ No newline at end of file + return readBytes; +} \ No newline at end of file diff --git a/Kernel/interruptions/systemCallsDispatcher.c b/Kernel/interruptions/systemCallsDispatcher.c index a452adc..ceae7f0 100644 --- a/Kernel/interruptions/systemCallsDispatcher.c +++ b/Kernel/interruptions/systemCallsDispatcher.c @@ -1,24 +1,18 @@ #include #include "systemCalls.h" #include "memManager.h" - -void exitProcess(); -// void setFn(uint64_t, uint64_t, uint64_t); -char * processes(); -// int enqueueProcess(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t); -char openPipe(int *, char *); -char nice(int, char); +#include "pipeLib.h" #include "semLib.h" #include "schedulerLib.h" uint64_t systemCallsDispatcher(uint64_t rdi, uint64_t rsi, uint64_t rdx, uint64_t rcx, uint64_t r8, uint64_t r9) { - switch (rdi) { - case 0: + switch (rdi) { + case 0: return write(rsi, rdx, rcx); case 1: return read(rsi, rdx, rcx); case 2: - return getTime(rsi, rdx, rcx); + return getTime(rsi); case 3: return enqueueProcess((void (*)(int, char **)) rsi, rdx, rcx, (char **) r8, (int *) r9); case 4: @@ -67,6 +61,6 @@ uint64_t systemCallsDispatcher(uint64_t rdi, uint64_t rsi, uint64_t rdx, uint64_ return pipes(); default: return -1; - } + } return 1; } \ No newline at end of file diff --git a/Kernel/kernel.c b/Kernel/kernel.c index cd321eb..3de6b0f 100644 --- a/Kernel/kernel.c +++ b/Kernel/kernel.c @@ -18,38 +18,40 @@ extern uint8_t endOfKernel; static const uint64_t PageSize = 0x1000; -static void * const sampleCodeModuleAddress = (void*)0x400000; -static void * const sampleDataModuleAddress = (void*)0x500000; -static void * const memoryModuleAddress = (void*)0x600000; +static void *const sampleCodeModuleAddress = (void *) 0x400000; +static void *const sampleDataModuleAddress = (void *) 0x500000; +static void *const memoryModuleAddress = (void *) 0x600000; typedef int (*EntryPoint)(); -void clearBSS(void * bssAddress, uint64_t bssSize) { - memset(bssAddress, 0, bssSize); +void clearBSS(void *bssAddress, uint64_t bssSize) { + memset(bssAddress, 0, bssSize); } -void * getStackBase() { - return (void*)( - (uint64_t)&endOfKernel - + PageSize * 8 //The size of the stack itself, 32KiB - - sizeof(uint64_t) //Begin at the top of the stack - ); +void *getStackBase() { + return (void *) ( + (uint64_t) & endOfKernel + + PageSize * 8 //The size of the stack itself, 32KiB + - sizeof(uint64_t) //Begin at the top of the stack + ); } -void * initializeKernelBinary() { - void * moduleAddresses[] = { - sampleCodeModuleAddress, - sampleDataModuleAddress - }; +void *initializeKernelBinary() { + void *moduleAddresses[] = { + sampleCodeModuleAddress, + sampleDataModuleAddress + }; - loadModules(&endOfKernelBinary, moduleAddresses); - clearBSS(&bss, &endOfKernel - &bss); + loadModules(&endOfKernelBinary, moduleAddresses); + clearBSS(&bss, &endOfKernel - &bss); - return getStackBase(); + return getStackBase(); } void load_idt(); + uint64_t getRSP(); + void printBottlerAndWait(); #include "test_util.h" @@ -62,167 +64,127 @@ void printBottlerAndWait(); #define MAX_MEMORY 352//1024-42x16 //Should be around 80% of memory managed by the MM #endif -typedef struct MM_rq{ - void *address; - uint32_t size; -}mm_rq; +typedef struct MM_rq { + void *address; + uint32_t size; +} mm_rq; -void test_mm(){ - mm_rq mm_rqs[MAX_BLOCKS]; - uint8_t rq; - uint32_t total; +void test_mm() { + mm_rq mm_rqs[MAX_BLOCKS]; + uint8_t rq; + uint32_t total; - int i = 1000; - while (i-- != 0){ + int i = 1000; + while (i-- != 0) { // while (1){ - rq = 0; - total = 0; + rq = 0; + total = 0; - // Request as many blocks as we can - while(rq < MAX_BLOCKS && total < MAX_MEMORY){ - mm_rqs[rq].size = GetUniform(MAX_MEMORY - total - 1) + 1; - mm_rqs[rq].address = pvPortMalloc(mm_rqs[rq].size); - // mm_rqs[rq].address = memMalloc(mm_rqs[rq].size); - if (mm_rqs[rq].address == NULL) { - for (int rqAux = 0; rqAux < rq; rqAux++) { - ncPrintDec(mm_rqs[rqAux].size ); - ncPrint(" - "); - } - // printStringLen(13, "malloc() -- ERROR", 20); - // new_line(); - ncPrint("Malloc -- null"); - ncNewline(); - } - total += mm_rqs[rq].size; - rq++; - } - - // ncPrint("libre dps de malloc: "); - // ncPrintDec(xPortGetFreeHeapSize()); - // ncNewline(); - // ncPrint("cumpli maximo"); - // ncNewline(); + // Request as many blocks as we can + while (rq < MAX_BLOCKS && total < MAX_MEMORY) { + mm_rqs[rq].size = GetUniform(MAX_MEMORY - total - 1) + 1; + mm_rqs[rq].address = pvPortMalloc(mm_rqs[rq].size); + // mm_rqs[rq].address = memMalloc(mm_rqs[rq].size); + if (mm_rqs[rq].address == NULL) { + for (int rqAux = 0; rqAux < rq; rqAux++) { + ncPrintDec(mm_rqs[rqAux].size); + ncPrint(" - "); + } + // printStringLen(13, "malloc() -- ERROR", 20); + // new_line(); + ncPrint("Malloc -- null"); + ncNewline(); + } + total += mm_rqs[rq].size; + rq++; + } - // Set - uint32_t i; - for (i = 0; i < rq; i++) - if (mm_rqs[i].address != NULL) - memset(mm_rqs[i].address, i, mm_rqs[i].size); + // ncPrint("libre dps de malloc: "); + // ncPrintDec(xPortGetFreeHeapSize()); + // ncNewline(); + // ncPrint("cumpli maximo"); + // ncNewline(); - // Check - for (i = 0; i < rq; i++) - if (mm_rqs[i].address != NULL) - if(!memcheck(mm_rqs[i].address, i, mm_rqs[i].size)) { - // printStringLen(13, "memCheck() -- ERROR", 20); - // new_line(); - ncPrint("memCheck -- null"); - ncNewline(); - } + // Set + uint32_t i; + for (i = 0; i < rq; i++) + if (mm_rqs[i].address != NULL) + memset(mm_rqs[i].address, i, mm_rqs[i].size); - // Free - for (i = 0; i < rq; i++) { - if (mm_rqs[i].address != NULL) - vPortFree(mm_rqs[i].address); - } + // Check + for (i = 0; i < rq; i++) + if (mm_rqs[i].address != NULL) + if (!memcheck(mm_rqs[i].address, i, mm_rqs[i].size)) { + // printStringLen(13, "memCheck() -- ERROR", 20); + // new_line(); + ncPrint("memCheck -- null"); + ncNewline(); + } + + // Free + for (i = 0; i < rq; i++) { + if (mm_rqs[i].address != NULL) + vPortFree(mm_rqs[i].address); + } // memFree(mm_rqs[i].address); - - // ncPrint("libre dps de free: "); - // ncPrintDec(xPortGetFreeHeapSize()); - // ncNewline(); - ncPrint("termine un loop regio"); - ncNewline(); - // if (i == 5) - // wait(3); - // ncClear(); + // ncPrint("libre dps de free: "); + // ncPrintDec(xPortGetFreeHeapSize()); + // ncNewline(); + ncPrint("termine un loop regio"); + ncNewline(); - // printStringLen(13, "ALL GOOD", 9); - // new_line(); - } + // if (i == 5) + // wait(3); + // ncClear(); + + // printStringLen(13, "ALL GOOD", 9); + // new_line(); + } } // void enqueueProcess(void (*fn) (int, char **), char foreground, int argc, char *argv[], int * fd); void initScheduler(); void _cli(); + void _sti(); + void haltcpu(); + void forceTimer(); int main() { - // _cli(); + // _cli(); - load_idt(); + load_idt(); - // if (initMemoryManager(memoryModuleAddress, memoryModuleAddress + sizeof(void *)) == -1) { + // if (initMemoryManager(memoryModuleAddress, memoryModuleAddress + sizeof(void *)) == -1) { // printStringLen(13, "createMemoryManager() -- ERROR", 31); - // new_line(); - // return EXIT_FAILURE; - // } + // new_line(); + // return EXIT_FAILURE; + // } - initMemoryManager(memoryModuleAddress); - initScheduler(); + initMemoryManager(memoryModuleAddress); + initScheduler(); - #ifndef BUDDY - // SACAR DESPUÉS! ES SOLO PARA TESTEO... CORRER DE A UNO! - // if (testOne() == EXIT_FAILURE) - // return EXIT_FAILURE; - // if (testTwo() == EXIT_FAILURE) - // return EXIT_FAILURE; - #endif - // test_mm(); +#ifndef BUDDY + // SACAR DESPUÉS! ES SOLO PARA TESTEO... CORRER DE A UNO! + // if (testOne() == EXIT_FAILURE) + // return EXIT_FAILURE; + // if (testTwo() == EXIT_FAILURE) + // return EXIT_FAILURE; +#endif + // test_mm(); - saveSampleRSP(getRSP()); - + saveSampleRSP(getRSP()); - // ((EntryPoint)sampleCodeModuleAddress)(); - char * argv[] = {"SampleCode"}; + char *argv[] = {"SampleCode"}; enqueueProcess(sampleCodeModuleAddress, 1, 1, argv, NULL); - clear(); - // haltcpu(); - _sti(); - forceTimer(); + clear(); + // haltcpu(); + _sti(); + forceTimer(); - // printBottlerAndWait(); - return EXIT_SUCCESS; -} - -void printBottlerAndWait() { - printStringLen(4, " ", 80); new_line(); - printStringLen(4, " (%( ", 80); new_line(); - printStringLen(15, " Welcome to", 17); - printStringLen(4, " %%%%% ", 80); new_line(); - printStringLen(15, " BottlerOS", 18); - printStringLen(4, " %%% ", 80); new_line(); - printStringLen(12, " %%%%%%%%%%%%% ", 80); new_line(); - printStringLen(12, " %%%%%%%%%%%%%%%%%%%%% ", 80); new_line(); - printStringLen(12, " %%%%%%% %%%%%%% ", 80); new_line(); - printStringLen(12, " %%%%% %%%%% ", 80); new_line(); - printStringLen(14, " %%%%% %%%%% ", 80); new_line(); - printStringLen(14, " %%%%% ", 27); - printStringLen(14, " %%%% %%%% ", 22); - printStringLen(14, " %%%%% ", 30); new_line(); - printStringLen(14, " %%%%% ", 28); - printStringLen(14, " (% %( ", 21); - printStringLen(14, " %%%%% ", 30); new_line(); - printStringLen(14, " %%%%%%% %%%%%%% ", 80); new_line(); - printStringLen(2, " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); new_line(); - printStringLen(2, " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); new_line(); - printStringLen(2, " %%%%%%%%%%%%%%%%%%%%%%% ", 41); - printStringLen(12, " % %* ", 8); - printStringLen(2, " %%%%%%%%% ", 30); new_line(); - printStringLen(2, " %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); new_line(); - printStringLen(9, " %%**%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/%% ", 80); new_line(); - printStringLen(9, " %%* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% /%% ", 80); new_line(); - printStringLen(9, " %%* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% /%% ", 80); new_line(); - printStringLen(9, " %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% ", 80); new_line(); - printStringLen(13, " ,%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%. ", 80); new_line(); - printStringLen(13, " %%. %%%%%%%%%%%%%%%%% .%% ", 80); new_line(); - printStringLen(13, " %%%%%%%%%%%%% ", 80); new_line(); - printStringLen(13, " %%%%%%% ", 80); new_line(); - printStringLen(13, " ", 80); new_line(); - - // wait(3); - - clear(); + return EXIT_SUCCESS; } \ No newline at end of file diff --git a/Kernel/lib.c b/Kernel/lib.c index f992436..a936417 100644 --- a/Kernel/lib.c +++ b/Kernel/lib.c @@ -1,61 +1,44 @@ -#include +#include "lib.h" -void * memset(void * destination, int32_t c, uint64_t length) -{ - uint8_t chr = (uint8_t)c; - char * dst = (char*)destination; +void *memset(void *destination, int32_t c, uint64_t length) { + uint8_t chr = (uint8_t) c; + char *dst = (char *) destination; - while(length--) - dst[length] = chr; + while (length--) + dst[length] = chr; - return destination; + return destination; } -void * memcpy(void * destination, const void * source, uint64_t length) -{ - /* - * memcpy does not support overlapping buffers, so always do it - * forwards. (Don't change this without adjusting memmove.) - * - * For speedy copying, optimize the common case where both pointers - * and the length are word-aligned, and copy word-at-a-time instead - * of byte-at-a-time. Otherwise, copy by bytes. - * - * The alignment logic below should be portable. We rely on - * the compiler to be reasonably intelligent about optimizing - * the divides and modulos out. Fortunately, it is. - */ - uint64_t i; +void *memcpy(void *destination, const void *source, uint64_t length) { + uint64_t i; - if ((uint64_t)destination % sizeof(uint32_t) == 0 && - (uint64_t)source % sizeof(uint32_t) == 0 && - length % sizeof(uint32_t) == 0) - { - uint32_t *d = (uint32_t *) destination; - const uint32_t *s = (const uint32_t *)source; + if ((uint64_t) destination % sizeof(uint32_t) == 0 && + (uint64_t) source % sizeof(uint32_t) == 0 && + length % sizeof(uint32_t) == 0) { + uint32_t *d = (uint32_t *) destination; + const uint32_t *s = (const uint32_t *) source; - for (i = 0; i < length / sizeof(uint32_t); i++) - d[i] = s[i]; - } - else - { - uint8_t * d = (uint8_t*)destination; - const uint8_t * s = (const uint8_t*)source; + for (i = 0; i < length / sizeof(uint32_t); i++) + d[i] = s[i]; + } else { + uint8_t *d = (uint8_t *) destination; + const uint8_t *s = (const uint8_t *) source; - for (i = 0; i < length; i++) - d[i] = s[i]; - } + for (i = 0; i < length; i++) + d[i] = s[i]; + } - return destination; + return destination; } void swap(char *x, char *y) { - char t = *x; - *x = *y; - *y = t; + char t = *x; + *x = *y; + *y = t; } - -char * reverse(char * buffer, int i, int j) { + +char *reverse(char *buffer, int i, int j) { while (i < j) { swap(&buffer[i++], &buffer[j--]); } @@ -67,54 +50,49 @@ int abs(int value) { return value < 0 ? -value : value; } -char addSpaces(char * str, char qty) { +char addSpaces(char *str, char qty) { char aux = qty; while (qty-- > 0) { *str++ = ' '; } return aux; } - -char * itoa(int value, char * buffer, int base, int length) { - if (base < 2 || base > 32) { + +char *itoa(int value, char *buffer, int base, int length) { + if (base < 2 || base > 32) { return buffer; } - + int n = abs(value); int i = 0; while (n && i < length) { int r = n % base; - + if (r >= 10) { buffer[i++] = 65 + (r - 10); - } - else { + } else { buffer[i++] = 48 + r; } - + n = n / base; } - + if (i == 0) { buffer[i++] = '0'; } - + if (value < 0 && base == 10) { buffer[i++] = '-'; } - + buffer[i] = '\0'; return reverse(buffer, 0, i - 1); } -void strlen(const char *str, int *len) { - for (*len = 0; str[*len]; (*len)++); -} - -int strcpy(char * strDest, const char * strSrc) { - int i = 0; +int strcpy(char *strDest, const char *strSrc) { + int i = 0; while ((*strDest++ = *strSrc++)) { - i++; - } + i++; + } return i; } \ No newline at end of file diff --git a/Kernel/moduleLoader.c b/Kernel/moduleLoader.c index b303c05..293dea9 100644 --- a/Kernel/moduleLoader.c +++ b/Kernel/moduleLoader.c @@ -3,24 +3,24 @@ #include #include -static uint32_t readUint32(uint8_t ** address) { - uint32_t result = *(uint32_t*)(*address); - *address += sizeof(uint32_t); - return result; +static uint32_t readUint32(uint8_t **address) { + uint32_t result = *(uint32_t *)(*address); + *address += sizeof(uint32_t); + return result; } -static void loadModule(uint8_t ** module, void * targetModuleAddress) { - uint32_t moduleSize = readUint32(module); +static void loadModule(uint8_t **module, void *targetModuleAddress) { + uint32_t moduleSize = readUint32(module); - memcpy(targetModuleAddress, *module, moduleSize); - *module += moduleSize; + memcpy(targetModuleAddress, *module, moduleSize); + *module += moduleSize; } -void loadModules(void * payloadStart, void ** targetModuleAddress) { - int i; - uint8_t * currentModule = (uint8_t*)payloadStart; - uint32_t moduleCount = readUint32(¤tModule); +void loadModules(void *payloadStart, void **targetModuleAddress) { + int i; + uint8_t *currentModule = (uint8_t *) payloadStart; + uint32_t moduleCount = readUint32(¤tModule); - for (i = 0; i < moduleCount; i++) - loadModule(¤tModule, targetModuleAddress[i]); + for (i = 0; i < moduleCount; i++) + loadModule(¤tModule, targetModuleAddress[i]); } \ No newline at end of file diff --git a/Kernel/include/test_util.h b/Kernel/tests/include/test_util.h similarity index 100% rename from Kernel/include/test_util.h rename to Kernel/tests/include/test_util.h diff --git a/Kernel/utils/include/memManager.h b/Kernel/utils/include/memManager.h new file mode 100644 index 0000000..56eb86c --- /dev/null +++ b/Kernel/utils/include/memManager.h @@ -0,0 +1,14 @@ +#ifndef MEM_MANAGER_H +#define MEM_MANAGER_H + +#include + +void initMemoryManager(void * managedMemory); +void * memMalloc(unsigned nbytes); +void memFree(void *ap); +// void * memMalloc(const size_t memoryToAllocate); +void * pvPortMalloc(size_t xWantedSize); +void vPortFree( void *pv ); +size_t xPortGetFreeHeapSize( void ); + +#endif \ No newline at end of file diff --git a/Kernel/utils/include/pcb.h b/Kernel/utils/include/pcb.h new file mode 100644 index 0000000..599cc22 --- /dev/null +++ b/Kernel/utils/include/pcb.h @@ -0,0 +1,9 @@ +#ifndef PCB_H +#define PCB_H + +#include + +void saveSampleRSP(uint64_t rsp); +uint64_t getSampleRSP(); + +#endif \ No newline at end of file diff --git a/Kernel/include/pipe.h b/Kernel/utils/include/pipe.h similarity index 90% rename from Kernel/include/pipe.h rename to Kernel/utils/include/pipe.h index 111f6d4..4073303 100644 --- a/Kernel/include/pipe.h +++ b/Kernel/utils/include/pipe.h @@ -4,7 +4,7 @@ #include #include #include -#include "lib.h" +#include "../../include/lib.h" #include "scheduler.h" #include "memManager.h" #include "pipeLib.h" diff --git a/Kernel/include/pipeLib.h b/Kernel/utils/include/pipeLib.h similarity index 100% rename from Kernel/include/pipeLib.h rename to Kernel/utils/include/pipeLib.h diff --git a/Kernel/include/scheduler.h b/Kernel/utils/include/scheduler.h similarity index 81% rename from Kernel/include/scheduler.h rename to Kernel/utils/include/scheduler.h index 9edb424..e029e9f 100644 --- a/Kernel/include/scheduler.h +++ b/Kernel/utils/include/scheduler.h @@ -3,8 +3,8 @@ #include "memManager.h" #include -#include "lib.h" -#include "time.h" +#include "../../include/lib.h" +#include "../../drivers/include/time.h" #include #include "schedulerLib.h" @@ -18,6 +18,7 @@ void haltcpu(); #define PROCESS_DATA_MAX_SIZE 100 #define MAX_ATTR_SIZE 6 #define MAX_NAME_SIZE 10 +#define IDLE_PID 1 typedef struct processCDT * processADT; @@ -27,5 +28,6 @@ uint64_t nextProcess(); char updateRSP(uint64_t newRsp); char getProcessData(char * out, processADT proc); processADT searchProcess(processADT * previous, int pid, processADT first); +uint64_t _initialize_stack_frame(void *, void *, int, char **); #endif \ No newline at end of file diff --git a/Kernel/include/schedulerLib.h b/Kernel/utils/include/schedulerLib.h similarity index 100% rename from Kernel/include/schedulerLib.h rename to Kernel/utils/include/schedulerLib.h diff --git a/Kernel/include/sem.h b/Kernel/utils/include/sem.h similarity index 83% rename from Kernel/include/sem.h rename to Kernel/utils/include/sem.h index a0f1f22..2437e29 100644 --- a/Kernel/include/sem.h +++ b/Kernel/utils/include/sem.h @@ -4,13 +4,14 @@ #include #include #include -#include "lib.h" +#include "../../include/lib.h" #include "scheduler.h" #include "memManager.h" #include "semLib.h" #define MAX_SEM 100 #define SEM_DATA_MAX_SIZE 100 +#define MAX_PID 4 void enter_region(uint32_t * lock); void leave_region(uint32_t * lock); diff --git a/Kernel/include/semLib.h b/Kernel/utils/include/semLib.h similarity index 92% rename from Kernel/include/semLib.h rename to Kernel/utils/include/semLib.h index e8105f0..93613ce 100644 --- a/Kernel/include/semLib.h +++ b/Kernel/utils/include/semLib.h @@ -10,7 +10,6 @@ typedef struct pid_t { typedef struct sem_t { unsigned int value; - // char name[MAX_NAME]; char * name; pid_t * entering; pid_t * last; diff --git a/Kernel/utils/memManagerBuddy.c b/Kernel/utils/memManagerBuddy.c index 3a0a096..98d9270 100644 --- a/Kernel/utils/memManagerBuddy.c +++ b/Kernel/utils/memManagerBuddy.c @@ -17,23 +17,23 @@ // } typedef struct meta { - unsigned char allo : 1; // 0000000_ - allocated - unsigned char left : 1; // 000000_0 - first or second - unsigned char size : 6; // ______00 - n where (2^n)-1 is the block size + unsigned char allo : 1; // 0000000_ - allocated + unsigned char left : 1; // 000000_0 - first or second + unsigned char size : 6; // ______00 - n where (2^n)-1 is the block size } Meta; // static char myblock[MANAGED_MEMORY_SIZE]; static char *myblock; void initMemoryManager(void * managedMemory) { - myblock = managedMemory; + myblock = managedMemory; } void unpack(Meta * m, int pos); /* Fills myblock with zeros and creates first metadata */ void init_block() { - memset(&myblock, '\0', MANAGED_MEMORY_SIZE); - memset(&myblock, 54, 1); + memset(&myblock, '\0', MANAGED_MEMORY_SIZE); + memset(&myblock, 54, 1); } int ceil(float num) { @@ -51,218 +51,218 @@ int ceil(float num) { // /* Returns log base 2 of a double d */ // double log2(double d) { -// return log(d) / log(2); +// return log(d) / log(2); // } /* Returns the level a reqSize will fit in */ int size_to_n(size_t reqSize) { - reqSize+=1; - double d = log2((double)reqSize); - return (int)ceil(d); + reqSize+=1; + double d = log2((double)reqSize); + return (int)ceil(d); } /* Returns the position of the next block of the correct size */ int jump_next(int n, int pos) { - int bits = pos>>(n); - bits+=1; - int ret = bits<<(n); + int bits = pos>>(n); + bits+=1; + int ret = bits<<(n); + + if (ret == MANAGED_MEMORY_SIZE) { + return ret; + } else { + return ret; + } - if (ret == MANAGED_MEMORY_SIZE) { - return ret; - } else { - return ret; - } - } /* Returns the position of the left half of a pair */ int jump_back(int n, int pos) { - int bits = pos>>(n); - bits-=1; - return bits<<(n); + int bits = pos>>(n); + bits-=1; + return bits<<(n); } /* Fills a Meta struct with metadata at pos */ void unpack(Meta * m, int pos) { - memset(m, myblock[pos], 1); + memset(m, myblock[pos], 1); } /* Returns whether position at level n is left or right partner */ int is_left(int n, int pos) { - // Manipulate bits to set nth bit on - int k = 1; - k<<=(n); - - // Manipulate bits to zero bits above n - unsigned int p = (unsigned int)pos; - p<<=(31-n); - p>>=(31-n); + // Manipulate bits to set nth bit on + int k = 1; + k<<=(n); - if (k == p) { - return 0; // Right - } else { - return 1; // Left - } + // Manipulate bits to zero bits above n + unsigned int p = (unsigned int)pos; + p<<=(31-n); + p>>=(31-n); + + if (k == p) { + return 0; // Right + } else { + return 1; // Left + } } /* Mergee two unallocated blocks with same size */ void merge(int pos, int pos2, int n) { - - // Create new meta and set size field - char newMeta = (n+1)<<2; - // Set left field - if (is_left(n+1, pos)) { - newMeta+=2; - } + // Create new meta and set size field + char newMeta = (n+1)<<2; - // Add new meta - myblock[pos] = newMeta; + // Set left field + if (is_left(n+1, pos)) { + newMeta+=2; + } - // Delete meta on right partner - myblock[pos2] = 0; + // Add new meta + myblock[pos] = newMeta; + + // Delete meta on right partner + myblock[pos2] = 0; } /* MYmymalloc */ void * pvPortMalloc(size_t reqSize) { - // Check if too big - if (reqSize > MANAGED_MEMORY_SIZE - 1) { - // fprintf(stderr, "Error: Requested size too large\n"); + // Check if too big + if (reqSize > MANAGED_MEMORY_SIZE - 1) { + // fprintf(stderr, "Error: Requested size too large\n"); return NULL; - } + } - // Traverse heap to find block of correct size - algo(n) - int n = size_to_n(reqSize); - int pos = 0; - unsigned char c = 0; - Meta * m = memset(&c, 0, 1); - - while (pos < MANAGED_MEMORY_SIZE) { - // Read metadata - unpack(m, pos); + // Traverse heap to find block of correct size - algo(n) + int n = size_to_n(reqSize); + int pos = 0; + unsigned char c = 0; + Meta * m = memset(&c, 0, 1); - // // Debugging - // if (m->size == 0) { - // exit(0); - // } + while (pos < MANAGED_MEMORY_SIZE) { + // Read metadata + unpack(m, pos); - if (n <= m->size) { - if (m->allo == 1) { - // Jump - pos = jump_next(n, pos); - continue; - } else if (m->size == n) { - // Allocate - myblock[pos]+=1; - pos+=1; - return (void*)((long int)&myblock+pos); - } else { - // Partition + // // Debugging + // if (m->size == 0) { + // exit(0); + // } - // Get partner position - int partner = jump_next((m->size)-1, pos); + if (n <= m->size) { + if (m->allo == 1) { + // Jump + pos = jump_next(n, pos); + continue; + } else if (m->size == n) { + // Allocate + myblock[pos]+=1; + pos+=1; + return (void*)((long int)&myblock+pos); + } else { + // Partition - // Set Left - char meta_1 = 2; - char meta_2 = 0; - - // Set Size - char s = ((m->size)-1)<<2; - meta_1 = (meta_1 | s); - meta_2 = (meta_2 | s); + // Get partner position + int partner = jump_next((m->size)-1, pos); - // Fill in metadata - myblock[pos] = meta_1; - myblock[partner] = meta_2; + // Set Left + char meta_1 = 2; + char meta_2 = 0; - // Continue on same position with new size of block - continue; - } - } else { - // Jump - pos = jump_next(n, pos); - continue; - } - } + // Set Size + char s = ((m->size)-1)<<2; + meta_1 = (meta_1 | s); + meta_2 = (meta_2 | s); + + // Fill in metadata + myblock[pos] = meta_1; + myblock[partner] = meta_2; + + // Continue on same position with new size of block + continue; + } + } else { + // Jump + pos = jump_next(n, pos); + continue; + } + } //error - return 0; + return 0; } /* MYmyfree */ void vPortFree(void * ptr) { - - // Error Checking - if (ptr <= (void *)&myblock || ptr > (void *)(&myblock + MANAGED_MEMORY_SIZE)) { - //error - return; - } - // Get position - // int pos = (int)(ptr-(void *)&myblock-1); + // Error Checking + if (ptr <= (void *)&myblock || ptr > (void *)(&myblock + MANAGED_MEMORY_SIZE)) { + //error + return; + } + + // Get position + // int pos = (int)(ptr-(void *)&myblock-1); int pos = (int)((char *)ptr-(char *)&myblock-1); - // Check if valid metadata location - if (pos%2 == 1 || myblock[pos] == 0) { + // Check if valid metadata location + if (pos%2 == 1 || myblock[pos] == 0) { //error - return; - } + return; + } - // Initialize variables for merge - unsigned char c1 = 0; - unsigned char c2 = 0; - Meta * m1 = memset(&c1, 0, 1); - Meta * m2 = memset(&c2, 0, 1); - unpack(m1,pos); + // Initialize variables for merge + unsigned char c1 = 0; + unsigned char c2 = 0; + Meta * m1 = memset(&c1, 0, 1); + Meta * m2 = memset(&c2, 0, 1); + unpack(m1,pos); - // Change allocated field - myblock[pos] = myblock[pos] - 1; + // Change allocated field + myblock[pos] = myblock[pos] - 1; - while (pos >= 0 && pos <= 8196){ - // Read metadata - unpack(m1,pos); + while (pos >= 0 && pos <= 8196){ + // Read metadata + unpack(m1,pos); - if (m1->left) { // Left Partner + if (m1->left) { // Left Partner - // Get position of other partner and read metadata - int pos2 = jump_next(m1->size, pos); + // Get position of other partner and read metadata + int pos2 = jump_next(m1->size, pos); - if (pos2 >= 0 && pos2 <= MANAGED_MEMORY_SIZE - 2) { - unpack(m2,pos2); - } else { - break; - } + if (pos2 >= 0 && pos2 <= MANAGED_MEMORY_SIZE - 2) { + unpack(m2,pos2); + } else { + break; + } - // Merge or break - if (m2->allo || m2->size != m1->size) { - break; - } else { - merge(pos, pos2, m1->size); - } + // Merge or break + if (m2->allo || m2->size != m1->size) { + break; + } else { + merge(pos, pos2, m1->size); + } - } else { // Right Partner + } else { // Right Partner - // Get position of other partner and read metadata - int pos2 = jump_back(m2->size,pos); + // Get position of other partner and read metadata + int pos2 = jump_back(m2->size,pos); - if (pos2 >= 0 && pos2 <= MANAGED_MEMORY_SIZE -2) { - unpack(m2,pos2); - } else { - break; - } + if (pos2 >= 0 && pos2 <= MANAGED_MEMORY_SIZE -2) { + unpack(m2,pos2); + } else { + break; + } - // Merge or break - if (m2->allo || m2->size != m1->size) { - break; - } else { - merge(pos2, pos, m1->size); - } - } - } + // Merge or break + if (m2->allo || m2->size != m1->size) { + break; + } else { + merge(pos2, pos, m1->size); + } + } + } } #endif \ No newline at end of file diff --git a/Kernel/utils/memManagerFRT4.c b/Kernel/utils/memManagerFRT4.c index c7215ec..be02304 100644 --- a/Kernel/utils/memManagerFRT4.c +++ b/Kernel/utils/memManagerFRT4.c @@ -8,13 +8,13 @@ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE -#define portCHAR char -#define portFLOAT float -#define portDOUBLE double -#define portLONG long -#define portSHORT short -#define portSTACK_TYPE uint32_t -#define portBASE_TYPE long +#define portCHAR char +#define portFLOAT float +#define portDOUBLE double +#define portLONG long +#define portSHORT short +#define portSTACK_TYPE uint32_t +#define portBASE_TYPE long typedef portSTACK_TYPE StackType_t; typedef long BaseType_t; @@ -28,42 +28,41 @@ typedef unsigned long UBaseType_t; // #define portBYTE_ALIGNMENT 16 #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) // 8 // #define portBYTE_ALIGNMENT_MASK ( 0x000F ) // 16 -#define pdFALSE ( ( BaseType_t ) 0 ) -#define pdTRUE ( ( BaseType_t ) 1 ) +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) #define portPOINTER_SIZE_TYPE uint32_t /* A few bytes might be lost to byte aligning the heap start address. */ -#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) -#define heapBITS_PER_BYTE ( ( size_t ) 8 ) -#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) +#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ) +#define heapBITS_PER_BYTE ( ( size_t ) 8 ) +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) /* Define the linked list structure. This is used to link free blocks in order of their memory address. */ -typedef struct A_BLOCK_LINK -{ - struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ - size_t xBlockSize; /*<< The size of the free block. */ +typedef struct A_BLOCK_LINK { + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ } BlockLink_t; static uint8_t *ucHeap; -void initMemoryManager(void * managedMemory) { - ucHeap = managedMemory; + +void initMemoryManager(void *managedMemory) { + ucHeap = managedMemory; } /* Definition of the Heap_stats_t structure. */ -typedef struct xHeapStats -{ - size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */ - size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ - size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ - size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */ - size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */ - size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */ - size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */ +typedef struct xHeapStats { + size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */ + size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */ + size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */ + size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */ } HeapStats_t; /* Prototype of the vPortGetHeapStats() function. */ -void vPortGetHeapStats( HeapStats_t *xHeapStats ); +void vPortGetHeapStats(HeapStats_t *xHeapStats); /*-----------------------------------------------------------*/ @@ -73,19 +72,20 @@ void vPortGetHeapStats( HeapStats_t *xHeapStats ); * the block in front it and/or the block behind it if the memory blocks are * adjacent to each other. */ -static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ); +static void prvInsertBlockIntoFreeList(BlockLink_t *pxBlockToInsert); /* * Called automatically to setup the required heap structures the first time * pvPortMalloc() is called. */ -static void prvHeapInit( void ); +static void prvHeapInit(void); /*-----------------------------------------------------------*/ /* The size of the structure placed at the beginning of each allocated memory block must by correctly byte aligned. */ -static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); +static const size_t xHeapStructSize = + (sizeof(BlockLink_t) + ((size_t)(portBYTE_ALIGNMENT - 1))) & ~((size_t)portBYTE_ALIGNMENT_MASK); /* Create a couple of list links to mark the start and end of the list. */ static BlockLink_t xStart, *pxEnd = NULL; @@ -105,314 +105,288 @@ static size_t xBlockAllocatedBit = 0; /*-----------------------------------------------------------*/ -void *pvPortMalloc( size_t xWantedSize ) -{ -BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; -void *pvReturn = NULL; +void *pvPortMalloc(size_t xWantedSize) { + BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; + void *pvReturn = NULL; - /* If this is the first call to malloc then the heap will require - initialisation to setup the list of free blocks. */ - if( pxEnd == NULL ) - { - prvHeapInit(); - } + /* If this is the first call to malloc then the heap will require + initialisation to setup the list of free blocks. */ + if (pxEnd == NULL) { + prvHeapInit(); + } - /* Check the requested block size is not so large that the top bit is - set. The top bit of the block size member of the BlockLink_t structure - is used to determine who owns the block - the application or the - kernel, so it must be free. */ - if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) - { - /* The wanted size is increased so it can contain a BlockLink_t - structure in addition to the requested amount of bytes. */ - if( xWantedSize > 0 ) - { - xWantedSize += xHeapStructSize; + /* Check the requested block size is not so large that the top bit is + set. The top bit of the block size member of the BlockLink_t structure + is used to determine who owns the block - the application or the + kernel, so it must be free. */ + if ((xWantedSize & xBlockAllocatedBit) == 0) { + /* The wanted size is increased so it can contain a BlockLink_t + structure in addition to the requested amount of bytes. */ + if (xWantedSize > 0) { + xWantedSize += xHeapStructSize; - /* Ensure that blocks are always aligned to the required number - of bytes. */ - if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) - { - /* Byte alignment required. */ - xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); - // configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); - } - } + /* Ensure that blocks are always aligned to the required number + of bytes. */ + if ((xWantedSize & portBYTE_ALIGNMENT_MASK) != 0x00) { + /* Byte alignment required. */ + xWantedSize += (portBYTE_ALIGNMENT - (xWantedSize & portBYTE_ALIGNMENT_MASK)); + // configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + } - if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) - { - /* Traverse the list from the start (lowest address) block until - one of adequate size is found. */ - pxPreviousBlock = &xStart; - pxBlock = xStart.pxNextFreeBlock; - while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) - { - pxPreviousBlock = pxBlock; - pxBlock = pxBlock->pxNextFreeBlock; - } + if ((xWantedSize > 0) && (xWantedSize <= xFreeBytesRemaining)) { + /* Traverse the list from the start (lowest address) block until + one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while ((pxBlock->xBlockSize < xWantedSize) && (pxBlock->pxNextFreeBlock != NULL)) { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } - /* If the end marker was reached then a block of adequate size - was not found. */ - if( pxBlock != pxEnd ) - { - /* Return the memory space pointed to - jumping over the - BlockLink_t structure at its start. */ - pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + /* If the end marker was reached then a block of adequate size + was not found. */ + if (pxBlock != pxEnd) { + /* Return the memory space pointed to - jumping over the + BlockLink_t structure at its start. */ + pvReturn = (void *) (((uint8_t *) pxPreviousBlock->pxNextFreeBlock) + xHeapStructSize); - /* This block is being returned for use so must be taken out - of the list of free blocks. */ - pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + /* This block is being returned for use so must be taken out + of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; - /* If the block is larger than required it can be split into - two. */ - if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) - { - /* This block is to be split into two. Create a new - block following the number of bytes requested. The void - cast is used to prevent byte alignment warnings from the - compiler. */ - pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); - // configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); + /* If the block is larger than required it can be split into + two. */ + if ((pxBlock->xBlockSize - xWantedSize) > heapMINIMUM_BLOCK_SIZE) { + /* This block is to be split into two. Create a new + block following the number of bytes requested. The void + cast is used to prevent byte alignment warnings from the + compiler. */ + pxNewBlockLink = (void *) (((uint8_t *) pxBlock) + xWantedSize); + // configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); - /* Calculate the sizes of two blocks split from the - single block. */ - pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; - pxBlock->xBlockSize = xWantedSize; + /* Calculate the sizes of two blocks split from the + single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; - /* Insert the new block into the list of free blocks. */ - prvInsertBlockIntoFreeList( pxNewBlockLink ); - } + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList(pxNewBlockLink); + } - xFreeBytesRemaining -= pxBlock->xBlockSize; + xFreeBytesRemaining -= pxBlock->xBlockSize; - if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) - { - xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; - } + if (xFreeBytesRemaining < xMinimumEverFreeBytesRemaining) { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } - /* The block is being returned - it is allocated and owned - by the application and has no "next" block. */ - pxBlock->xBlockSize |= xBlockAllocatedBit; - pxBlock->pxNextFreeBlock = NULL; - xNumberOfSuccessfulAllocations++; - } - } - else { + /* The block is being returned - it is allocated and owned + by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + xNumberOfSuccessfulAllocations++; + } + } else { - // ncNewline(); - // ncPrint("MALLOC: "); - // ncPrintDec(xFreeBytesRemaining); - // ncPrint(" "); - // ncPrintDec(xWantedSize); - // ncPrint(" "); - // ncPrintDec(configADJUSTED_HEAP_SIZE); - // ncNewline(); - } - } + // ncNewline(); + // ncPrint("MALLOC: "); + // ncPrintDec(xFreeBytesRemaining); + // ncPrint(" "); + // ncPrintDec(xWantedSize); + // ncPrint(" "); + // ncPrintDec(configADJUSTED_HEAP_SIZE); + // ncNewline(); + } + } - // configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); - return pvReturn; + // configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); + return pvReturn; } + /*-----------------------------------------------------------*/ -void vPortFree( void *pv ) -{ -uint8_t *puc = ( uint8_t * ) pv; -BlockLink_t *pxLink; +void vPortFree(void *pv) { + uint8_t *puc = (uint8_t *) pv; + BlockLink_t *pxLink; - if( pv != NULL ) - { - /* The memory being freed will have an BlockLink_t structure immediately - before it. */ - puc -= xHeapStructSize; + if (pv != NULL) { + /* The memory being freed will have an BlockLink_t structure immediately + before it. */ + puc -= xHeapStructSize; - /* This casting is to keep the compiler from issuing warnings. */ - pxLink = ( void * ) puc; + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = (void *) puc; - /* Check the block is actually allocated. */ - // configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); - // configASSERT( pxLink->pxNextFreeBlock == NULL ); + /* Check the block is actually allocated. */ + // configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); + // configASSERT( pxLink->pxNextFreeBlock == NULL ); - if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) - { - if( pxLink->pxNextFreeBlock == NULL ) - { - /* The block is being returned to the heap - it is no longer - allocated. */ - pxLink->xBlockSize &= ~xBlockAllocatedBit; + if ((pxLink->xBlockSize & xBlockAllocatedBit) != 0) { + if (pxLink->pxNextFreeBlock == NULL) { + /* The block is being returned to the heap - it is no longer + allocated. */ + pxLink->xBlockSize &= ~xBlockAllocatedBit; - { - /* Add this block to the list of free blocks. */ - xFreeBytesRemaining += pxLink->xBlockSize; - prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); - xNumberOfSuccessfulFrees++; - } - } - } - } + { + /* Add this block to the list of free blocks. */ + xFreeBytesRemaining += pxLink->xBlockSize; + prvInsertBlockIntoFreeList(((BlockLink_t *) pxLink)); + xNumberOfSuccessfulFrees++; + } + } + } + } } + /*-----------------------------------------------------------*/ -size_t xPortGetFreeHeapSize( void ) -{ - return xFreeBytesRemaining; +size_t xPortGetFreeHeapSize(void) { + return xFreeBytesRemaining; } + /*-----------------------------------------------------------*/ -size_t xPortGetMinimumEverFreeHeapSize( void ) -{ - return xMinimumEverFreeBytesRemaining; +size_t xPortGetMinimumEverFreeHeapSize(void) { + return xMinimumEverFreeBytesRemaining; } + /*-----------------------------------------------------------*/ -void vPortInitialiseBlocks( void ) -{ - /* This just exists to keep the linker quiet. */ +void vPortInitialiseBlocks(void) { + /* This just exists to keep the linker quiet. */ } + /*-----------------------------------------------------------*/ -static void prvHeapInit( void ) -{ -BlockLink_t *pxFirstFreeBlock; -uint8_t *pucAlignedHeap; -size_t uxAddress; -size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; +static void prvHeapInit(void) { + BlockLink_t *pxFirstFreeBlock; + uint8_t *pucAlignedHeap; + size_t uxAddress; + size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; - /* Ensure the heap starts on a correctly aligned boundary. */ - uxAddress = ( size_t ) ucHeap; + /* Ensure the heap starts on a correctly aligned boundary. */ + uxAddress = (size_t) ucHeap; - if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) - { - uxAddress += ( portBYTE_ALIGNMENT - 1 ); - uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; - } + if ((uxAddress & portBYTE_ALIGNMENT_MASK) != 0) { + uxAddress += (portBYTE_ALIGNMENT - 1); + uxAddress &= ~((size_t)portBYTE_ALIGNMENT_MASK); + xTotalHeapSize -= uxAddress - (size_t) ucHeap; + } - pucAlignedHeap = ( uint8_t * ) uxAddress; + pucAlignedHeap = (uint8_t *) uxAddress; - /* xStart is used to hold a pointer to the first item in the list of free - blocks. The void cast is used to prevent compiler warnings. */ - xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; - xStart.xBlockSize = ( size_t ) 0; + /* xStart is used to hold a pointer to the first item in the list of free + blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = (void *) pucAlignedHeap; + xStart.xBlockSize = (size_t) 0; - /* pxEnd is used to mark the end of the list of free blocks and is inserted - at the end of the heap space. */ - uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; - uxAddress -= xHeapStructSize; - uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); - pxEnd = ( void * ) uxAddress; - pxEnd->xBlockSize = 0; - pxEnd->pxNextFreeBlock = NULL; + /* pxEnd is used to mark the end of the list of free blocks and is inserted + at the end of the heap space. */ + uxAddress = ((size_t) pucAlignedHeap) + xTotalHeapSize; + uxAddress -= xHeapStructSize; + uxAddress &= ~((size_t)portBYTE_ALIGNMENT_MASK); + pxEnd = (void *) uxAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; - /* To start with there is a single free block that is sized to take up the - entire heap space, minus the space taken by pxEnd. */ - pxFirstFreeBlock = ( void * ) pucAlignedHeap; - pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; - pxFirstFreeBlock->pxNextFreeBlock = pxEnd; + /* To start with there is a single free block that is sized to take up the + entire heap space, minus the space taken by pxEnd. */ + pxFirstFreeBlock = (void *) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = uxAddress - (size_t) pxFirstFreeBlock; + pxFirstFreeBlock->pxNextFreeBlock = pxEnd; - /* Only one block exists - and it covers the entire usable heap space. */ - xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; - xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + /* Only one block exists - and it covers the entire usable heap space. */ + xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; - /* Work out the position of the top bit in a size_t variable. */ - xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ((size_t) 1) << ((sizeof(size_t) * heapBITS_PER_BYTE) - 1); } + /*-----------------------------------------------------------*/ -static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) -{ -BlockLink_t *pxIterator; -uint8_t *puc; +static void prvInsertBlockIntoFreeList(BlockLink_t *pxBlockToInsert) { + BlockLink_t *pxIterator; + uint8_t *puc; - /* Iterate through the list until a block is found that has a higher address - than the block being inserted. */ - for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) - { - /* Nothing to do here, just iterate to the right position. */ - } + /* Iterate through the list until a block is found that has a higher address + than the block being inserted. */ + for (pxIterator = &xStart; + pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock) { + /* Nothing to do here, just iterate to the right position. */ + } - /* Do the block being inserted, and the block it is being inserted after - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxIterator; - if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) - { - pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; - pxBlockToInsert = pxIterator; - } + /* Do the block being inserted, and the block it is being inserted after + make a contiguous block of memory? */ + puc = (uint8_t *) pxIterator; + if ((puc + pxIterator->xBlockSize) == (uint8_t *) pxBlockToInsert) { + pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; + pxBlockToInsert = pxIterator; + } - /* Do the block being inserted, and the block it is being inserted before - make a contiguous block of memory? */ - puc = ( uint8_t * ) pxBlockToInsert; - if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) - { - if( pxIterator->pxNextFreeBlock != pxEnd ) - { - /* Form one big block from the two blocks. */ - pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxEnd; - } - } - else - { - pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; - } + /* Do the block being inserted, and the block it is being inserted before + make a contiguous block of memory? */ + puc = (uint8_t *) pxBlockToInsert; + if ((puc + pxBlockToInsert->xBlockSize) == (uint8_t *) pxIterator->pxNextFreeBlock) { + if (pxIterator->pxNextFreeBlock != pxEnd) { + /* Form one big block from the two blocks. */ + pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; + } else { + pxBlockToInsert->pxNextFreeBlock = pxEnd; + } + } else { + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; + } - /* If the block being inserted plugged a gab, so was merged with the block - before and the block after, then it's pxNextFreeBlock pointer will have - already been set, and should not be set here as that would make it point - to itself. */ - if( pxIterator != pxBlockToInsert ) - { - pxIterator->pxNextFreeBlock = pxBlockToInsert; - } + /* If the block being inserted plugged a gab, so was merged with the block + before and the block after, then it's pxNextFreeBlock pointer will have + already been set, and should not be set here as that would make it point + to itself. */ + if (pxIterator != pxBlockToInsert) { + pxIterator->pxNextFreeBlock = pxBlockToInsert; + } } + /*-----------------------------------------------------------*/ -void vPortGetHeapStats( HeapStats_t *pxHeapStats ) -{ -BlockLink_t *pxBlock; -size_t xBlocks = 0, xMaxSize = 0, xMinSize = configTOTAL_HEAP_SIZE;//portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */ +void vPortGetHeapStats(HeapStats_t *pxHeapStats) { + BlockLink_t *pxBlock; + size_t xBlocks = 0, xMaxSize = 0, xMinSize = + configTOTAL_HEAP_SIZE;//portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */ - pxBlock = xStart.pxNextFreeBlock; + pxBlock = xStart.pxNextFreeBlock; - /* pxBlock will be NULL if the heap has not been initialised. The heap - is initialised automatically when the first allocation is made. */ - if( pxBlock != NULL ) - { - do - { - /* Increment the number of blocks and record the largest block seen - so far. */ - xBlocks++; + /* pxBlock will be NULL if the heap has not been initialised. The heap + is initialised automatically when the first allocation is made. */ + if (pxBlock != NULL) { + do { + /* Increment the number of blocks and record the largest block seen + so far. */ + xBlocks++; - if( pxBlock->xBlockSize > xMaxSize ) - { - xMaxSize = pxBlock->xBlockSize; - } + if (pxBlock->xBlockSize > xMaxSize) { + xMaxSize = pxBlock->xBlockSize; + } - if( pxBlock->xBlockSize < xMinSize ) - { - xMinSize = pxBlock->xBlockSize; - } + if (pxBlock->xBlockSize < xMinSize) { + xMinSize = pxBlock->xBlockSize; + } - /* Move to the next block in the chain until the last block is - reached. */ - pxBlock = pxBlock->pxNextFreeBlock; - } while( pxBlock != pxEnd ); - } + /* Move to the next block in the chain until the last block is + reached. */ + pxBlock = pxBlock->pxNextFreeBlock; + } while (pxBlock != pxEnd); + } - pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize; - pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize; - pxHeapStats->xNumberOfFreeBlocks = xBlocks; + pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize; + pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize; + pxHeapStats->xNumberOfFreeBlocks = xBlocks; - pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining; - pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations; - pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees; - pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining; + pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining; + pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations; + pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees; + pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining; } diff --git a/Kernel/utils/pcb.c b/Kernel/utils/pcb.c index dc4f9b3..b6e89cb 100644 --- a/Kernel/utils/pcb.c +++ b/Kernel/utils/pcb.c @@ -1,37 +1,5 @@ #include "pcb.h" -// static const uint8_t * firstProcessAddress = (uint8_t *) 0x18000000; -// static const long stackSize = 0x4000000; // 2^26 -// static const uint8_t * lastProcessAddress = (uint8_t *) 0x10000001; // 2^29 - 1 - -// int activeProcesses = 0, currentProcess = -1; -// uint64_t priority0[MAX_PROCESSES]; -// uint64_t priority1[MAX_PROCESSES]; -// uint64_t priority2[MAX_PROCESSES]; - -// void cleanProcesses() { -// activeProcesses = 0; -// currentProcess = -1; -// } - -// void newProcess(void (*fn)) { -// if (firstProcessAddress - activeProcesses * stackSize + stackSize <= lastProcessAddress) return; -// _initialize_stack_frame(fn, firstProcessAddress - activeProcesses * stackSize); -// } - -// void newStack(uint64_t rsp) { -// priority0[activeProcesses++] = rsp; -// } - -// uint64_t preserveStack(uint64_t rsp) { -// if (currentProcess != -1) { -// priority0[currentProcess] = rsp; -// } -// if (++currentProcess >= activeProcesses) currentProcess = 0; -// if (activeProcesses == 0) return 0; -// return priority0[currentProcess]; -// } - static uint64_t sampleRSP; void saveSampleRSP(uint64_t rsp) { diff --git a/Kernel/utils/pipe.c b/Kernel/utils/pipe.c index 54aa3d8..936b8bd 100644 --- a/Kernel/utils/pipe.c +++ b/Kernel/utils/pipe.c @@ -2,21 +2,21 @@ static int fdIndex = 2; -node_t * firstPipe; +node_t *firstPipe; -char openPipe(int fds[2], char * name) { - pipe_t * pipe = pvPortMalloc(sizeof(pipe_t)); +char openPipe(int fds[2], char *name) { + pipe_t *pipe = pvPortMalloc(sizeof(pipe_t)); pipe->name = pvPortMalloc(MAX_NAME); pipe->buffer = pvPortMalloc(PIPE_MAX_SIZE); strcpy(pipe->name, name); - + if ((pipe->sem = semOpen(SEM_NAME, 1)) == NULL) return EXIT_FAILURE; if ((pipe->fullSem = semOpen(FULL_SEM_NAME, 0)) == NULL) return EXIT_FAILURE; - node_t * node = pvPortMalloc(sizeof(node_t)); + node_t *node = pvPortMalloc(sizeof(node_t)); node->pipe = pipe; node->next = firstPipe; firstPipe = node; @@ -31,60 +31,60 @@ char openPipe(int fds[2], char * name) { return EXIT_SUCCESS; } -node_t * searchPipe(node_t ** previous, int fd) { - node_t * curr = firstPipe; - * previous = NULL; +node_t *searchPipe(node_t **previous, int fd) { + node_t *curr = firstPipe; + *previous = NULL; while (curr != NULL) { if (curr->pipe->fd[0] == fd || curr->pipe->fd[1] == fd) { break; } - * previous = curr; + *previous = curr; curr = curr->next; } if (curr == NULL) { - * previous = NULL; + *previous = NULL; return NULL; } return curr; } -node_t * searchWPipe(node_t ** previous, int fd) { - node_t * curr = firstPipe; - * previous = NULL; +node_t *searchWPipe(node_t **previous, int fd) { + node_t *curr = firstPipe; + *previous = NULL; while (curr != NULL) { if (curr->pipe->fd[1] == fd) { break; } - * previous = curr; + *previous = curr; curr = curr->next; } if (curr == NULL) { - * previous = NULL; + *previous = NULL; return NULL; } return curr; } -node_t * searchRPipe(node_t ** previous, int fd) { - node_t * curr = firstPipe; - * previous = NULL; +node_t *searchRPipe(node_t **previous, int fd) { + node_t *curr = firstPipe; + *previous = NULL; while (curr != NULL) { if (curr->pipe->fd[0] == fd) { break; } - * previous = curr; + *previous = curr; curr = curr->next; } if (curr == NULL) { - * previous = NULL; + *previous = NULL; return NULL; } return curr; } void writePipe(int fd, char c) { - node_t * prev = NULL; - node_t * node = searchWPipe(&prev, fd); + node_t *prev = NULL; + node_t *node = searchWPipe(&prev, fd); semWait(node->pipe->sem); @@ -96,8 +96,8 @@ void writePipe(int fd, char c) { } char readPipe(int fd) { - node_t * prev = NULL; - node_t * node = searchRPipe(&prev, fd); + node_t *prev = NULL; + node_t *node = searchRPipe(&prev, fd); semWait(node->pipe->sem); @@ -111,8 +111,8 @@ char readPipe(int fd) { } void closePipe(int fd) { - node_t * prev = NULL; - node_t * del = searchPipe(&prev, fd); + node_t *prev = NULL; + node_t *del = searchPipe(&prev, fd); if (del == NULL) return; @@ -130,7 +130,7 @@ void closePipe(int fd) { vPortFree(del); } -void getGenPipeData(char ** out, char * written, char toAdd, char * in, char isLast) { +void getGenPipeData(char **out, char *written, char toAdd, char *in, char isLast) { char copied = strcpy(*out, in); *out += copied; *out += addSpaces(*out, toAdd - copied); @@ -141,7 +141,7 @@ void getGenPipeData(char ** out, char * written, char toAdd, char * in, char isL } } -char getPipeData(char * out, node_t * node) { +char getPipeData(char *out, node_t *node) { if (node == NULL) return EXIT_FAILURE; @@ -160,25 +160,25 @@ char getPipeData(char * out, node_t * node) { out += addSpaces(out, 2); written += 2; - + char buffer[10]; getGenPipeData(&out, &written, MAX_ATTR_SIZE, itoa(node->pipe->fd[0], buffer, 10, 2), 0); getGenPipeData(&out, &written, MAX_ATTR_SIZE, itoa(node->pipe->fd[1], buffer, 16, 10), 0); - char * aux = getEntering(node->pipe->sem); + char *aux = getEntering(node->pipe->sem); getGenPipeData(&out, &written, MAX_PIDS_SIZE, aux, 1); vPortFree(aux); - + return written; } -char * pipes(){ - char * ans = pvPortMalloc((fdIndex / 2) * PIPE_DATA_MAX_SIZE); - char * ret = ans; - - char * info = "name fdIn fdOut pids\n"; +char *pipes() { + char *ans = pvPortMalloc((fdIndex / 2) * PIPE_DATA_MAX_SIZE); + char *ret = ans; + + char *info = "name fdIn fdOut pids\n"; ans += strcpy(ans, info); - node_t * aux = firstPipe; + node_t *aux = firstPipe; while (aux != NULL) { char writtenChars = getPipeData(ans, aux); if (writtenChars == EXIT_FAILURE) diff --git a/Kernel/utils/queue.c b/Kernel/utils/queue.c deleted file mode 100644 index 1560e35..0000000 --- a/Kernel/utils/queue.c +++ /dev/null @@ -1,51 +0,0 @@ -// #include "queue.h" -// #include "memManager.h" -// #include - -// typedef struct nodeT { -// processADT * process; -// struct nodeT * next; -// } nodeT; - -// typedef struct queueCDT { -// nodeT * first; -// nodeT * last; -// int length; -// } queueCDT; - -// queueADT createQueue() { -// queueADT aux = pvPortMalloc(sizeof(queueCDT)); -// if (aux == NULL) -// return NULL; -// aux->first = NULL; -// aux->last = NULL; -// aux->length = 0; -// return aux; -// } - -// void queue(queueADT * my_queue, processADT * process) { -// if (my_queue == NULL) -// return; -// nodeT * new_node = pvPortMalloc(sizeof(nodeT)); -// if (new_node == NULL) -// return; -// new_node->process = process; -// new_node->next = NULL; -// (*my_queue)->last->next = new_node; -// (*my_queue)->last = new_node; -// (*my_queue)->length++; -// } - -// processADT * dequeue(queueADT * my_queue) { -// if (my_queue == NULL || isEmpty(my_queue)) -// return NULL; -// nodeT * aux = (*my_queue)->first; -// (*my_queue)->first = (*my_queue)->first->next; -// processADT * ans = aux->process; -// vPortFree(aux); -// return ans; -// } - -// char isEmpty(queueADT * my_queue) { -// return (*my_queue)->length == 0; -// } \ No newline at end of file diff --git a/Kernel/utils/scheduler.c b/Kernel/utils/scheduler.c index 8e50987..1d4c2d2 100644 --- a/Kernel/utils/scheduler.c +++ b/Kernel/utils/scheduler.c @@ -1,13 +1,12 @@ #include "scheduler.h" -#define IDLE_PID 1 -uint64_t _initialize_stack_frame(void *, void *, int, char**); - -enum states {READY = 0, DEAD, BLOCKED, BBCHILDREN, WAITING, BLOCKEDIO}; +enum states { + READY = 0, DEAD, BLOCKED, BBCHILDREN, WAITING, BLOCKEDIO +}; typedef struct processCDT { - struct processCDT * next; - char * name; + struct processCDT *next; + char *name; int pid; int ppid; uint64_t rsp; @@ -16,7 +15,7 @@ typedef struct processCDT { char executions; char foreground; enum states state; - int * fd; + int *fd; int children; char backWait; } processCDT; @@ -25,30 +24,29 @@ typedef struct sleepCDT { int pid; long time; long secs; - struct sleepCDT * next; + struct sleepCDT *next; } sleepCDT; -processCDT * firstBlockedIteration = NULL; +processCDT *firstBlockedIteration = NULL; -processCDT * firstProcess = NULL; -processCDT * lastProcess = NULL; -sleepCDT * firstSleep = NULL; +processCDT *firstProcess = NULL; +processCDT *lastProcess = NULL; +sleepCDT *firstSleep = NULL; -static processCDT * currentProcess = NULL; +static processCDT *currentProcess = NULL; static int pids = IDLE_PID; static char update = 1; static char idleFlag = 2; -void removeProcess(processCDT * del, processCDT ** first, processCDT ** last) { - processCDT * prev = NULL; +void removeProcess(processCDT *del, processCDT **first, processCDT **last) { + processCDT *prev = NULL; del = searchProcess(&prev, del->pid, *first); - + if (prev == NULL) { *first = del->next; if (*last == del) *last = NULL; - } - else { + } else { prev->next = del->next; if (*last == del) *last = prev; @@ -58,28 +56,28 @@ void removeProcess(processCDT * del, processCDT ** first, processCDT ** last) { uint64_t nextProcess(uint64_t currentRSP) { if (currentProcess != NULL) currentProcess->rsp = currentRSP; - processCDT * prev = currentProcess; - if (currentProcess != NULL && currentProcess->state == READY && currentProcess->executions == MAX_PRIORITY - currentProcess->priority + 1) { + processCDT *prev = currentProcess; + if (currentProcess != NULL && currentProcess->state == READY && + currentProcess->executions == MAX_PRIORITY - currentProcess->priority + 1) { currentProcess->executions = 0; currentProcess = currentProcess->next; } - while (currentProcess == NULL || currentProcess->state == BLOCKED || currentProcess->state == DEAD || currentProcess->state == WAITING || currentProcess->state == BLOCKEDIO) { + while (currentProcess == NULL || currentProcess->state == BLOCKED || currentProcess->state == DEAD || + currentProcess->state == WAITING || currentProcess->state == BLOCKEDIO) { if (currentProcess == NULL) { currentProcess = firstProcess; - } - else if (currentProcess == firstBlockedIteration) { + } else if (currentProcess == firstBlockedIteration) { idleFlag = 1; unblock(IDLE_PID); prev = currentProcess; currentProcess = currentProcess->next; - } - else if (currentProcess->state == DEAD) { - processCDT * del = currentProcess; + } else if (currentProcess->state == DEAD) { + processCDT *del = currentProcess; currentProcess = currentProcess->next; removeProcess(del, &firstProcess, &lastProcess); vPortFree((void *) del); - } - else if (currentProcess->state == BLOCKED || currentProcess->state == WAITING || currentProcess->state == BLOCKEDIO) { + } else if (currentProcess->state == BLOCKED || currentProcess->state == WAITING || + currentProcess->state == BLOCKEDIO) { if (firstBlockedIteration == NULL) firstBlockedIteration = currentProcess; prev = currentProcess; @@ -102,13 +100,13 @@ void idle() { } void initScheduler() { - char * argv[] = {"idle"}; + char *argv[] = {"idle"}; nice(enqueueProcess(idle, 0, 1, argv, NULL), 19); } -int enqueueProcess(void (*fn) (int, char **), char foreground, int argc, char *argv[], int * fd) { +int enqueueProcess(void (*fn)(int, char **), char foreground, int argc, char *argv[], int *fd) { if (fd == NULL) { - int * aux = pvPortMalloc(2 * sizeof(int)); + int *aux = pvPortMalloc(2 * sizeof(int)); aux[0] = 0; aux[1] = 1; fd = aux; @@ -126,13 +124,13 @@ int enqueueProcess(void (*fn) (int, char **), char foreground, int argc, char *a } processADT process = pvPortMalloc(sizeof(processCDT)); - uint64_t * auxi = pvPortMalloc(STACK_SIZE); - uint64_t * rbp = STACK_SIZE + auxi; - uint64_t * rsp = rbp - 20; - - char priority = (foreground == 1) ? DEF_PRIORITY : MAX_PRIORITY/2; + uint64_t *auxi = pvPortMalloc(STACK_SIZE); + uint64_t *rbp = STACK_SIZE + auxi; + uint64_t *rsp = rbp - 20; - char * aux = pvPortMalloc(10); + char priority = (foreground == 1) ? DEF_PRIORITY : MAX_PRIORITY / 2; + + char *aux = pvPortMalloc(10); int j; for (j = 0; j < MAX_NAME_SIZE - 1 && argv[0][j] != 0; j++) { aux[j] = argv[0][j]; @@ -157,10 +155,10 @@ int enqueueProcess(void (*fn) (int, char **), char foreground, int argc, char *a if (firstProcess == NULL) firstProcess = process; - else + else lastProcess->next = process; lastProcess = process; - + return process->pid; } @@ -168,7 +166,7 @@ void sleep(int secs) { if (currentProcess == NULL) return; - sleepCDT * proc = pvPortMalloc(sizeof(sleepCDT)); + sleepCDT *proc = pvPortMalloc(sizeof(sleepCDT)); proc->pid = currentProcess->pid; proc->secs = secs; proc->time = getTimeOfDay(); @@ -178,7 +176,7 @@ void sleep(int secs) { block(currentProcess->pid); } -void wakeUp(sleepCDT * wake, sleepCDT * prev) { +void wakeUp(sleepCDT *wake, sleepCDT *prev) { if (wake == firstSleep) firstSleep = wake->next; else { @@ -189,43 +187,42 @@ void wakeUp(sleepCDT * wake, sleepCDT * prev) { } void checkSleeping() { - sleepCDT * prev = NULL; - sleepCDT * aux = firstSleep; - while(aux != NULL) { + sleepCDT *prev = NULL; + sleepCDT *aux = firstSleep; + while (aux != NULL) { if (getTimeOfDay() >= aux->time + aux->secs) { wakeUp(aux, prev); aux = prev->next; - } - else { + } else { prev = aux; aux = aux->next; } } } -processADT searchProcess(processADT * previous, int pid, processADT first) { +processADT searchProcess(processADT *previous, int pid, processADT first) { processADT curr = first; - * previous = NULL; + *previous = NULL; while (curr != NULL) { if (curr->pid == pid) { break; } - * previous = curr; + *previous = curr; curr = curr->next; } if (curr == NULL) { - * previous = NULL; + *previous = NULL; return NULL; } return curr; } void unblockIO() { - processCDT * aux = firstProcess; - while(aux != NULL) { + processCDT *aux = firstProcess; + while (aux != NULL) { if (aux->state == BLOCKEDIO) aux->state = READY; - + aux = aux->next; } } @@ -237,7 +234,7 @@ char blockIO() { currentProcess->state = BLOCKEDIO; } - processCDT * prev = NULL; + processCDT *prev = NULL; processADT parent = searchProcess(&prev, currentProcess->ppid, firstProcess); if (currentProcess->foreground) { if (parent->backWait) { @@ -247,7 +244,7 @@ char blockIO() { } forceTimer(); - return EXIT_SUCCESS; + return EXIT_SUCCESS; } char block(int pid) { @@ -270,7 +267,7 @@ char block(int pid) { forceTimer(); } - return EXIT_SUCCESS; + return EXIT_SUCCESS; } char unblock(int pid) { @@ -278,8 +275,7 @@ char unblock(int pid) { processADT del = searchProcess(&prev, pid, firstProcess); if (del == NULL || del->state == DEAD) { return EXIT_FAILURE; - } - else { + } else { del->state = READY; } @@ -347,8 +343,7 @@ char nice(int pid, char offset) { processADT del = searchProcess(&prev, pid, firstProcess); if (del == NULL) { return EXIT_FAILURE; - } - else { + } else { del->priority = offset + 20; } return EXIT_SUCCESS; @@ -391,7 +386,7 @@ char isForeground() { return currentProcess->foreground; } -void getGenProcessData(char ** out, char * written, char toAdd, char * in, char isLast) { +void getGenProcessData(char **out, char *written, char toAdd, char *in, char isLast) { char copied = strcpy(*out, in); *out += copied; *out += addSpaces(*out, toAdd - copied); @@ -402,7 +397,7 @@ void getGenProcessData(char ** out, char * written, char toAdd, char * in, char } } -char getProcessData(char * out, processCDT * proc) { +char getProcessData(char *out, processCDT *proc) { if (proc == NULL) return EXIT_FAILURE; @@ -421,26 +416,27 @@ char getProcessData(char * out, processCDT * proc) { out += addSpaces(out, 2); written += 2; - + char buffer[10]; getGenProcessData(&out, &written, MAX_ATTR_SIZE, itoa(proc->pid, buffer, 10, 10), 0); getGenProcessData(&out, &written, MAX_ATTR_SIZE, itoa(proc->priority, buffer, 10, 2), 0); getGenProcessData(&out, &written, MAX_NAME_SIZE, itoa(proc->rsp, buffer, 16, 10), 0); getGenProcessData(&out, &written, MAX_NAME_SIZE, itoa(proc->rbp, buffer, 16, 10), 0); getGenProcessData(&out, &written, MAX_ATTR_SIZE, (proc->foreground == 1) ? "F" : "B", 0); - getGenProcessData(&out, &written, MAX_ATTR_SIZE, proc->state == BLOCKED ? "Block" : proc->state == DEAD ? "Killed" : "Ready", 1); - + getGenProcessData(&out, &written, MAX_ATTR_SIZE, + proc->state == BLOCKED ? "Block" : proc->state == DEAD ? "Killed" : "Ready", 1); + return written; } -char * processes(){ - char * ans = pvPortMalloc(pids * PROCESS_DATA_MAX_SIZE); - char * ret = ans; - - char * info = "name pid prio rsp rbp fore state\n"; +char *processes() { + char *ans = pvPortMalloc(pids * PROCESS_DATA_MAX_SIZE); + char *ret = ans; + + char *info = "name pid prio rsp rbp fore state\n"; ans += strcpy(ans, info); - processCDT * aux = firstProcess; + processCDT *aux = firstProcess; while (aux != NULL) { char writtenChars = getProcessData(ans, aux); if (writtenChars == EXIT_FAILURE) diff --git a/Kernel/utils/sem.c b/Kernel/utils/sem.c index deb00f8..f6b6e42 100644 --- a/Kernel/utils/sem.c +++ b/Kernel/utils/sem.c @@ -3,20 +3,20 @@ static uint32_t semLock; typedef struct node_t { - sem_t * sem; - struct node_t * next; + sem_t *sem; + struct node_t *next; } node_t; -node_t * firstSem = NULL; +node_t *firstSem = NULL; static char counter = 0; -sem_t * semOpen(char * name, unsigned int value) { +sem_t *semOpen(char *name, unsigned int value) { enter_region(&semLock); - - sem_t * sem = pvPortMalloc(sizeof(sem_t)); - node_t * node = pvPortMalloc(sizeof(node_t)); + + sem_t *sem = pvPortMalloc(sizeof(sem_t)); + node_t *node = pvPortMalloc(sizeof(node_t)); node->sem = sem; - node->next = firstSem; + node->next = firstSem; firstSem = node; sem->name = pvPortMalloc(MAX_NAME); strcpy(sem->name, name); @@ -28,27 +28,27 @@ sem_t * semOpen(char * name, unsigned int value) { return sem; } -char semClose(sem_t * sem) { +char semClose(sem_t *sem) { if (sem == NULL) return EXIT_FAILURE; enter_region(&semLock); - node_t * del = NULL; + node_t *del = NULL; if (firstSem->sem == sem) { del = firstSem; firstSem = firstSem->next; - } - else { - node_t * aux = firstSem; + } else { + node_t *aux = firstSem; while (aux != NULL) { - if (aux->next != NULL) + if (aux->next != NULL) { if (aux->next->sem == sem) { del = aux->next; aux->next = aux->next->next; break; } + } aux = aux->next; } } @@ -58,32 +58,31 @@ char semClose(sem_t * sem) { return EXIT_FAILURE; } - pid_t * pid = sem->entering; + pid_t *pid = sem->entering; while (pid != NULL) { - pid_t * aux = pid; + pid_t *aux = pid; pid = pid->next; vPortFree(aux); } vPortFree(sem->name); vPortFree(sem); vPortFree(del); - + counter--; leave_region(&semLock); return EXIT_SUCCESS; } -void semWait(sem_t * sem) { +void semWait(sem_t *sem) { enter_region(&semLock); if (sem->value > 0) { sem->value--; - } - else { + } else { leave_region(&semLock); - pid_t * curr = pvPortMalloc(sizeof(pid_t)); + pid_t *curr = pvPortMalloc(sizeof(pid_t)); curr->pid = getPid(); curr->next = NULL; if (sem->entering == NULL) @@ -100,13 +99,13 @@ void semWait(sem_t * sem) { leave_region(&semLock); } -void semPost(sem_t * sem) { +void semPost(sem_t *sem) { enter_region(&semLock); sem->value++; if (sem->entering != NULL) { - pid_t * aux = sem->entering; + pid_t *aux = sem->entering; sem->entering = sem->entering->next; if (sem->entering == NULL) sem->last = NULL; @@ -117,7 +116,7 @@ void semPost(sem_t * sem) { leave_region(&semLock); } -char getSemaphoresData(char * out, node_t * node) { +char getSemaphoresData(char *out, node_t *node) { if (node == NULL) return EXIT_FAILURE; @@ -136,7 +135,7 @@ char getSemaphoresData(char * out, node_t * node) { out += addSpaces(out, 2); written += 2; - + char buffer[10]; char copied = strcpy(out, itoa(node->sem->value, buffer, 10, 2)); out += copied; @@ -146,7 +145,7 @@ char getSemaphoresData(char * out, node_t * node) { written += 2; pid_t *aux_pid = node->sem->entering; - + while (aux_pid != NULL) { copied = strcpy(out, itoa(aux_pid->pid, buffer, 10, 10)); aux_pid = aux_pid->next; @@ -157,11 +156,9 @@ char getSemaphoresData(char * out, node_t * node) { return written; } -#define MAX_PID 4 - -char * getEntering(sem_t * sem){ - char * ans = pvPortMalloc(sizeof(pid_t *)); - pid_t * aux = sem->entering; +char *getEntering(sem_t *sem) { + char *ans = pvPortMalloc(sizeof(pid_t * )); + pid_t *aux = sem->entering; char buffer[MAX_PID]; while (aux != NULL) { strcpy(ans, itoa(aux->pid, buffer, 10, 3)); @@ -172,14 +169,14 @@ char * getEntering(sem_t * sem){ return ans; } -char * getSems() { - char * ans = pvPortMalloc(counter * SEM_DATA_MAX_SIZE); - char * ret = ans; - - char * info = "name value pidsWaiting\n"; +char *getSems() { + char *ans = pvPortMalloc(counter * SEM_DATA_MAX_SIZE); + char *ret = ans; + + char *info = "name value pidsWaiting\n"; ans += strcpy(ans, info); - node_t * aux = firstSem; + node_t *aux = firstSem; while (aux != NULL) { char writtenChars = getSemaphoresData(ans, aux); if (writtenChars == EXIT_FAILURE) diff --git a/Userland/SampleCodeModule/Makefile b/Userland/SampleCodeModule/Makefile index ead40ab..4ae6163 100644 --- a/Userland/SampleCodeModule/Makefile +++ b/Userland/SampleCodeModule/Makefile @@ -1,58 +1,37 @@ -include ../Makefile.inc - -MODULE=0000-sampleCodeModule.bin -MODULE_ELF=0000-sampleCodeModule.elf -SOURCES=$(wildcard *.c) -SOURCES_SHELL=$(wildcard shell/*.c) -SOURCES_ASM=$(wildcard asm/*.asm) -SOURCES_PROMPT=$(wildcard shell/commands/*.c) -SOURCES_BOTTLER=$(wildcard bottler/*.c) -OBJECTS=$(SOURCES:.c=.o) -OBJECTS_SHELL=$(SOURCES_SHELL:.c=.o) -OBJECTS_PROMPT=$(SOURCES_PROMPT:.c=.o) -OBJECTS_BOTTLER=$(SOURCES_BOTTLER:.c=.o) -OBJECTS_ASM=$(SOURCES_ASM:.asm=.o) - -ALL_OBJECTS= $(OBJECTS) $(OBJECTS_ASM) $(OBJECTS_SHELL) $(OBJECTS_COMMANDS) $(OBJECTS_PROMPT) $(OBJECTS_BOTTLER) - -STATICLIBS= - -all: $(MODULE) $(MODULE_ELF) #shellModule - -#shellModule: -# cd shell; make - -$(MODULE): $(STATICLIBS) $(ALL_OBJECTS) - $(LD) $(LDFLAGS) -T sampleCodeModule.ld $(OBJECTS) $(OBJECTS_SHELL) $(OBJECTS_ASM) $(OBJECTS_PROMPT) $(OBJECTS_BOTTLER) -o ../$(MODULE) - -$(MODULE_ELF): $(STATICLIBS) $(ALL_OBJECTS) - $(LD) $(LDFLAGS) -I./include -I./shell/include -I./bottler/include -T sampleCodeModule.ld --oformat=elf64-x86-64 $(OBJECTS) $(OBJECTS_SHELL) $(OBJECTS_ASM) $(OBJECTS_PROMPT) $(OBJECTS_BOTTLER) -o ../$(MODULE_ELF) - -%.o:%.c - $(GCC) $(GCCFLAGS) -T _loader.c -I./include -I./shell/include -I./bottler/include -c $< -o $@ - -%.o:%.asm - $(ASM) $(ASMFLAGS) $< -o $@ - -clean: -# cd shell; make clean - rm -rf *.o - cd shell; rm -rf *.o - cd shell/commands; rm -rf *.o - -.PHONY: all clean print - -# include ../Makefile.inc - -# MODULE=0000-sampleCodeModule.bin -# SOURCES=$(wildcard [^_]*.c) - -# all: $(MODULE) - -# $(MODULE): $(SOURCES) -# $(GCC) $(GCCFLAGS) -T sampleCodeModule.ld _loader.c $(SOURCES) -I./include -o ../$(MODULE) - -# clean: -# rm -rf *.o - -# .PHONY: all clean print +include ../Makefile.inc + +MODULE=0000-sampleCodeModule.bin +MODULE_ELF=0000-sampleCodeModule.elf +SOURCES=$(wildcard *.c) +SOURCES_SHELL=$(wildcard shell/*.c) +SOURCES_ASM=$(wildcard asm/*.asm) +SOURCES_PROMPT=$(wildcard shell/commands/*.c) +SOURCES_BOTTLER=$(wildcard bottler/*.c) +OBJECTS=$(SOURCES:.c=.o) +OBJECTS_SHELL=$(SOURCES_SHELL:.c=.o) +OBJECTS_PROMPT=$(SOURCES_PROMPT:.c=.o) +OBJECTS_BOTTLER=$(SOURCES_BOTTLER:.c=.o) +OBJECTS_ASM=$(SOURCES_ASM:.asm=.o) + +ALL_OBJECTS= $(OBJECTS) $(OBJECTS_ASM) $(OBJECTS_SHELL) $(OBJECTS_COMMANDS) $(OBJECTS_PROMPT) $(OBJECTS_BOTTLER) + +STATICLIBS= + +all: $(MODULE) $(MODULE_ELF) + +$(MODULE): $(STATICLIBS) $(ALL_OBJECTS) + $(LD) $(LDFLAGS) -T sampleCodeModule.ld $(OBJECTS) $(OBJECTS_SHELL) $(OBJECTS_ASM) $(OBJECTS_PROMPT) $(OBJECTS_BOTTLER) -o ../$(MODULE) + +$(MODULE_ELF): $(STATICLIBS) $(ALL_OBJECTS) + $(LD) $(LDFLAGS) -I./include -I./shell/include -I./bottler/include -T sampleCodeModule.ld --oformat=elf64-x86-64 $(OBJECTS) $(OBJECTS_SHELL) $(OBJECTS_ASM) $(OBJECTS_PROMPT) $(OBJECTS_BOTTLER) -o ../$(MODULE_ELF) + +%.o:%.c + $(GCC) $(GCCFLAGS) -T _loader.c -I./include -I./shell/include -I./bottler/include -c $< -o $@ + +%.o:%.asm + $(ASM) $(ASMFLAGS) $< -o $@ + +clean: + rm -rf $(ALL_OBJECTS) + +.PHONY: all clean print \ No newline at end of file diff --git a/Userland/SampleCodeModule/_loader.c b/Userland/SampleCodeModule/_loader.c index 8c9752d..1a0c89d 100644 --- a/Userland/SampleCodeModule/_loader.c +++ b/Userland/SampleCodeModule/_loader.c @@ -1,4 +1,3 @@ -/* _loader.c */ #include extern char bss; @@ -6,22 +5,20 @@ extern char endOfBinary; int main(int argc, char *argv[]); -void * memset(void * destiny, int32_t c, uint64_t length); +void *memset(void *destiny, int32_t c, uint64_t length); int _start(int argc, char *argv[]) { - //Clean BSS - memset(&bss, 0, &endOfBinary - &bss); + memset(&bss, 0, &endOfBinary - &bss); - return main(argc, argv); + return main(argc, argv); } +void *memset(void *destination, int32_t c, uint64_t length) { + uint8_t chr = (uint8_t) c; + char *dst = (char *) destination; -void * memset(void * destination, int32_t c, uint64_t length) { - uint8_t chr = (uint8_t)c; - char * dst = (char*)destination; + while (length--) + dst[length] = chr; - while(length--) - dst[length] = chr; - - return destination; + return destination; } diff --git a/Userland/SampleCodeModule/bottler/bottler.c b/Userland/SampleCodeModule/bottler/bottler.c index c636651..fa99336 100644 --- a/Userland/SampleCodeModule/bottler/bottler.c +++ b/Userland/SampleCodeModule/bottler/bottler.c @@ -1,41 +1,66 @@ #include "bottler.h" -void bottler(int argc, char ** argv) { - printStringLen(" ", 80); new_line(); - printStringLen(" (%( ", 80); new_line(); - printStringLen( " Welcome to", 17); - printStringLen(" %%%%% ", 80); new_line(); - printStringLen( " BottlerOS", 18); - printStringLen(" %%% ", 80); new_line(); - printStringLen( " %%%%%%%%%%%%% ", 80); new_line(); - printStringLen( " %%%%%%%%%%%%%%%%%%%%% ", 80); new_line(); - printStringLen( " %%%%%%% %%%%%%% ", 80); new_line(); - printStringLen( " %%%%% %%%%% ", 80); new_line(); - printStringLen( " %%%%% %%%%% ", 80); new_line(); - printStringLen( " %%%%% ", 27); - printStringLen( " %%%% %%%% ", 22); - printStringLen( " %%%%% ", 30); new_line(); - printStringLen( " %%%%% ", 28); - printStringLen( " (% %( ", 21); - printStringLen( " %%%%% ", 30); new_line(); - printStringLen( " %%%%%%% %%%%%%% ", 80); new_line(); - printStringLen(" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); new_line(); - printStringLen(" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); new_line(); - printStringLen(" %%%%%%%%%%%%%%%%%%%%%%% ", 41); - printStringLen( " % %* ", 8); - printStringLen(" %%%%%%%%% ", 30); new_line(); - printStringLen(" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); new_line(); - printStringLen(" %%**%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/%% ", 80); new_line(); - printStringLen(" %%* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% /%% ", 80); new_line(); - printStringLen(" %%* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% /%% ", 80); new_line(); - printStringLen(" %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% ", 80); new_line(); - printStringLen( " ,%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%. ", 80); new_line(); - printStringLen( " %%. %%%%%%%%%%%%%%%%% .%% ", 80); new_line(); - printStringLen( " %%%%%%%%%%%%% ", 80); new_line(); - printStringLen( " %%%%%%% ", 80); new_line(); - printStringLen( " ", 80); new_line(); - sys_sleep(3); - - winClear(); +void bottler(int argc, char **argv) { + printStringLen(" ", 80); + new_line(); + printStringLen(" (%( ", 80); + new_line(); + printStringLen(" Welcome to", 17); + printStringLen(" %%%%% ", 80); + new_line(); + printStringLen(" BottlerOS", 18); + printStringLen(" %%% ", 80); + new_line(); + printStringLen(" %%%%%%%%%%%%% ", 80); + new_line(); + printStringLen(" %%%%%%%%%%%%%%%%%%%%% ", 80); + new_line(); + printStringLen(" %%%%%%% %%%%%%% ", 80); + new_line(); + printStringLen(" %%%%% %%%%% ", 80); + new_line(); + printStringLen(" %%%%% %%%%% ", 80); + new_line(); + printStringLen(" %%%%% ", 27); + printStringLen(" %%%% %%%% ", 22); + printStringLen(" %%%%% ", 30); + new_line(); + printStringLen(" %%%%% ", 28); + printStringLen(" (% %( ", 21); + printStringLen(" %%%%% ", 30); + new_line(); + printStringLen(" %%%%%%% %%%%%%% ", 80); + new_line(); + printStringLen(" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); + new_line(); + printStringLen(" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); + new_line(); + printStringLen(" %%%%%%%%%%%%%%%%%%%%%%% ", 41); + printStringLen(" % %* ", 8); + printStringLen(" %%%%%%%%% ", 30); + new_line(); + printStringLen(" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ", 80); + new_line(); + printStringLen(" %%**%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/%% ", 80); + new_line(); + printStringLen(" %%* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% /%% ", 80); + new_line(); + printStringLen(" %%* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% /%% ", 80); + new_line(); + printStringLen(" %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% ", 80); + new_line(); + printStringLen(" ,%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%. ", 80); + new_line(); + printStringLen(" %%. %%%%%%%%%%%%%%%%% .%% ", 80); + new_line(); + printStringLen(" %%%%%%%%%%%%% ", 80); + new_line(); + printStringLen(" %%%%%%% ", 80); + new_line(); + printStringLen(" ", 80); + new_line(); + sys_sleep(3); + + winClear(); sys_exit(); } \ No newline at end of file diff --git a/Userland/SampleCodeModule/include/system.h b/Userland/SampleCodeModule/include/system.h index 2889aeb..0eb036c 100644 --- a/Userland/SampleCodeModule/include/system.h +++ b/Userland/SampleCodeModule/include/system.h @@ -8,13 +8,11 @@ typedef struct pid_t { typedef struct sem_t { unsigned int value; - // char name[MAX_NAME]; char * name; pid_t * entering; pid_t * last; } sem_t; -// void sys_switchContext(); int sys_loadProcess(void (*fn) (int, char **), char foreground, int argc, char *argv[], int * fd); int sys_time(char); void sys_exit(); @@ -27,10 +25,8 @@ void * sys_free(void *); void * sys_openPipe(int *, char *); char sys_nice(int, char); void sys_sleep(int); -// void sys_semWait(void *); void sys_semWait(sem_t *); void sys_semPost(sem_t *); -// void * sys_semOpen(char *, unsigned int); sem_t * sys_semOpen(char *, unsigned int); int sys_getPid(); char sys_semClose(void *); diff --git a/Userland/SampleCodeModule/libc.c b/Userland/SampleCodeModule/libc.c index f274097..10ea8bd 100644 --- a/Userland/SampleCodeModule/libc.c +++ b/Userland/SampleCodeModule/libc.c @@ -1,43 +1,43 @@ #include "libc.h" -void printString(char * string) { +void printString(char *string) { int len = strlen(string); sys_write(1, string, len); } -void printStringLen(char * string, int len) { +void printStringLen(char *string, int len) { sys_write(1, string, len); } -void printStringError(char * string) { +void printStringError(char *string) { int len = strlen(string); sys_write(2, string, len); } -int strlen(const char * s) { +int strlen(const char *s) { int i = 0; for (i = 0; s[i] != '\0'; i++); return i; } -int strcmp(const char * s1, const char * s2) { - while(*s1 && (*s1 == *s2)) { +int strcmp(const char *s1, const char *s2) { + while (*s1 && (*s1 == *s2)) { s1++; s2++; } return *s1 - *s2; } -char * strcat(char * dest, const char * src) { - char * rdest = dest; +char *strcat(char *dest, const char *src) { + char *rdest = dest; while (*dest) - dest++; + dest++; while ((*dest++ = *src++)); return rdest; } -void putChar(char c){ +void putChar(char c) { char buffer = c; sys_write(1, &buffer, 0); } @@ -54,33 +54,32 @@ void winClear() { sys_write(1, "\e\f", 2); } -int strcpy(char * strDest, const char * strSrc) { - int i = 0; +int strcpy(char *strDest, const char *strSrc) { + int i = 0; while ((*strDest++ = *strSrc++)) { - i++; - } + i++; + } return i; } -char* gtoa(int value, char* buffer, int base, int length) { - if (base < 2 || base > 32) { +char *gtoa(int value, char *buffer, int base, int length) { + if (base < 2 || base > 32) { return buffer; } - + int n = abs(value); - + int i = 0; while (n && i < length) { int r = n % base; if (r >= 10) { buffer[i++] = 65 + (r - 10); - } - else { + } else { buffer[i++] = 48 + r; } n = n / base; } - + if (i == 0) { buffer[i++] = '0'; } @@ -88,9 +87,9 @@ char* gtoa(int value, char* buffer, int base, int length) { if (value < 0 && base == 10) { buffer[i++] = '-'; } - + buffer[i] = '\0'; - + return reverse(buffer, 0, i - 1); } @@ -102,61 +101,54 @@ char getChar() { } void swap(char *x, char *y) { - char t = *x; *x = *y; *y = t; + char t = *x; + *x = *y; + *y = t; } - -char* reverse(char *buffer, int i, int j) { + +char *reverse(char *buffer, int i, int j) { while (i < j) { swap(&buffer[i++], &buffer[j--]); } - + return buffer; } int abs(int value) { return value < 0 ? -value : value; } - -char* itoa(int value, char* buffer, int base) { - if (base < 2 || base > 32) { + +char *itoa(int value, char *buffer, int base) { + if (base < 2 || base > 32) { return buffer; } - + int n = abs(value); - + int i = 0; while (n) { int r = n % base; if (r >= 10) { buffer[i++] = 65 + (r - 10); - } - else { + } else { buffer[i++] = 48 + r; } n = n / base; } - + if (i == 0) { buffer[i++] = '0'; } - + if (value < 0 && base == 10) { buffer[i++] = '-'; } - + buffer[i] = '\0'; - + return reverse(buffer, 0, i - 1); } -// int atoi(char * string, int length) { -// int res = 0, i = 0; -// while (string[i] != 0 && i < length) { -// res = res * 10 + string[i++] - '0'; -// } -// return res; -// } - int atoi(char *str, int length) { int i = 0, sign = 1, val = 0, nbr = 0; while (str[i] != '\0') { @@ -177,14 +169,14 @@ int atoi(char *str, int length) { } int pow(int base, int exponent) { - int result = 1; - for (; exponent > 0; exponent--) { - result = result * base; - } - return result; + int result = 1; + for (; exponent > 0; exponent--) { + result = result * base; + } + return result; } -char isFloat(char * str) { +char isFloat(char *str) { int dot = 0; if (*str == '-') str++; @@ -201,9 +193,9 @@ char isFloat(char * str) { float atof(char *arr) { float val = 0; - int afterdot=0; - float scale=1; - int neg = 0; + int afterdot = 0; + float scale = 1; + int neg = 0; if (*arr == '-') { arr++; @@ -211,21 +203,21 @@ float atof(char *arr) { } while (*arr) { if (afterdot) { - scale = scale/10; - val = val + (*arr-'0')*scale; + scale = scale / 10; + val = val + (*arr - '0') * scale; } else { - if (*arr == '.') + if (*arr == '.') afterdot++; else val = val * 10.0 + (*arr - '0'); } arr++; } - if(neg) return -val; - else return val; + if (neg) return -val; + else return val; } -char * strstrip(char * s, char c) { +char *strstrip(char *s, char c) { while (*s != 0) { if (*s != c) break; @@ -234,20 +226,19 @@ char * strstrip(char * s, char c) { return s; } -char *strtok(char * s, char delim) { +char *strtok(char *s, char delim) { char *ptr = s; if (s == 0) { return 0; } - + int flag = 0; while (*ptr != 0) { if (*ptr == delim) { flag = 1; *ptr = 0; - } - else if (flag == 1) + } else if (flag == 1) return ptr; ptr++; } @@ -260,84 +251,84 @@ char isNumber(char c) { // Tomada y modificada de https://github.com/antongus/stm32tpl/blob/master/ftoa.c -#define MAX_PRECISION (10) +#define MAX_PRECISION (10) static const double rounders[MAX_PRECISION + 1] = -{ - 0.5, // 0 - 0.05, // 1 - 0.005, // 2 - 0.0005, // 3 - 0.00005, // 4 - 0.000005, // 5 - 0.0000005, // 6 - 0.00000005, // 7 - 0.000000005, // 8 - 0.0000000005, // 9 - 0.00000000005 // 10 -}; + { + 0.5, // 0 + 0.05, // 1 + 0.005, // 2 + 0.0005, // 3 + 0.00005, // 4 + 0.000005, // 5 + 0.0000005, // 6 + 0.00000005, // 7 + 0.000000005, // 8 + 0.0000000005, // 9 + 0.00000000005 // 10 + }; -void ftoa(double f, char * buf, int precision) { - char * ptr = buf; - char * p = ptr; - char * p1; - char c; - long intPart; +void ftoa(double f, char *buf, int precision) { + char *ptr = buf; + char *p = ptr; + char *p1; + char c; + long intPart; - if (precision > MAX_PRECISION) - precision = MAX_PRECISION; + if (precision > MAX_PRECISION) + precision = MAX_PRECISION; - if (f < 0) { - f = -f; - *ptr++ = '-'; - } + if (f < 0) { + f = -f; + *ptr++ = '-'; + } - if (precision < 0) { - if (f < 1.0) precision = 6; - else if (f < 10.0) precision = 5; - else if (f < 100.0) precision = 4; - else if (f < 1000.0) precision = 3; - else if (f < 10000.0) precision = 2; - else if (f < 100000.0) precision = 1; - else precision = 0; - } + if (precision < 0) { + if (f < 1.0) precision = 6; + else if (f < 10.0) precision = 5; + else if (f < 100.0) precision = 4; + else if (f < 1000.0) precision = 3; + else if (f < 10000.0) precision = 2; + else if (f < 100000.0) precision = 1; + else precision = 0; + } - if (precision) - f += rounders[precision]; + if (precision) + f += rounders[precision]; - intPart = f; - f -= intPart; + intPart = f; + f -= intPart; - if (!intPart) - *ptr++ = '0'; - else { - p = ptr; + if (!intPart) + *ptr++ = '0'; + else { + p = ptr; - while (intPart) { - *p++ = '0' + intPart % 10; - intPart /= 10; - } + while (intPart) { + *p++ = '0' + intPart % 10; + intPart /= 10; + } - p1 = p; + p1 = p; - while (p > ptr) { - c = *--p; - *p = *ptr; - *ptr++ = c; - } + while (p > ptr) { + c = *--p; + *p = *ptr; + *ptr++ = c; + } - ptr = p1; - } + ptr = p1; + } - if (precision && ((int) (f * pow(10, precision))) != 0) { - *ptr++ = '.'; + if (precision && ((int) (f * pow(10, precision))) != 0) { + *ptr++ = '.'; - while (precision-- && ((int) (f * pow(10, precision))) != 0) { - f *= 10.0; - c = f; - *ptr++ = '0' + c; - f -= c; - } - } + while (precision-- && ((int) (f * pow(10, precision))) != 0) { + f *= 10.0; + c = f; + *ptr++ = '0' + c; + f -= c; + } + } - *ptr = 0; + *ptr = 0; } \ No newline at end of file diff --git a/Userland/SampleCodeModule/sampleCodeModule.c b/Userland/SampleCodeModule/sampleCodeModule.c index 1ae0651..b65c822 100644 --- a/Userland/SampleCodeModule/sampleCodeModule.c +++ b/Userland/SampleCodeModule/sampleCodeModule.c @@ -1,22 +1,19 @@ -/* sampleCodeModule.c */ #include "libc.h" #include "shell/include/shell.h" #include "bottler/include/bottler.h" #include - -int sys_loadProcess(void (*fn) (int, char **), char foreground, int argc, char *argv[], int * fd); -void sys_exit(); +#include "system.h" int main(int argc, char *argv[]) { winClear(); - char * argv1[] = {"bottler"}; + char *argv1[] = {"bottler"}; sys_loadProcess(bottler, 1, 1, argv1, NULL); sys_wait(); - char * argv2[] = {"shell"}; + char *argv2[] = {"shell"}; sys_loadProcess(shell, 1, 1, argv2, NULL); sys_exit(); - return 1; + return 1; } diff --git a/Userland/SampleCodeModule/shell/Makefile b/Userland/SampleCodeModule/shell/Makefile deleted file mode 100644 index 968eac3..0000000 --- a/Userland/SampleCodeModule/shell/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# include ../../Makefile.inc - -# SOURCES=$(wildcard *.c) -# SOURCES_COMMANDS=$(wildcard prompt_commands/*.c) -# OBJECTS=$(SOURCES:.c=.o) -# OBJECTS_COMMANDS=$(SOURCES_COMMANDS:.c=.o) - -# ALL_OBJECTS= $(OBJECTS) $(OBJECTS_COMMANDS) - -# STATICLIBS= - -# all: $(OBJECTS) - -# %.o:%.c -# $(GCC) $(GCCFLAGS) -I./include -c $< -o $@ - -# clean: -# rm -rf *.o - -# .PHONY: all clean print \ No newline at end of file diff --git a/Userland/SampleCodeModule/shell/shell.c b/Userland/SampleCodeModule/shell/shell.c index 8684256..663c6e0 100644 --- a/Userland/SampleCodeModule/shell/shell.c +++ b/Userland/SampleCodeModule/shell/shell.c @@ -1,32 +1,32 @@ #include "shell.h" cmd_t commands[] = { - { "help", help, 0, 1}, - { "cat", cat, 0, 1}, - { "time", time, 0, 1}, - { "block", block, 1, 1}, - { "unblock", unblock, 1, 1}, - { "inforeg", inforeg, 0, 1}, - { "excdiv", excdiv, 1, 1}, - { "excop", excop, 1, 1}, - { "filter", filter, 0, 1}, - { "clear", clear, 1, 1}, - { "cpufeatures", cpufeatures, 0, 1}, - { "nice", nice, 0, 1}, - { "ps", ps, 0, 1}, - { "pipes", pipes, 0, 1}, - { "kill", kill, 1, 1}, - { "sem", sem, 0, 1}, - { "quadratic", quadratic, 0, 1}, - { "printmem", printmem, 0, 1}, - { "phylo", phylo, 0, 1}, - { "wc", wc, 0, 1}, - { "loop", loop, 0, 0}, - { "loopcaca", loop, 0, 1}, - { NULL, NULL, 0, 0} + {"help", help, 0, 1}, + {"cat", cat, 0, 1}, + {"time", time, 0, 1}, + {"block", block, 1, 1}, + {"unblock", unblock, 1, 1}, + {"inforeg", inforeg, 0, 1}, + {"excdiv", excdiv, 1, 1}, + {"excop", excop, 1, 1}, + {"filter", filter, 0, 1}, + {"clear", clear, 1, 1}, + {"cpufeatures", cpufeatures, 0, 1}, + {"nice", nice, 0, 1}, + {"ps", ps, 0, 1}, + {"pipes", pipes, 0, 1}, + {"kill", kill, 1, 1}, + {"sem", sem, 0, 1}, + {"quadratic", quadratic, 0, 1}, + {"printmem", printmem, 0, 1}, + {"phylo", phylo, 0, 1}, + {"wc", wc, 0, 1}, + {"loop", loop, 0, 0}, + {"loopcaca", loop, 0, 1}, + {NULL, NULL, 0, 0} }; -int scanfNoPrint(char * buffer) { +int scanfNoPrint(char *buffer) { char c; int i = 0; while ((c = getChar()) != '\n' && i < SIZE - 1) { @@ -34,8 +34,7 @@ int scanfNoPrint(char * buffer) { if (c == '\b' && i > 0) { buffer[--i] = ' '; backspace(); - } - else if (c != 0 && c != '\b') { + } else if (c != 0 && c != '\b') { buffer[i++] = c; putChar(c); } @@ -45,9 +44,9 @@ int scanfNoPrint(char * buffer) { return i; } -void processInput(char * input) { +void processInput(char *input) { int comm_flag0 = 0, comm_flag1 = 0, pipe = -1, end = -1, ampersand = -1; - char* tokens[SIZE] = {0}; + char *tokens[SIZE] = {0}; tokens[0] = strstrip(input, ' '); for (int i = 1; i < MAX_ARGS; i++) { tokens[i] = strtok(tokens[i - 1], ' '); @@ -56,7 +55,7 @@ void processInput(char * input) { pipe = i - 1; } if (tokens[i][0] == 0) { - if (i > 1 && !strcmp(tokens[i-1], "&")) { + if (i > 1 && !strcmp(tokens[i - 1], "&")) { ampersand = end = i - 1; break; } @@ -70,7 +69,7 @@ void processInput(char * input) { return; } - int * fd, * fd1, * fd2; + int *fd, *fd1, *fd2; fd1 = sys_malloc(2 * sizeof(int)); fd1[0] = 0; fd1[1] = 1; @@ -86,8 +85,8 @@ void processInput(char * input) { fd2[0] = fd[0]; fd2[1] = 1; } - char ** argv0 = NULL; - char ** argv1 = NULL; + char **argv0 = NULL; + char **argv1 = NULL; int comm0 = -1; int comm1 = -1; @@ -98,8 +97,7 @@ void processInput(char * input) { argv1 = sys_malloc(sizeof(char *) * (end - pipe - 1)); for (int i = pipe + 1; i < end; i++) argv1[i - pipe - 1] = tokens[i]; - } - else { + } else { argv0 = sys_malloc(sizeof(char *) * end); for (int i = 0; i < end; i++) argv0[i] = tokens[i]; @@ -125,8 +123,7 @@ void processInput(char * input) { if (pipe != -1) { sys_loadProcess(commands[comm0].func, commands[comm0].isForeground, pipe, argv0, fd1); sys_loadProcess(commands[comm1].func, commands[comm0].isForeground, end - pipe - 1, argv1, fd2); - } - else { + } else { if (commands[comm0].isBuiltIn) commands[comm0].func(end, argv0); else { @@ -143,8 +140,7 @@ void processInput(char * input) { if (!comm_flag0) { if (*tokens[0] != 0) incorrect_comm(tokens[0]); - } - else if (!comm_flag1 && pipe != -1) { + } else if (!comm_flag1 && pipe != -1) { if (*tokens[pipe + 1] != 0) incorrect_comm(tokens[pipe + 1]); } @@ -154,21 +150,19 @@ void shell(int argc, char *argv[]) { printStringLen("$> ", 3); char buffer[SIZE] = {0}; - // while (1) { while (scanfNoPrint(buffer) != 0) { new_line(); processInput(buffer); printStringLen("$> ", 3); } - // } } -void incorrect_comm(char * buffer) { +void incorrect_comm(char *buffer) { printString(buffer); printStringLen(" is not a BottlerShell command\n", 32); } -void incorrect_arg(char * command) { +void incorrect_arg(char *command) { printStringLen("Incorrect arguments for command ", 33); printString(command); new_line();