* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / ruby-runner.c
blobb756c219fa2bfa2d7bba8cceed6974bed4456450
1 #define _POSIX_C_SOURCE 200809L
2 #include "ruby/internal/config.h"
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
10 #include "ruby-runner.h"
12 #ifdef MAKE_MJIT_BUILD_DIR
13 const char MJIT_HEADER[] = BUILDDIR "/" MJIT_MIN_HEADER;
14 #else
16 #define STRINGIZE(expr) STRINGIZE0(expr)
17 #define STRINGIZE0(expr) #expr
19 static void
20 insert_env_path(const char *envname, const char *paths, size_t size, int prepend)
22 const char *env = getenv(envname);
23 char c = 0;
24 size_t n = 0;
26 if (env) {
27 while ((c = *env) == PATH_SEP) ++env;
28 n = strlen(env);
29 while (n > 0 && env[n-1] == PATH_SEP) --n;
31 if (c) {
32 char *e = malloc(size+n+1);
33 size_t pos = 0;
34 if (prepend) {
35 memcpy(e, paths, pos = size-1);
36 e[pos++] = PATH_SEP;
38 memcpy(e+pos, env, n);
39 pos += n;
40 if (!prepend) {
41 e[pos++] = PATH_SEP;
42 memcpy(e+pos, paths, size-1);
43 pos += size-1;
45 e[pos] = '\0';
46 env = e;
48 else {
49 env = paths;
51 setenv(envname, env, 1);
54 #define EXTOUT_DIR BUILDDIR"/"EXTOUT
55 int
56 main(int argc, char **argv)
58 static const char builddir[] = BUILDDIR;
59 static const char rubypath[] = BUILDDIR"/"STRINGIZE(RUBY_INSTALL_NAME);
60 static const char rubylib[] =
61 ABS_SRCDIR"/lib"
62 PATH_SEPARATOR
63 EXTOUT_DIR"/common"
64 PATH_SEPARATOR
65 EXTOUT_DIR"/"ARCH
67 #ifndef LOAD_RELATIVE
68 static const char mjit_build_dir[] = BUILDDIR"/mjit_build_dir."SOEXT;
69 struct stat stbuf;
70 #endif
71 const size_t dirsize = sizeof(builddir);
72 const size_t namesize = sizeof(rubypath) - dirsize;
73 const char *rubyname = rubypath + dirsize;
74 char *arg0 = argv[0], *p;
76 insert_env_path(LIBPATHENV, builddir, dirsize, 1);
77 insert_env_path("RUBYLIB", rubylib, sizeof(rubylib), 0);
78 #ifndef LOAD_RELATIVE
79 if (PRELOADENV[0] && stat(mjit_build_dir, &stbuf) == 0) {
80 insert_env_path(PRELOADENV, mjit_build_dir, sizeof(mjit_build_dir), 1);
81 setenv("MJIT_SEARCH_BUILD_DIR", "true", 0);
83 #endif
85 if (!(p = strrchr(arg0, '/'))) p = arg0; else p++;
86 if (strlen(p) < namesize - 1) {
87 argv[0] = malloc(p - arg0 + namesize);
88 memcpy(argv[0], arg0, p - arg0);
89 p = argv[0] + (p - arg0);
91 memcpy(p, rubyname, namesize);
93 execv(rubypath, argv);
94 perror(rubypath);
95 return -1;
98 #endif /* MAKE_MJIT_BUILD_DIR */