With MULT and DIV operations
[pspdecompiler.git] / utils.c
blob0cc780f5686904badfec2215130893b052e5c29d
1 /**
2 * Author: Humberto Naves (hsnaves@gmail.com)
3 */
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <string.h>
9 #include <errno.h>
11 #include "utils.h"
13 void report (const char *fmt, ...)
15 va_list ap;
16 va_start (ap, fmt);
17 vfprintf (stdout, fmt, ap);
18 va_end (ap);
21 void error (const char *fmt, ...)
23 va_list ap;
24 va_start (ap, fmt);
25 vfprintf (stderr, fmt, ap);
26 fprintf (stderr, "\n");
27 va_end (ap);
30 void xerror (const char *fmt, ...)
32 va_list ap;
33 va_start (ap, fmt);
34 vfprintf (stderr, fmt, ap);
35 fprintf (stderr, ": %s\n", strerror (errno));
36 va_end (ap);
40 void fatal (const char *fmt, ...)
42 va_list ap;
43 va_start (ap, fmt);
44 fprintf (stderr, "fatal: ");
45 vfprintf (stderr, fmt, ap);
46 fprintf (stderr, "\n");
47 va_end (ap);
48 exit (1);
51 void xfatal (const char *fmt, ...)
53 va_list ap;
54 va_start (ap, fmt);
55 fprintf (stderr, "fatal: ");
56 vfprintf (stderr, fmt, ap);
57 fprintf (stderr, ": %s\n", strerror (errno));
58 va_end (ap);
59 exit (1);
62 void *xmalloc (size_t size)
64 void *ptr = malloc (size);
65 if (!ptr) fatal (__FILE__ ": memory exhausted");
66 return ptr;
69 void *xrealloc (void *ptr, size_t size)
71 void *nptr = realloc (ptr, size);
72 if (!nptr) fatal (__FILE__ ": can't realloc");
73 return nptr;
77 static
78 int _file_size (FILE *fp, const char *path, size_t *size)
80 long r;
82 if (fseek (fp, 0L, SEEK_END)) {
83 xerror (__FILE__ ": can't seek file `%s'", path);
84 fclose (fp);
85 return 0;
88 r = ftell (fp);
89 if (r == -1) {
90 xerror (__FILE__ ": can't get file size of `%s'", path);
91 return 0;
94 if (size) *size = (size_t) r;
95 return 1;
98 void *read_file (const char *path, size_t *size)
100 FILE *fp;
101 void *buffer;
102 size_t file_size;
103 size_t read_return;
105 fp = fopen (path, "rb");
106 if (!fp) {
107 xerror (__FILE__ ": can't open file `%s'", path);
108 return NULL;
111 if (!_file_size (fp, path, &file_size)) {
112 return NULL;
115 buffer = xmalloc (file_size);
116 rewind (fp);
118 read_return = fread (buffer, 1, file_size, fp);
119 fclose (fp);
121 if (read_return != file_size) {
122 error (__FILE__ ": can't fully read file `%s'", path);
123 free (buffer);
124 return NULL;
127 if (size) *size = file_size;
128 return buffer;