ia64/xen-unstable

view tools/xenstore/utils.c @ 6946:e703abaf6e3d

Add behaviour to the remove methods to remove the transaction's path itself. This allows us to write Remove(path) to remove the specified path rather than having to slice the path ourselves.
author emellor@ewan
date Sun Sep 18 14:42:13 2005 +0100 (2005-09-18)
parents 3233e7ecfa9f
children 06d84bf87159
line source
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <stdarg.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <errno.h>
7 #include <unistd.h>
8 #include <fcntl.h>
9 #include <sys/types.h>
10 #include <signal.h>
12 #include "utils.h"
14 void xprintf(const char *fmt, ...)
15 {
16 static FILE *out = NULL;
17 va_list args;
18 if (!out)
19 out = stderr;
21 va_start(args, fmt);
22 vfprintf(out, fmt, args);
23 va_end(args);
24 fflush(out);
25 }
27 void barf(const char *fmt, ...)
28 {
29 char *str;
30 va_list arglist;
32 xprintf("FATAL: ");
34 va_start(arglist, fmt);
35 vasprintf(&str, fmt, arglist);
36 va_end(arglist);
38 xprintf("%s\n", str);
39 free(str);
40 exit(1);
41 }
43 void barf_perror(const char *fmt, ...)
44 {
45 char *str;
46 int err = errno;
47 va_list arglist;
49 xprintf("FATAL: ");
51 va_start(arglist, fmt);
52 vasprintf(&str, fmt, arglist);
53 va_end(arglist);
55 xprintf("%s: %s\n", str, strerror(err));
56 free(str);
57 exit(1);
58 }
60 void *_realloc_array(void *ptr, size_t size, size_t num)
61 {
62 if (num >= SIZE_MAX/size)
63 return NULL;
64 return realloc_nofail(ptr, size * num);
65 }
67 void *realloc_nofail(void *ptr, size_t size)
68 {
69 ptr = realloc(ptr, size);
70 if (ptr)
71 return ptr;
72 barf("realloc of %zu failed", size);
73 }
75 void *malloc_nofail(size_t size)
76 {
77 void *ptr = malloc(size);
78 if (ptr)
79 return ptr;
80 barf("malloc of %zu failed", size);
81 }
83 /* This version adds one byte (for nul term) */
84 void *grab_file(const char *filename, unsigned long *size)
85 {
86 unsigned int max = 16384;
87 int ret, fd;
88 void *buffer;
90 if (streq(filename, "-"))
91 fd = dup(STDIN_FILENO);
92 else
93 fd = open(filename, O_RDONLY, 0);
95 if (fd < 0)
96 return NULL;
98 buffer = malloc(max+1);
99 *size = 0;
100 while ((ret = read(fd, buffer + *size, max - *size)) > 0) {
101 *size += ret;
102 if (*size == max)
103 buffer = realloc(buffer, max *= 2 + 1);
104 }
105 if (ret < 0) {
106 free(buffer);
107 buffer = NULL;
108 } else
109 ((char *)buffer)[*size] = '\0';
110 close(fd);
111 return buffer;
112 }
114 void release_file(void *data, unsigned long size __attribute__((unused)))
115 {
116 free(data);
117 }