+ *output = run_with_timeout(ctx, cmd, &ok, time_ms);
+ if (ok)
+ return true;
+ if (!*output)
+ err(1, "Problem running child");
+ if (*time_ms == 0)
+ *output = talloc_asprintf_append(*output,
+ "\n== TIMED OUT ==\n");
+ return false;
+}
+
+static int unlink_all(const char *dir)
+{
+ char cmd[strlen(dir) + sizeof("rm -rf ")];
+ sprintf(cmd, "rm -rf %s", dir);
+ if (tools_verbose)
+ printf("Running: %s\n", cmd);
+ if (system(cmd) != 0)
+ warn("Could not remove temporary work in %s", dir);
+ return 0;
+}
+
+const char *temp_dir(const void *ctx)
+{
+ /* For first call, create dir. */
+ while (!tmpdir) {
+ tmpdir = getenv("TMPDIR");
+ if (!tmpdir)
+ tmpdir = "/tmp";
+ tmpdir = talloc_asprintf(talloc_autofree_context(),
+ "%s/ccanlint-%u.%lu",
+ tmpdir, getpid(), random());
+ if (mkdir(tmpdir, 0700) != 0) {
+ if (errno == EEXIST) {
+ talloc_free(tmpdir);
+ tmpdir = NULL;
+ continue;
+ }
+ err(1, "mkdir %s failed", tmpdir);
+ }
+ talloc_set_destructor(tmpdir, unlink_all);
+ if (tools_verbose)
+ printf("Created temporary directory %s\n", tmpdir);
+ }
+ return tmpdir;
+}
+
+int unlink_file_destructor(char *filename)
+{
+ unlink(filename);
+ return 0;
+}
+
+char *maybe_temp_file(const void *ctx, const char *extension, bool keep,
+ const char *srcname)
+{
+ unsigned baselen;
+ char *f, *suffix = talloc_strdup(ctx, "");
+ struct stat st;
+ unsigned int count = 0;
+
+ srcname = talloc_basename(ctx, srcname);
+ if (strrchr(srcname, '.'))
+ baselen = strrchr(srcname, '.') - srcname;
+ else
+ baselen = strlen(srcname);
+
+ do {
+ f = talloc_asprintf(ctx, "%s/%.*s%s%s",
+ temp_dir(ctx),
+ baselen, srcname,
+ suffix, extension);
+ talloc_free(suffix);
+ suffix = talloc_asprintf(ctx, "-%u", ++count);
+ } while (lstat(f, &st) == 0);
+
+ if (tools_verbose)
+ printf("Creating %sfile %s\n", keep ? "" : "temporary ", f);
+
+ if (!keep)
+ talloc_set_destructor(f, unlink_file_destructor);