shithub: scc

Download patch

ref: 3c7144d5d343692883589bedf327c4e3244d9f29
parent: e09ad0442d5af5784989e81a81b390bed5295d13
author: Roberto E. Vargas Caballero <[email protected]>
date: Fri Jun 29 09:43:46 EDT 2012

Added wrapper.c

This module has all the wrappers about usual system functions like malloc or
strdup, doing that caller can be sure that returned value is correct.

--- a/Makefile
+++ b/Makefile
@@ -1,5 +1,6 @@
 
-OBJS = types.o decl.o lex.o error.o symbol.o flow.o main.o expr.o keyword.o code.o
+OBJS = types.o decl.o lex.o error.o symbol.o flow.o main.o expr.o keyword.o \
+	code.o wrapper.o
 LIBS =
 
 all: kcc
--- a/cc.h
+++ b/cc.h
@@ -20,4 +20,7 @@
 extern void error(const char *fmt, ...);
 extern void die(const char *fmt, ...);
 extern void warning_error(char flag, const char *fmt, ...);
+extern void *xmalloc(size_t size);
+extern void *xcalloc(size_t nmemb, size_t size);
+extern char *xstrdup(const char *s);
 #endif
--- a/symbol.c
+++ b/symbol.c
@@ -5,8 +5,6 @@
 #include "cc.h"
 #include "symbol.h"
 
-#define xmalloc malloc
-#define xstrdup strdup
 #define NR_SYM_HASH 32
 
 struct symhash {
--- a/types.c
+++ b/types.c
@@ -7,9 +7,6 @@
 #include "tokens.h"
 #include "symbol.h"
 
-/* TODO: create wrapper file */
-#define xcalloc calloc
-
 struct type tschar = {.btype = CHAR};
 struct type tshort = {.btype = SHORT};
 struct type tint = {.btype = INT};
--- /dev/null
+++ b/wrapper.c
@@ -1,0 +1,37 @@
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "cc.h"
+
+
+static void out_of_memory(void)
+{
+	/* TODO: deal with out of memory errors */
+	error("out of memory");
+}
+
+void *xmalloc(size_t size)
+{
+	register void *p = malloc(size);
+
+	if (!p)
+		out_of_memory();
+	return p;
+}
+
+void *xcalloc(size_t nmemb, size_t size)
+{
+	register size_t nbytes = nmemb * size;
+	register void *p = xmalloc(nbytes);
+
+	return memset(p, nbytes, 0);
+}
+
+char *xstrdup(const char *s)
+{
+	register size_t len = strlen(s);
+	register char *p = xmalloc(len);
+
+	return memcpy(p, s, len);
+}