skip to content
==> src/main.c <==
1/* mesh-build-programs [name...]: builds every mesh program (programs/<name>/)
2 * into out/programs/<name>/ -- <name>.ptx, <name>.wasm, <triple>/<name> with
3 * source.hash, program.toml -- and their variants.
4 *
5 *   MESH_PROGRAMS_OUT=DIR  the catalog (default <root>/out/programs)
6 *   MESH_PTX_ARCH=sm_NN    the PTX target (default sm_86; meshd JITs it for its GPU)
7 *   MESH_WASM_ONLY=1       only the wasm images;  MESH_NATIVE_ONLY=1  only the native programs
8 *   MESH_SKIP_WASM=1       no wasm images (a catalog for CUDA and native members only)
9 *   SEXC, MESH_PTX_LINK    the tools (default: sexc and mesh-ptx-link beside this binary, else on PATH)
10 *   -C DIR                 the workspace (default: the current folder)
11 *
12 * Ported from alpha-rust-mesh scripts/build-programs.sh. */
13#include "build.h"
14
15#include <limits.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <unistd.h>
20
21static bool on(const char *k) {
22    const char *v = getenv(k);
23    return v && strcmp(v, "1") == 0;
24}
25
26/* A tool: $env, else beside this program (/proc/self/exe), else its name on PATH. */
27static const char *tool(const char *env, const char *name, char *buf, size_t cap) {
28    const char *v = getenv(env);
29    if (v && *v) return v;
30    char self[PATH_MAX];
31    ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
32    if (n > 0) {
33        self[n] = 0;
34        char *slash = strrchr(self, '/');
35        if (slash) {
36            snprintf(buf, cap, "%.*s/%s", (int)(slash - self), self, name);
37            if (access(buf, X_OK) == 0) return buf;
38        }
39    }
40    return name;
41}
42
43int main(int argc, char **argv) {
44    const char *root = ".";
45    int first = 1;
46    if (argc > 2 && strcmp(argv[1], "-C") == 0) {
47        root = argv[2];
48        first = 3;
49    }
50    for (int i = first; i < argc; i++)
51        if (argv[i][0] == '-') {
52            fprintf(stderr, "usage: mesh-build-programs [-C DIR] [name...]\n");
53            return 2;
54        }
55    char outbuf[PATH_MAX], sexcbuf[PATH_MAX], linkbuf[PATH_MAX];
56    const char *out = getenv("MESH_PROGRAMS_OUT");
57    if (!out || !*out) {
58        snprintf(outbuf, sizeof outbuf, "%s/out/programs", root);
59        out = outbuf;
60    }
61    const char *arch = getenv("MESH_PTX_ARCH");
62    mbp_opts o = {
63        .root = root,
64        .out = out,
65        .arch = arch && *arch ? arch : "sm_86",
66        .sexc = tool("SEXC", "sexc", sexcbuf, sizeof sexcbuf),
67        .ptx_link = tool("MESH_PTX_LINK", "mesh-ptx-link", linkbuf, sizeof linkbuf),
68        .wasm_only = on("MESH_WASM_ONLY"),
69        .native_only = on("MESH_NATIVE_ONLY"),
70        .skip_wasm = on("MESH_SKIP_WASM"),
71    };
72    return mbp_run(&o, argv + first, (size_t)(argc - first));
73}