* AcessOS Basic C Library\r
* stdlib.c\r
*/\r
-/**\r
- * \todo Move half of these to stdio\r
- */\r
#include <acess/sys.h>\r
#include <stdlib.h>\r
#include <stdio.h>\r
#include "lib.h"\r
\r
-#define _stdout 1\r
-#define _stdin 0\r
+extern void _stdio_cleanup(void);\r
+\r
+#define MAX_ATEXIT_HANDLERS 64 // Standard defines >=32\r
\r
// === PROTOTYPES ===\r
EXPORT int atoi(const char *str);\r
EXPORT void exit(int status);\r
\r
+// === GLOBALS ===\r
+typedef void (*stdlib_exithandler_t)(void);\r
+stdlib_exithandler_t g_stdlib_exithandlers[MAX_ATEXIT_HANDLERS];\r
+ int g_stdlib_num_exithandlers;\r
+\r
// === CODE ===\r
+void _call_atexit_handlers(void)\r
+{\r
+ int i;\r
+ for( i = g_stdlib_num_exithandlers; i --; )\r
+ g_stdlib_exithandlers[i]();\r
+ _stdio_cleanup();\r
+}\r
+\r
+EXPORT void atexit(void (*__func)(void))\r
+{\r
+ if( g_stdlib_num_exithandlers < MAX_ATEXIT_HANDLERS )\r
+ {\r
+ g_stdlib_exithandlers[g_stdlib_num_exithandlers++] = __func;\r
+ }\r
+}\r
+\r
/**\r
* \fn EXPORT void exit(int status)\r
* \brief Exit\r
*/\r
EXPORT void exit(int status)\r
{\r
+ _call_atexit_handlers();\r
_exit(status);\r
}\r
\r
*/\r
EXPORT void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *))\r
{\r
- int i, j, min;\r
+ size_t i, j, min;\r
+ // With 0 items, there's nothing to do and with 1 its already sorted\r
+ if(nmemb == 0 || nmemb == 1) return;\r
+ \r
+ // SORT!\r
for( i = 0; i < (nmemb-1); i++ )\r
{\r
min = i;\r
}\r
}\r
\r
-/**\r
- * \fn EXPORT int atoi(const char *str)\r
- * \brief Convert a string to an integer\r
- */\r
-EXPORT int atoi(const char *str)\r
-{\r
- int neg = 0;\r
- int ret = 0;\r
- \r
- // NULL Check\r
- if(!str) return 0;\r
- \r
- while(*str == ' ' || *str == '\t') str++;\r
- \r
- // Check for negative\r
- if(*str == '-') {\r
- neg = 1;\r
- str++;\r
- }\r
- \r
- if(*str == '0') {\r
- str ++;\r
- if(*str == 'x') {\r
- str++;\r
- // Hex\r
- while( ('0' <= *str && *str <= '9')\r
- || ('A' <= *str && *str <= 'F' )\r
- || ('a' <= *str && *str <= 'f' )\r
- )\r
- {\r
- ret *= 16;\r
- if(*str <= '9') {\r
- ret += *str - '0';\r
- } else if (*str <= 'F') {\r
- ret += *str - 'A' + 10;\r
- } else {\r
- ret += *str - 'a' + 10;\r
- }\r
- str++;\r
- }\r
- } else {\r
- // Octal\r
- while( '0' <= *str && *str <= '7' )\r
- {\r
- ret *= 8;\r
- ret += *str - '0';\r
- str++;\r
- }\r
- }\r
- } else {\r
- // Decimal\r
- while( '0' <= *str && *str <= '9' )\r
- {\r
- ret *= 10;\r
- ret += *str - '0';\r
- str++;\r
- }\r
- }\r
- \r
- // Negate if needed\r
- if(neg) ret = -ret;\r
- return ret;\r
-}\r
+\r
+int abs(int j) { return j < 0 ? -j : j; }\r
+long int labs(long int j) { return j < 0 ? -j : j; }\r
+\r