CSc/Debug.c
changeset 0 5c129dd80d4f
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/CSc/Debug.c	Thu Nov 21 14:55:10 2019 +0100
@@ -0,0 +1,68 @@
+#include "CS.h"
+
+char *prg_name;
+struct timeval t0;
+
+void debug_init(char *prgname) {
+	prg_name = prgname;
+	gettimeofday(&t0, NULL);
+}
+void pre(char *o) {
+	fprintf(stderr, "%s\n", o);
+	fflush(stderr);
+}
+void deb(int level, DebugP deP) {
+	if ((csP->debMaxLev >= level && csP->debMaxLev != 7) || (csP->debMaxLev == 7 && level == 7)) {
+		if(sem_wait(&(csP->shP->debugSem))< 0) ERR("LOG sem_wait");
+		struct timeval t;
+		gettimeofday(&t, NULL);
+		fprintf(stderr, "%03ld%06d %s: %s\n", (long)t.tv_sec-t0.tv_sec, (int)t.tv_usec, deP->id, deP->msg);
+		fflush(stderr);
+		if(sem_post(&(csP->shP->debugSem)) < 0) ERR("LOG sem_post");
+	}
+}
+void err(int level, char *o, DebugP deP) {
+	fprintf(stderr, "%s: %s\n", deP->id, o);
+	fflush(stderr);
+}
+void back_trace() {
+	if(sem_wait(&(csP->shP->debugSem))< 0) ERR("LOG sem_wait");
+
+   int j, nptrs;
+   void *buffer[24];
+   char **strings;
+
+   nptrs = backtrace(buffer, 24);
+
+   strings = backtrace_symbols(buffer, nptrs);
+   if (strings == NULL) {
+       ERR("ABORT backtrace_symbols");
+       exit(EXIT_FAILURE);
+   }
+
+   char shcmd[] = "sed -e 's/.*\\[\\(.*\\)\\]$/\\1/' | addr2line -fspe ";
+   char *cmdbuf = malloc(sizeof(shcmd) + 64);
+   strcpy(cmdbuf, shcmd);
+   strcat(cmdbuf, prg_name);
+	#define SIZE 640
+   char *resbuf = malloc(SIZE);;
+   for(j = 0; j < nptrs; j++) {
+   	int pc[2], po[2];
+   	if(pipe(pc) < 0) ERR("ABORT pipe");
+   	if(pipe(po) < 0) ERR("ABORT pipe");
+   	if(!fork()) {
+   		close(po[0]); dup2(po[1],1);
+   		close(pc[1]); dup2(pc[0],0);
+   		execl("/bin/bash", "/bin/bash", "-c", cmdbuf, (char *) NULL);
+   	}
+		if(write(pc[1], strings[j], strlen(strings[j])) < 0) ERR("ABORT write pipe");
+		if(write(pc[1], "\n", 1) < 0) ERR("ABORT write pipe");
+		close(pc[1]);
+		memset(resbuf, 0, SIZE);
+		if(read(po[0], resbuf, SIZE)) fprintf(stderr, "%s", resbuf);
+		for(int i = 0; i < 2; i++) close(po[i]), close(pc[i]);
+   }
+	if(sem_post(&(csP->shP->debugSem))< 0) ERR("LOG sem_post");
+   free(strings); free(cmdbuf); free(resbuf);
+
+}