]> git.ozlabs.org Git - ccan/blob - tools/tools.c
configurator: HAVE_PROC_SELF_MAPS
[ccan] / tools / tools.c
1 #include <ccan/talloc/talloc.h>
2 #include <ccan/grab_file/grab_file.h>
3 #include <ccan/noerr/noerr.h>
4 #include <ccan/read_write_all/read_write_all.h>
5 #include <ccan/noerr/noerr.h>
6 #include <ccan/time/time.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <sys/time.h>
10 #include <sys/wait.h>
11 #include <fcntl.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <stdarg.h>
15 #include <errno.h>
16 #include <err.h>
17 #include <unistd.h>
18 #include <assert.h>
19 #include <signal.h>
20 #include "tools.h"
21
22 static const char *tmpdir = NULL;
23 bool tools_verbose = false;
24
25 /* Ten minutes. */
26 const unsigned int default_timeout_ms = 10 * 60 * 1000;
27
28 char *talloc_basename(const void *ctx, const char *dir)
29 {
30         char *p = strrchr(dir, '/');
31
32         if (!p)
33                 return talloc_strdup(ctx, dir);
34         return talloc_strdup(ctx, p+1);
35 }
36
37 char *talloc_dirname(const void *ctx, const char *dir)
38 {
39         char *p = strrchr(dir, '/');
40
41         if (!p)
42                 return talloc_strdup(ctx, ".");
43         return talloc_strndup(ctx, dir, p - dir);
44 }
45
46 char *talloc_getcwd(const void *ctx)
47 {
48         unsigned int len;
49         char *cwd;
50
51         /* *This* is why people hate C. */
52         len = 32;
53         cwd = talloc_array(ctx, char, len);
54         while (!getcwd(cwd, len)) {
55                 if (errno != ERANGE) {
56                         talloc_free(cwd);
57                         return NULL;
58                 }
59                 cwd = talloc_realloc(ctx, cwd, char, len *= 2);
60         }
61         return cwd;
62 }
63
64 static void killme(int sig)
65 {
66         kill(-getpid(), SIGKILL);
67 }
68
69 char *run_with_timeout(const void *ctx, const char *cmd,
70                        bool *ok, unsigned *timeout_ms)
71 {
72         pid_t pid;
73         int p[2];
74         char *ret;
75         int status, ms;
76         struct timeval start;
77
78         *ok = false;
79         if (pipe(p) != 0)
80                 return talloc_asprintf(ctx, "Failed to create pipe: %s",
81                                        strerror(errno));
82
83         if (tools_verbose)
84                 printf("Running: %s\n", cmd);
85
86         /* Always flush buffers before fork! */
87         fflush(stdout);
88         start = time_now();
89         pid = fork();
90         if (pid == -1) {
91                 close_noerr(p[0]);
92                 close_noerr(p[1]);
93                 return talloc_asprintf(ctx, "Failed to fork: %s",
94                                        strerror(errno));
95                 return NULL;
96         }
97
98         if (pid == 0) {
99                 struct itimerval itim;
100
101                 if (dup2(p[1], STDOUT_FILENO) != STDOUT_FILENO
102                     || dup2(p[1], STDERR_FILENO) != STDERR_FILENO
103                     || close(p[0]) != 0
104                     || close(STDIN_FILENO) != 0
105                     || open("/dev/null", O_RDONLY) != STDIN_FILENO)
106                         exit(128);
107
108                 signal(SIGALRM, killme);
109                 itim.it_interval.tv_sec = itim.it_interval.tv_usec = 0;
110                 itim.it_value = time_from_msec(*timeout_ms);
111                 setitimer(ITIMER_REAL, &itim, NULL);
112
113                 status = system(cmd);
114                 if (WIFEXITED(status))
115                         exit(WEXITSTATUS(status));
116                 /* Here's a hint... */
117                 exit(128 + WTERMSIG(status));
118         }
119
120         close(p[1]);
121         ret = grab_fd(ctx, p[0], NULL);
122         /* This shouldn't fail... */
123         if (waitpid(pid, &status, 0) != pid)
124                 err(1, "Failed to wait for child");
125
126         ms = time_to_msec(time_sub(time_now(), start));
127         if (ms > *timeout_ms)
128                 *timeout_ms = 0;
129         else
130                 *timeout_ms -= ms;
131         close(p[0]);
132         if (tools_verbose) {
133                 printf("%s", ret);
134                 printf("Finished: %u ms, %s %u\n", ms,
135                        WIFEXITED(status) ? "exit status" : "killed by signal",
136                        WIFEXITED(status) ? WEXITSTATUS(status)
137                        : WTERMSIG(status));
138         }
139         *ok = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
140         return ret;
141 }
142
143 /* Tallocs *output off ctx; return false if command fails. */
144 bool run_command(const void *ctx, unsigned int *time_ms, char **output,
145                  const char *fmt, ...)
146 {
147         va_list ap;
148         char *cmd;
149         bool ok;
150         unsigned int default_time = default_timeout_ms;
151
152         if (!time_ms)
153                 time_ms = &default_time;
154         else if (*time_ms == 0) {
155                 *output = talloc_strdup(ctx, "\n== TIMED OUT ==\n");
156                 return false;
157         }
158
159         va_start(ap, fmt);
160         cmd = talloc_vasprintf(ctx, fmt, ap);
161         va_end(ap);
162
163         *output = run_with_timeout(ctx, cmd, &ok, time_ms);
164         if (ok)
165                 return true;
166         if (!*output)
167                 err(1, "Problem running child");
168         if (*time_ms == 0)
169                 *output = talloc_asprintf_append(*output,
170                                                  "\n== TIMED OUT ==\n");
171         return false;
172 }
173
174 static int unlink_all(const char *dir)
175 {
176         char cmd[strlen(dir) + sizeof("rm -rf ")];
177         sprintf(cmd, "rm -rf %s", dir);
178         if (tools_verbose)
179                 printf("Running: %s\n", cmd);
180         if (system(cmd) != 0)
181                 warn("Could not remove temporary work in %s", dir);
182         return 0;
183 }
184
185 const char *temp_dir(const void *ctx)
186 {
187         /* For first call, create dir. */
188         while (!tmpdir) {
189                 tmpdir = getenv("TMPDIR");
190                 if (!tmpdir)
191                         tmpdir = "/tmp";
192                 tmpdir = talloc_asprintf(talloc_autofree_context(),
193                                          "%s/ccanlint-%u.%lu",
194                                          tmpdir, getpid(), random());
195                 if (mkdir(tmpdir, 0700) != 0) {
196                         if (errno == EEXIST) {
197                                 talloc_free(tmpdir);
198                                 tmpdir = NULL;
199                                 continue;
200                         }
201                         err(1, "mkdir %s failed", tmpdir);
202                 }
203                 talloc_set_destructor(tmpdir, unlink_all);
204                 if (tools_verbose)
205                         printf("Created temporary directory %s\n", tmpdir);
206         }
207         return tmpdir;
208 }
209
210 int unlink_file_destructor(char *filename)
211 {
212         unlink(filename);
213         return 0;
214 }
215
216 char *temp_file(const void *ctx, const char *extension, const char *srcname)
217 {
218         unsigned baselen;
219         char *f, *suffix = talloc_strdup(ctx, "");
220         struct stat st;
221         unsigned int count = 0;
222
223         srcname = talloc_basename(ctx, srcname);
224         if (strrchr(srcname, '.'))
225                 baselen = strrchr(srcname, '.') - srcname;
226         else
227                 baselen = strlen(srcname);
228
229         do {
230                 f = talloc_asprintf(ctx, "%s/%.*s%s%s",
231                                     temp_dir(ctx),
232                                     baselen, srcname,
233                                     suffix, extension);
234                 talloc_free(suffix);
235                 suffix = talloc_asprintf(ctx, "-%u", ++count);
236         } while (lstat(f, &st) == 0);
237
238         if (tools_verbose)
239                 printf("Creating file %s\n", f);
240
241         talloc_free(suffix);
242         return f;
243 }
244
245 bool move_file(const char *oldname, const char *newname)
246 {
247         char *contents;
248         size_t size;
249         int fd;
250         bool ret;
251
252         if (tools_verbose)
253                 printf("Moving file %s to %s: ", oldname, newname);
254
255         /* Simple case: rename works. */
256         if (rename(oldname, newname) == 0) {
257                 if (tools_verbose)
258                         printf("rename worked\n");
259                 return true;
260         }
261
262         /* Try copy and delete: not atomic! */
263         contents = grab_file(NULL, oldname, &size);
264         if (!contents) {
265                 if (tools_verbose)
266                         printf("read failed: %s\n", strerror(errno));
267                 return false;
268         }
269
270         fd = open(newname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
271         if (fd < 0) {
272                 if (tools_verbose)
273                         printf("output open failed: %s\n", strerror(errno));
274                 ret = false;
275                 goto free;
276         }
277
278         ret = write_all(fd, contents, size);
279         if (close(fd) != 0)
280                 ret = false;
281
282         if (ret) {
283                 if (tools_verbose)
284                         printf("copy worked\n");
285                 unlink(oldname);
286         } else {
287                 if (tools_verbose)
288                         printf("write/close failed\n");
289                 unlink(newname);
290         }
291
292 free:
293         talloc_free(contents);
294         return ret;
295 }