Ruby 4.1.0dev (2026-11-19 revision b3e890bf959ffb14f55ecd016717417a62ebd04e)
dln.c (b3e890bf959ffb14f55ecd016717417a62ebd04e)
1/**********************************************************************
2
3 dln.c -
4
5 $Author$
6 created at: Tue Jan 18 17:05:06 JST 1994
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#ifdef RUBY_EXPORT
13#include "ruby/ruby.h"
14#define dln_notimplement rb_notimplement
15#define dln_memerror rb_memerror
16#define dln_exit rb_exit
17#define dln_loaderror rb_loaderror
18#define dln_fatalerror rb_fatal
19#else
20#define dln_notimplement --->>> dln not implemented <<<---
21#define dln_memerror abort
22#define dln_exit exit
23static void dln_loaderror(const char *format, ...);
24#define dln_fatalerror dln_loaderror
25#endif
26#include "dln.h"
27#include "internal.h"
28#include "internal/box.h"
29#include "internal/compilers.h"
30
31#ifdef HAVE_STDLIB_H
32# include <stdlib.h>
33#endif
34
35#if defined(HAVE_ALLOCA_H)
36#include <alloca.h>
37#endif
38
39#ifdef HAVE_STRING_H
40# include <string.h>
41#else
42# include <strings.h>
43#endif
44
45#if defined __APPLE__
46# include <AvailabilityMacros.h>
47#endif
48
49#ifndef xmalloc
50void *xmalloc();
51void *xcalloc();
52void *xrealloc();
53#endif
54
55#include <stdio.h>
56#include <sys/types.h>
57#include <sys/stat.h>
58
59#ifndef S_ISDIR
60# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
61#endif
62
63#ifdef HAVE_SYS_PARAM_H
64# include <sys/param.h>
65#endif
66#ifndef MAXPATHLEN
67# define MAXPATHLEN 1024
68#endif
69
70#ifdef HAVE_UNISTD_H
71# include <unistd.h>
72#endif
73
74#ifndef UNREACHABLE_RETURN
75# define UNREACHABLE_RETURN(x) return (x)
76#endif
77
78#ifndef dln_loaderror
79static void
80dln_loaderror(const char *format, ...)
81{
82 va_list ap;
83 va_start(ap, format);
84 vfprintf(stderr, format, ap);
85 va_end(ap);
86 abort();
87}
88#endif
89
90#if defined(HAVE_DLOPEN) && !defined(_AIX)
91/* dynamic load with dlopen() */
92# define USE_DLN_DLOPEN
93#endif
94
95#define FUNCNAME_PREFIX "Init_"
96
97#if defined __CYGWIN__ || defined DOSISH
98#define isdirsep(x) ((x) == '/' || (x) == '\\')
99#else
100#define isdirsep(x) ((x) == '/')
101#endif
102
103#if defined(_WIN32) || defined(USE_DLN_DLOPEN)
104struct string_part {
105 const char *ptr;
106 size_t len;
107};
108
109static struct string_part
110init_funcname_len(const char *file)
111{
112 const char *p = file, *base, *dot = NULL;
113
114 /* Load the file as an object one */
115 for (base = p; *p; p++) { /* Find position of last '/' */
116 if (*p == '.' && !dot) dot = p;
117 if (isdirsep(*p)) base = p+1, dot = NULL;
118 }
119 /* Delete suffix if it exists */
120 const size_t len = (dot ? dot : p) - base;
121 return (struct string_part){base, len};
122}
123
124static inline char *
125concat_funcname(char *buf, const char *prefix, size_t plen, const struct string_part base)
126{
127 if (!buf) {
128 dln_memerror();
129 }
130 memcpy(buf, prefix, plen);
131 memcpy(buf + plen, base.ptr, base.len);
132 buf[plen + base.len] = '\0';
133 return buf;
134}
135
136#define build_funcname(prefix, buf, file) do {\
137 const struct string_part f = init_funcname_len(file);\
138 const size_t plen = sizeof(prefix "") - 1;\
139 *(buf) = concat_funcname(ALLOCA_N(char, plen+f.len+1), prefix, plen, f);\
140} while (0)
141
142#define init_funcname(buf, file) build_funcname(FUNCNAME_PREFIX, buf, file)
143#endif
144
145#ifdef USE_DLN_DLOPEN
146# include <dlfcn.h>
147#endif
148
149#if defined(_AIX)
150#include <ctype.h> /* for isdigit() */
151#include <errno.h> /* for global errno */
152#include <sys/ldr.h>
153#endif
154
155#ifdef _WIN32
156#include <windows.h>
157#include <imagehlp.h>
158#endif
159
160#ifdef _WIN32
161static const char *
162dln_strerror(char *message, size_t size)
163{
164 int error = GetLastError();
165 char *p = message;
166 size_t len = snprintf(message, size, "%d: ", error);
167
168#define format_message(sublang) FormatMessage(\
169 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, \
170 NULL, error, MAKELANGID(LANG_NEUTRAL, (sublang)), \
171 message + len, size - len, NULL)
172 if (format_message(SUBLANG_ENGLISH_US) == 0)
173 format_message(SUBLANG_DEFAULT);
174 for (p = message + len; *p; p++) {
175 if (*p == '\n' || *p == '\r')
176 *p = ' ';
177 }
178 return message;
179}
180#define dln_strerror() dln_strerror(message, sizeof message)
181#elif defined USE_DLN_DLOPEN
182static const char *
183dln_strerror(void)
184{
185 return (char*)dlerror();
186}
187#endif
188
189#if defined(_AIX)
190static void
191aix_loaderror(const char *pathname)
192{
193 char *message[1024], errbuf[1024];
194 int i;
195#define ERRBUF_APPEND(s) strlcat(errbuf, (s), sizeof(errbuf))
196 snprintf(errbuf, sizeof(errbuf), "load failed - %s. ", pathname);
197
198 if (loadquery(L_GETMESSAGES, &message[0], sizeof(message)) != -1) {
199 ERRBUF_APPEND("Please issue below command for detailed reasons:\n\t");
200 ERRBUF_APPEND("/usr/sbin/execerror ruby ");
201 for (i=0; message[i]; i++) {
202 ERRBUF_APPEND("\"");
203 ERRBUF_APPEND(message[i]);
204 ERRBUF_APPEND("\" ");
205 }
206 ERRBUF_APPEND("\n");
207 }
208 else {
209 ERRBUF_APPEND(strerror(errno));
210 ERRBUF_APPEND("[loadquery failed]");
211 }
212 dln_loaderror("%s", errbuf);
213}
214#endif
215
216#if defined _WIN32 && defined RUBY_EXPORT
217HANDLE rb_libruby_handle(void);
218
219static int
220rb_w32_check_imported(HMODULE ext, HMODULE mine)
221{
222 ULONG size;
223 const IMAGE_IMPORT_DESCRIPTOR *desc;
224
225 desc = ImageDirectoryEntryToData(ext, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
226 if (!desc) return 0;
227 while (desc->Name) {
228 PIMAGE_THUNK_DATA pint = (PIMAGE_THUNK_DATA)((char *)ext + desc->Characteristics);
229 PIMAGE_THUNK_DATA piat = (PIMAGE_THUNK_DATA)((char *)ext + desc->FirstThunk);
230 for (; piat->u1.Function; piat++, pint++) {
231 static const char prefix[] = "rb_";
232 PIMAGE_IMPORT_BY_NAME pii;
233 const char *name;
234
235 if (IMAGE_SNAP_BY_ORDINAL(pint->u1.Ordinal)) continue;
236 pii = (PIMAGE_IMPORT_BY_NAME)((char *)ext + (size_t)pint->u1.AddressOfData);
237 name = (const char *)pii->Name;
238 if (strncmp(name, prefix, sizeof(prefix) - 1) == 0) {
239 FARPROC addr = GetProcAddress(mine, name);
240 if (addr) return (FARPROC)piat->u1.Function == addr;
241 }
242 }
243 desc++;
244 }
245 return 1;
246}
247#endif
248
249#if defined(DLN_NEEDS_ALT_SEPARATOR) && DLN_NEEDS_ALT_SEPARATOR
250#define translit_separator(src) do { \
251 char *tmp = ALLOCA_N(char, strlen(src) + 1), *p = tmp, c; \
252 do { \
253 *p++ = ((c = *file++) == '/') ? DLN_NEEDS_ALT_SEPARATOR : c; \
254 } while (c); \
255 (src) = tmp; \
256 } while (0)
257#else
258#define translit_separator(str) (void)(str)
259#endif
260
261#ifdef USE_DLN_DLOPEN
262# include "ruby/internal/stdbool.h"
263# include "internal/warnings.h"
264static bool
265dln_incompatible_func(void *handle, const char *funcname, void *const fp, const char **libname)
266{
267 void *ex = dlsym(handle, funcname);
268 if (!ex) return false;
269 if (ex == fp) return false;
270# if defined(HAVE_DLADDR) && !defined(__CYGWIN__)
271 Dl_info dli;
272 if (dladdr(ex, &dli)) {
273 *libname = dli.dli_fname;
274 }
275# endif
276 return true;
277}
278
279COMPILER_WARNING_PUSH
280#if defined(__clang__) || GCC_VERSION_SINCE(4, 2, 0)
281COMPILER_WARNING_IGNORED(-Wpedantic)
282#endif
283static bool
284dln_incompatible_library_p(void *handle, const char **libname)
285{
286#define check_func(func) \
287 if (dln_incompatible_func(handle, #func, (void *)&func, libname)) \
288 return true
289 check_func(ruby_xmalloc);
290 return false;
291}
292COMPILER_WARNING_POP
293#endif
294
295#if !defined(MAC_OS_X_VERSION_MIN_REQUIRED)
296/* assume others than old Mac OS X have no problem */
297# define dln_disable_dlclose() false
298
299#elif !defined(MAC_OS_X_VERSION_10_11) || \
300 (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_11)
301/* targeting older versions only */
302# define dln_disable_dlclose() true
303
304#elif MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_11
305/* targeting newer versions only */
306# define dln_disable_dlclose() false
307
308#else
309/* support both versions, and check at runtime */
310# include <sys/sysctl.h>
311
312static bool
313dln_disable_dlclose(void)
314{
315 int mib[] = {CTL_KERN, KERN_OSREV};
316 int32_t rev;
317 size_t size = sizeof(rev);
318 if (sysctl(mib, numberof(mib), &rev, &size, NULL, 0)) return true;
319 if (rev < MAC_OS_X_VERSION_10_11) return true;
320 return false;
321}
322#endif
323
324#if defined(_WIN32) || defined(USE_DLN_DLOPEN)
325static void *
326dln_open(const char *file)
327{
328 static const char incompatible[] = "incompatible library version";
329 const char *error = NULL;
330 void *handle;
331
332#if defined(_WIN32)
333# define DLN_DEFINED
334 char message[1024];
335
336 /* Convert the file path to wide char */
337 WCHAR *winfile = rb_w32_mbstr_to_wstr(CP_UTF8, file, -1, NULL);
338 if (!winfile) {
339 dln_memerror();
340 }
341
342 /* Load file */
343 handle = LoadLibraryW(winfile);
344 free(winfile);
345
346 if (!handle) {
347 error = dln_strerror();
348 goto failed;
349 }
350
351# if defined(RUBY_EXPORT)
352 if (!rb_w32_check_imported(handle, rb_libruby_handle())) {
353 FreeLibrary(handle);
354 error = incompatible;
355 goto failed;
356 }
357# endif
358
359#elif defined(USE_DLN_DLOPEN)
360# define DLN_DEFINED
361
362# ifndef RTLD_LAZY
363# define RTLD_LAZY 1
364# endif
365# ifndef RTLD_GLOBAL
366# define RTLD_GLOBAL 0
367# endif
368# ifndef RTLD_LOCAL
369# define RTLD_LOCAL 0 /* TODO: 0??? some systems (including libc) use 0x00100 for RTLD_GLOBAL, 0x00000 for RTLD_LOCAL */
370# endif
371
372 /* Load file */
373 int mode = rb_box_available() ? RTLD_LAZY|RTLD_LOCAL : RTLD_LAZY|RTLD_GLOBAL;
374 handle = dlopen(file, mode);
375 if (handle == NULL) {
376 error = dln_strerror();
377 goto failed;
378 }
379
380# if defined(RUBY_EXPORT)
381 {
382 const char *libruby_name = NULL;
383 if (dln_incompatible_library_p(handle, &libruby_name)) {
384 if (dln_disable_dlclose()) {
385 /* dlclose() segfaults */
386 if (libruby_name) {
387 dln_fatalerror("linked to incompatible %s - %s", libruby_name, file);
388 }
389 dln_fatalerror("%s - %s", incompatible, file);
390 }
391 else {
392 if (libruby_name) {
393 const size_t len = strlen(libruby_name);
394 char *const tmp = ALLOCA_N(char, len + 1);
395 if (tmp) memcpy(tmp, libruby_name, len + 1);
396 libruby_name = tmp;
397 }
398 dlclose(handle);
399 if (libruby_name) {
400 dln_loaderror("linked to incompatible %s - %s", libruby_name, file);
401 }
402 error = incompatible;
403 goto failed;
404 }
405 }
406 }
407# endif
408#endif
409
410 return handle;
411
412 failed:
413 dln_loaderror("%s - %s", error, file);
414}
415
416static void *
417dln_sym(void *handle, const char *symbol)
418{
419#if defined(_WIN32)
420 return GetProcAddress(handle, symbol);
421#elif defined(USE_DLN_DLOPEN)
422 return dlsym(handle, symbol);
423#endif
424}
425
426static uintptr_t
427dln_sym_func(void *handle, const char *symbol)
428{
429 void *func = dln_sym(handle, symbol);
430
431 if (func == NULL) {
432 const char *error;
433#if defined(_WIN32)
434 char message[1024];
435 error = dln_strerror();
436#elif defined(USE_DLN_DLOPEN)
437 const size_t errlen = strlen(error = dln_strerror()) + 1;
438 error = memcpy(ALLOCA_N(char, errlen), error, errlen);
439#endif
440 dln_loaderror("%s - %s", error, symbol);
441 }
442 return (uintptr_t)func;
443}
444
445#define dln_sym_callable(rettype, argtype, handle, symbol) \
446 (*(rettype (*)argtype)dln_sym_func(handle, symbol))
447#endif
448
449void *
450dln_symbol(void *handle, const char *symbol)
451{
452#if defined(_WIN32) || defined(USE_DLN_DLOPEN)
453 if (handle == NULL) {
454# if defined(USE_DLN_DLOPEN)
455 handle = dlopen(NULL, RTLD_LAZY | RTLD_GLOBAL);
456# elif defined(_WIN32)
457 handle = rb_libruby_handle();
458# else
459 return NULL;
460# endif
461 }
462 return dln_sym(handle, symbol);
463#else
464 return NULL;
465#endif
466}
467
468
469#if defined(RUBY_DLN_CHECK_ABI) && defined(USE_DLN_DLOPEN)
470static bool
471abi_check_enabled_p(void)
472{
473 const char *val = getenv("RUBY_ABI_CHECK");
474 return val == NULL || !(val[0] == '0' && val[1] == '\0');
475}
476#endif
477
478static void *
479dln_load_and_init(const char *file, const char *init_fct_name)
480{
481#if defined(DLN_DEFINED)
482 void *handle = dln_open(file);
483
484#ifdef RUBY_DLN_CHECK_ABI
485 typedef unsigned long long abi_version_number;
486 abi_version_number binary_abi_version =
487 dln_sym_callable(abi_version_number, (void), handle, "ruby_abi_version")();
488 if (binary_abi_version != RUBY_ABI_VERSION && abi_check_enabled_p()) {
489 dln_loaderror("incompatible ABI version of binary - %s", file);
490 }
491#endif
492
493 /* Call the init code */
494 dln_sym_callable(void, (void), handle, init_fct_name)();
495
496 return handle;
497
498#elif defined(_AIX)
499# define DLN_DEFINED
500 {
501 void (*init_fct)(void);
502
503 /* TODO: check - AIX's load system call will return the first/last symbol/function? */
504 init_fct = (void(*)(void))load((char*)file, 1, 0);
505 if (init_fct == NULL) {
506 aix_loaderror(file);
507 }
508 if (loadbind(0, (void*)dln_load, (void*)init_fct) == -1) {
509 aix_loaderror(file);
510 }
511 (*init_fct)();
512 return (void*)init_fct;
513 }
514#else
515 dln_notimplement();
517#endif
518}
519
520void *
521dln_load(const char *file)
522{
523 return dln_load_feature(file, file);
524}
525
526void *
527dln_load_feature(const char *file, const char *fname)
528{
529#if defined(DLN_DEFINED)
530 char *init_fct_name;
531 init_funcname(&init_fct_name, fname);
532 return dln_load_and_init(file, init_fct_name);
533#else
534 dln_notimplement();
536#endif
537}
#define xrealloc
Old name of ruby_xrealloc.
Definition xmalloc.h:56
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define xcalloc
Old name of ruby_xcalloc.
Definition xmalloc.h:55
int len
Length of the buffer.
Definition io.h:8
#define ALLOCA_N(type, n)
Definition memory.h:295
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
C99 shim for <stdbool.h>.