Ruby 3.5.0dev (2025-04-16 revision a4eb81a08334cbe2963e535f9cbfd0aea96c3144)
ruby-runner.c (a4eb81a08334cbe2963e535f9cbfd0aea96c3144)
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>
9
10#ifdef _WIN32
11# error This feature is unnecessary on Windows in favor of SxS.
12#endif
13
14#include "ruby-runner.h"
15
16static void
17insert_env_path(const char *envname, const char *paths, size_t size, int prepend)
18{
19 const char *env = getenv(envname);
20 char c = 0;
21 size_t n = 0;
22
23 if (env) {
24 while ((c = *env) == PATH_SEP) ++env;
25 n = strlen(env);
26 while (n > 0 && env[n-1] == PATH_SEP) --n;
27 }
28 if (c) {
29 char *e = malloc(size+n+1);
30 size_t pos = 0;
31 if (prepend) {
32 if (size == n || (size < n && env[size] == PATH_SEP)) {
33 if (strncmp(paths, env, size) == 0) {
34 free(e);
35 return;
36 }
37 }
38 memcpy(e, paths, pos = size-1);
39 e[pos++] = PATH_SEP;
40 }
41 memcpy(e+pos, env, n);
42 pos += n;
43 if (!prepend) {
44 if (size == n || (size < n && env[n-size-1] == PATH_SEP)) {
45 if (strncmp(paths, &env[n-size], size) == 0) {
46 free(e);
47 return;
48 }
49 }
50 e[pos++] = PATH_SEP;
51 memcpy(e+pos, paths, size-1);
52 pos += size-1;
53 }
54 e[pos] = '\0';
55 env = e;
56 }
57 else {
58 env = paths;
59 }
60 setenv(envname, env, 1);
61}
62
63#define insert_env_path_lit(env, path, prep) \
64 insert_env_path(env, path, sizeof(path), prep)
65
66#define EXTOUT_DIR BUILDDIR"/"EXTOUT
67int
68main(int argc, char **argv)
69{
70 static const char builddir[] = BUILDDIR;
71 static const char rubypath[] = BUILDDIR"/"STRINGIZE(RUBY_INSTALL_NAME);
72 static const char rubylib[] =
73 ABS_SRCDIR"/lib"
74 PATH_SEPARATOR
75 EXTOUT_DIR"/common"
76 PATH_SEPARATOR
77 EXTOUT_DIR"/"ARCH
78 ;
79 const size_t dirsize = sizeof(builddir);
80 const size_t namesize = sizeof(rubypath) - dirsize;
81 const char *rubyname = rubypath + dirsize;
82 char *arg0 = argv[0], *p;
83
84 insert_env_path(LIBPATHENV, builddir, dirsize, 1);
85 insert_env_path("RUBYLIB", rubylib, sizeof(rubylib), 0);
86
87 if (!getenv("GEM_PATH")) {
88 insert_env_path_lit("GEM_PATH", ABS_SRCDIR"/.bundle", 1);
89 insert_env_path_lit("GEM_PATH", BUILDDIR"/.bundle", 1);
90 setenv("GEM_HOME", BUILDDIR"/.bundle", 0);
91 }
92
93 if (!(p = strrchr(arg0, '/'))) p = arg0; else p++;
94 if (strlen(p) < namesize - 1) {
95 argv[0] = malloc(p - arg0 + namesize);
96 memcpy(argv[0], arg0, p - arg0);
97 p = argv[0] + (p - arg0);
98 }
99 memcpy(p, rubyname, namesize);
100
101 execv(rubypath, argv);
102 perror(rubypath);
103 return -1;
104}
#define PATH_SEP
The delimiter of PATH environment variable.
Definition dosish.h:45