Debian Codegraph @

src/load.c

raw
1 /*
2 * load.c - load a program
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #define LIBGAUCHE_BODY
35 #include "gauche.h"
36 #include "gauche/priv/configP.h"
37 #include "gauche/port.h"
38 #include "gauche/priv/builtin-syms.h"
39 #include "gauche/priv/readerP.h"
40 #include "gauche/priv/portP.h"
41 #include "gauche/priv/moduleP.h"
42
43 #include <ctype.h>
44 #include <fcntl.h>
45
46 /*
47 * Load file.
48 */
49
50 /* Static parameters */
51 static struct {
52 /* Load path list */
53 ScmGloc *load_path_rec; /* *load-path* */
54 ScmGloc *dynload_path_rec; /* *dynamic-load-path* */
55 ScmGloc *load_suffixes_rec; /* *load-suffixes* */
56 ScmGloc *load_path_hooks_rec; /* *load-path-hooks* */
57 ScmInternalMutex path_mutex;
58
59 /* Provided features */
60 ScmObj provided; /* List of provided features. */
61 ScmObj providing; /* Alist of features that is being loaded,
62 and the thread that is loading it. */
63 ScmObj waiting; /* Alist of threads that is waiting for
64 a feature to being provided, and the
65 feature that is waited. */
66 ScmInternalMutex prov_mutex;
67 ScmInternalCond prov_cv;
68
69 /* Dynamic environments kept during specific `load'. They are
70 thread-specific, and we use ScmParameter mechanism. */
71 ScmPrimitiveParameter *load_history; /* history of the nested load */
72 ScmPrimitiveParameter *load_next; /* list of the directories to be
73 searched. */
74 ScmPrimitiveParameter *load_port; /* current port from which we are
75 loading */
76
77 /* Dynamic linking */
78 ScmObj dso_suffixes;
79 ScmHashTable *dso_table; /* Hashtable path -> <dlobj> */
80 ScmObj dso_prelinked; /* List of 'prelinked' DSOs, that is, they
81 are already linked but pretened to be
82 DSOs. dynamic-load won't do anything.
83 NB: We assume initfns of prelinked DSOs
84 are already called by the application,
85 but we may change this design in future.
86 */
87 ScmClass *dlptr_class; /* Foreign pointer class for the address
88 retrieved from dso. */
89 ScmInternalMutex dso_mutex;
90 } ldinfo;
91
92 /* keywords used for load and load-from-port surbs */
93 static ScmObj key_error_if_not_found = SCM_UNBOUND;
94 static ScmObj key_macro = SCM_UNBOUND;
95 static ScmObj key_ignore_coding = SCM_UNBOUND;
96 static ScmObj key_paths = SCM_UNBOUND;
97 static ScmObj key_environment = SCM_UNBOUND;
98 static ScmObj key_main_script = SCM_UNBOUND;
99
100 #define PARAM_REF(vm, loc) Scm_PrimitiveParameterRef(vm, ldinfo.loc)
101
102 /*
103 * ScmLoadPacket is the way to communicate to Scm_Load facility.
104 */
105
106 /* small utility. initializes OUT fields of the load packet. */
107 static void load_packet_prepare(ScmLoadPacket *packet)
108 {
109 if (packet) {
110 packet->exception = SCM_FALSE;
111 packet->loaded = FALSE;
112 }
113 }
114
115 /* for applications to initialize ScmLoadPacket before passing it to
116 Scm_Load or Scm_LoadFromPort. As of 0.9, ScmLoadPacket only has
117 fields to be filled by those APIs, so applications don't need to
118 initialize it explicitly. However, it is possible in future that
119 we add some fields to pass info from applications to APIs, in which
120 case it is necessary for this function to set appropriate initial
121 values for such fields. */
122 void Scm_LoadPacketInit(ScmLoadPacket *p)
123 {
124 load_packet_prepare(p);
125 }
126
127 /*--------------------------------------------------------------------
128 * Scm_LoadFromPort
129 *
130 * The most basic function in the load()-family. Read an expression
131 * from the given port and evaluates it repeatedly, until it reaches
132 * EOF. Then the port is closed. The port is locked by the calling
133 * thread until the operation terminates.
134 *
135 * The result of the last evaluation remains on VM.
136 *
137 * No matter how the load terminates, either normal or abnormal,
138 * the port is closed, and the current module is restored to the
139 * one when load is called.
140 *
141 * FLAGS argument is ignored for now, but reserved for future
142 * extension. SCM_LOAD_QUIET_NOFILE and SCM_LOAD_IGNORE_CODING
143 * won't have any effect for LoadFromPort; see Scm_Load below.
144 *
145 * TODO: if we're using coding-aware port, how should we propagate
146 * locking into the wrapped (original) port?
147 */
148
149 int Scm_LoadFromPort(ScmPort *port, u_long flags, ScmLoadPacket *packet)
150 {
151 static ScmObj load_from_port = SCM_UNDEFINED;
152 ScmObj args = SCM_NIL;
153 SCM_BIND_PROC(load_from_port, "load-from-port", Scm_GaucheModule());
154 load_packet_prepare(packet);
155
156 args = Scm_Cons(SCM_OBJ(port), args);
157
158 if (flags&SCM_LOAD_PROPAGATE_ERROR) {
159 Scm_ApplyRec(load_from_port, args);
160 if (packet) packet->loaded = TRUE;
161 return 0;
162 } else {
163 ScmEvalPacket eresult;
164 int r = Scm_Apply(load_from_port, args, &eresult);
165 if (packet) {
166 packet->exception = eresult.exception;
167 packet->loaded = (r >= 0);
168 }
169 return (r < 0)? -1 : 0;
170 }
171 }
172
173 /*---------------------------------------------------------------------
174 * Scm_Load
175 * Scm_VMLoad
176 *
177 * Scheme's load().
178 *
179 * filename - name of the file. can be sans suffix.
180 * load_paths - list of pathnames or #f. If #f, system's load path
181 * is used.
182 * env - a module where the forms are evaluated, or #f.
183 * If #f, the current module is used.
184 * flags - combination of ScmLoadFlags.
185 */
186
187 /* The real `load' function is moved to Scheme. This is a C stub to
188 call it. */
189 ScmObj Scm_VMLoad(ScmString *filename, ScmObj paths, ScmObj env, int flags)
190 {
191 ScmObj opts = SCM_NIL;
192 static ScmObj load_proc = SCM_UNDEFINED;
193 SCM_BIND_PROC(load_proc, "load", Scm_SchemeModule());
194
195 if (flags&SCM_LOAD_QUIET_NOFILE) {
196 opts = Scm_Cons(key_error_if_not_found, Scm_Cons(SCM_FALSE, opts));
197 }
198 if (flags&SCM_LOAD_IGNORE_CODING) {
199 opts = Scm_Cons(key_ignore_coding, Scm_Cons(SCM_TRUE, opts));
200 }
201 if (flags&SCM_LOAD_MAIN_SCRIPT) {
202 opts = Scm_Cons(key_main_script, Scm_Cons(SCM_TRUE, opts));
203 }
204 if (SCM_NULLP(paths) || SCM_PAIRP(paths)) {
205 opts = Scm_Cons(key_paths, Scm_Cons(paths, opts));
206 }
207 if (!SCM_FALSEP(env)) {
208 opts = Scm_Cons(key_environment, Scm_Cons(env, opts));
209 }
210 return Scm_VMApply(load_proc, Scm_Cons(SCM_OBJ(filename), opts));
211 }
212
213 int Scm_Load(const char *cpath, u_long flags, ScmLoadPacket *packet)
214 {
215 static ScmObj load_proc = SCM_UNDEFINED;
216 ScmObj f = SCM_MAKE_STR_COPYING(cpath);
217 ScmObj opts = SCM_NIL;
218 SCM_BIND_PROC(load_proc, "load", Scm_SchemeModule());
219
220 if (flags&SCM_LOAD_QUIET_NOFILE) {
221 opts = Scm_Cons(key_error_if_not_found, Scm_Cons(SCM_FALSE, opts));
222 }
223 if (flags&SCM_LOAD_IGNORE_CODING) {
224 opts = Scm_Cons(key_ignore_coding, Scm_Cons(SCM_TRUE, opts));
225 }
226 if (flags&SCM_LOAD_MAIN_SCRIPT) {
227 opts = Scm_Cons(key_main_script, Scm_Cons(SCM_TRUE, opts));
228 }
229
230 load_packet_prepare(packet);
231 if (flags&SCM_LOAD_PROPAGATE_ERROR) {
232 ScmObj r = Scm_ApplyRec(load_proc, Scm_Cons(f, opts));
233 if (packet) {
234 packet->loaded = !SCM_FALSEP(r);
235 }
236 return 0;
237 } else {
238 ScmEvalPacket eresult;
239 int r = Scm_Apply(load_proc, Scm_Cons(f, opts), &eresult);
240 if (packet) {
241 packet->exception = eresult.exception;
242 packet->loaded = (r > 0 && !SCM_FALSEP(eresult.results[0]));
243 }
244 return (r >= 0)? 0 : -1;
245 }
246 }
247
248 /* A convenience routine */
249 int Scm_LoadFromCString(const char *program, u_long flags, ScmLoadPacket *p)
250 {
251 ScmObj ip = Scm_MakeInputStringPort(SCM_STRING(SCM_MAKE_STR(program)), TRUE);
252 return Scm_LoadFromPort(SCM_PORT(ip), flags, p);
253 }
254
255
256 /*
257 * Utilities
258 */
259
260 ScmObj Scm_GetLoadPath(void)
261 {
262 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.path_mutex);
263 ScmObj paths = Scm_CopyList(Scm_GlocGetValue(ldinfo.load_path_rec));
264 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.path_mutex);
265 return paths;
266 }
267
268 ScmObj Scm_GetDynLoadPath(void)
269 {
270 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.path_mutex);
271 ScmObj paths = Scm_CopyList(Scm_GlocGetValue(ldinfo.dynload_path_rec));
272 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.path_mutex);
273 return paths;
274 }
275
276 static ScmObj break_env_paths(const char *envname)
277 {
278 const char *e = Scm_GetEnv(envname);
279 #ifndef GAUCHE_WINDOWS
280 char delim = ':';
281 #else /*GAUCHE_WINDOWS*/
282 char delim = ';';
283 #endif /*GAUCHE_WINDOWS*/
284
285 if (e == NULL || strlen(e) == 0) {
286 return SCM_NIL;
287 } else if (Scm_IsSugid()) {
288 /* don't trust env when setugid'd */
289 return SCM_NIL;
290 } else {
291 return Scm_StringSplitByChar(SCM_STRING(SCM_MAKE_STR_COPYING(e)),
292 delim);
293 }
294 }
295
296 static void add_gloc_list_item(ScmGloc *gloc, ScmObj item, int afterp)
297 {
298 ScmObj vs = Scm_GlocGetValue(gloc);
299 ScmObj r = afterp? Scm_Append2(vs, SCM_LIST1(item)) : Scm_Cons(item, vs);
300 Scm_GlocSetValue(gloc, r);
301 }
302
303 /* Add CPATH to the current list of load path. The path is
304 * added before the current list, unless AFTERP is true.
305 * The existence of CPATH is not checked.
306 *
307 * Besides load paths, existence of directories CPATH/$ARCH and
308 * CPATH/../$ARCH is checked, where $ARCH is the system architecture
309 * signature, and if found, it is added to the dynload_path. If
310 * no such directory is found, CPATH itself is added to the dynload_path.
311 */
312 ScmObj Scm_AddLoadPath(const char *cpath, int afterp)
313 {
314 ScmObj spath = SCM_MAKE_STR_COPYING(cpath);
315 ScmStat statbuf;
316
317 /* check dynload path */
318 ScmObj dpath = Scm_StringAppendC(SCM_STRING(spath), "/", 1, 1);
319 dpath = Scm_StringAppendC(SCM_STRING(dpath), Scm_HostArchitecture(),-1,-1);
320 if (stat(Scm_GetStringConst(SCM_STRING(dpath)), &statbuf) < 0
321 || !S_ISDIR(statbuf.st_mode)) {
322 dpath = Scm_StringAppendC(SCM_STRING(spath), "/../", 4, 4);
323 dpath = Scm_StringAppendC(SCM_STRING(dpath), Scm_HostArchitecture(),-1,-1);
324 if (stat(Scm_GetStringConst(SCM_STRING(dpath)), &statbuf) < 0
325 || !S_ISDIR(statbuf.st_mode)) {
326 dpath = spath;
327 }
328 }
329
330 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.path_mutex);
331 add_gloc_list_item(ldinfo.load_path_rec, spath, afterp);
332 add_gloc_list_item(ldinfo.dynload_path_rec, dpath, afterp);
333 ScmObj r = Scm_GlocGetValue(ldinfo.load_path_rec);
334 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.path_mutex);
335
336 return r;
337 }
338
339 void Scm_AddLoadPathHook(ScmObj proc, int afterp)
340 {
341 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.path_mutex);
342 add_gloc_list_item(ldinfo.load_path_hooks_rec, proc, afterp);
343 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.path_mutex);
344 }
345
346 void Scm_DeleteLoadPathHook(ScmObj proc)
347 {
348 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.path_mutex);
349 /* we should use Scm_Delete, instead of Scm_DeleteX,
350 to avoid race with reader of the list */
351 Scm_GlocSetValue(ldinfo.load_path_hooks_rec,
352 Scm_Delete(proc, Scm_GlocGetValue(ldinfo.load_path_hooks_rec),
353 SCM_CMP_EQ));
354 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.path_mutex);
355 }
356
357 /*------------------------------------------------------------------
358 * Dynamic linking
359 */
360
361 /* The API to load object file dynamically differ among platforms.
362 * We include the platform-dependent implementations (dl_*.c) that
363 * provides a common API:
364 *
365 * void *dl_open(const char *pathname)
366 * Dynamically loads the object file specified by PATHNAME,
367 * and returns its handle. On failure, returns NULL.
368 *
369 * PATHNAME is guaranteed to contain directory names, so this function
370 * doesn't need to look it up in the search paths.
371 * The caller also checks whether pathname is already loaded or not,
372 * so this function doesn't need to worry about duplicate loads.
373 * This function should have the semantics equivalent to the
374 * RTLD_NOW|RTLD_GLOBAL of dlopen().
375 *
376 * We don't call with NULL as PATHNAME; dlopen() returns the handle
377 * of the calling program itself in such a case, but we never need that
378 * behavior.
379 *
380 * ScmDynLoadEntry dl_sym(void *handle, const char *symbol)
381 * Finds the address of SYMBOL in the dl_openModule()-ed module
382 * HANDLE.
383 *
384 * void dl_close(void *handle)
385 * Closes the opened module. This can only be called when we couldn't
386 * find the initialization function in the module; once the initialization
387 * function is called, we don't have a safe way to remove the module.
388 *
389 * const char *dl_error(void)
390 * Returns the last error occurred on HANDLE in the dl_* function.
391 *
392 * Notes:
393 * - The caller must take care of mutex so that dl_ won't be called from
394 * more than one thread at a time, and no other thread calls
395 * dl_* functions between dl_open and dl_error (so that dl_open
396 * can store the error info in global variable).
397 *
398 * Since this API assumes the caller does a lot of work, the implementation
399 * should be much simpler than implementing fully dlopen()-compatible
400 * functions.
401 */
402
403 /* The implementation of dynamic loader is a bit complicated in the presence
404 of multiple threads and multiple initialization routines.
405
406 We keep ScmDLObj record for each DYNAMIC-LOADed files (keyed
407 by pathname including suffix) to track the state of loading. The thread
408 must lock the structure first to operate on the particluar DSO.
409
410 By default, a DSO has one initialization function (initfn) whose name
411 can be derived from DSO's basename (if DSO is /foo/bar/baz.so, the
412 initfn is Scm_Init_baz). DSO may have more than one initfn, if it is
413 made from multiple Scheme files via precompiler; in which case, each
414 initfn initializes a part of DSO corresponding to a Scheme module.
415 Each *.sci file contains dynamic-load form of the DSO with :init-function
416 keyword arguments.
417 */
418
419 typedef void (*ScmDynLoadEntry)(void); /* Dynamically loaded function pointer */
420
421 struct ScmDLObjRec {
422 SCM_HEADER;
423 ScmString *path; /* pathname for DSO, including suffix */
424 int loaded; /* TRUE if this DSO is already loaded.
425 It may need to be initialized, though.
426 Check initfns. */
427 void *handle; /* whatever dl_open returned */
428 ScmVM *loader; /* The VM that's holding the lock to operate
429 on this DLO. */
430 ScmHashCore entries; /* name -> <foreign-pointer> */
431 ScmInternalMutex mutex;
432 ScmInternalCond cv;
433 };
434
435 static void dlobj_print(ScmObj obj, ScmPort *sink,
436 ScmWriteContext *mode SCM_UNUSED)
437 {
438 Scm_Printf(sink, "#<dlobj %S>", SCM_DLOBJ(obj)->path);
439 }
440
441 SCM_DEFINE_BUILTIN_CLASS_SIMPLE(Scm_DLObjClass, dlobj_print);
442
443 static ScmDLObj *make_dlobj(ScmString *path)
444 {
445 ScmDLObj *z = SCM_NEW(ScmDLObj);
446 SCM_SET_CLASS(z, &Scm_DLObjClass);
447 z->path = path;
448 z->loader = NULL;
449 z->loaded = FALSE;
450 z->handle = NULL;
451 Scm_HashCoreInitSimple(&z->entries, SCM_HASH_STRING, 0, NULL);
452 (void)SCM_INTERNAL_MUTEX_INIT(z->mutex);
453 (void)SCM_INTERNAL_COND_INIT(z->cv);
454 return z;
455 }
456
457 /* NB: we rely on dlcompat library for dlopen instead of using dl_darwin.c
458 for now; Boehm GC requires dlopen when compiled with pthread, so there's
459 not much point to avoid dlopen here. */
460 #if defined(HAVE_DLOPEN)
461 #include "dl_dlopen.c"
462 #elif defined(GAUCHE_WINDOWS)
463 #include "dl_win.c"
464 #else
465 #include "dl_dummy.c"
466 #endif
467
468 /* Find dlobj with path, creating one if there aren't, and returns it. */
469 static ScmDLObj *find_dlobj(ScmObj path)
470 {
471 ScmDLObj *z = NULL;
472
473 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.dso_mutex);
474 ScmObj p = Scm_HashTableRef(ldinfo.dso_table, path, SCM_FALSE);
475 if (SCM_DLOBJP(p)) {
476 z = SCM_DLOBJ(p);
477 } else {
478 z = make_dlobj(SCM_STRING(path));
479 Scm_HashTableSet(ldinfo.dso_table, path, SCM_OBJ(z), 0);
480 }
481 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.dso_mutex);
482 return z;
483 }
484
485 static void lock_dlobj(ScmDLObj *dlo)
486 {
487 ScmVM *vm = Scm_VM();
488 (void)SCM_INTERNAL_MUTEX_LOCK(dlo->mutex);
489 while (dlo->loader != vm) {
490 if (dlo->loader == NULL) break;
491 (void)SCM_INTERNAL_COND_WAIT(dlo->cv, dlo->mutex);
492 }
493 dlo->loader = vm;
494 (void)SCM_INTERNAL_MUTEX_UNLOCK(dlo->mutex);
495 }
496
497 static void unlock_dlobj(ScmDLObj *dlo)
498 {
499 (void)SCM_INTERNAL_MUTEX_LOCK(dlo->mutex);
500 dlo->loader = NULL;
501 (void)SCM_INTERNAL_COND_BROADCAST(dlo->cv);
502 (void)SCM_INTERNAL_MUTEX_UNLOCK(dlo->mutex);
503 }
504
505 /* Find NAME in the looked-up entries.
506 NAME must begin with '_'.
507 Assuming the caller holding the lock of DLO. */
508 static ScmObj find_entry(ScmDLObj *dlo, ScmString *name)
509 {
510 ScmDictEntry *e = Scm_HashCoreSearch(&dlo->entries, (intptr_t)name,
511 SCM_DICT_GET);
512 if (e) return SCM_DICT_VALUE(e);
513 else return SCM_FALSE;
514 }
515
516 /* Register name => fptr entry in dlo. Assuming the caller holding the
517 lock of DLO. Returns a foreign pointer wrapping ptr. */
518 static ScmObj add_entry(ScmDLObj *dlo, ScmString *name, void *ptr)
519 {
520 ScmObj fptr = Scm_MakeForeignPointer(ldinfo.dlptr_class, ptr);
521 Scm_ForeignPointerAttrSet(SCM_FOREIGN_POINTER(fptr),
522 SCM_SYM_NAME, SCM_OBJ(name));
523 ScmDictEntry *e = Scm_HashCoreSearch(&dlo->entries, (intptr_t)name,
524 SCM_DICT_CREATE);
525 (void)SCM_DICT_SET_VALUE(e, fptr);
526 return fptr;
527 }
528
529 /* lookup the symbol within DLO.
530 NAME must begin with '_'. We look up both with and without '_'.
531 Assuming the caller holding the lock of OBJ. */
532 static ScmObj lookup_entry(ScmDLObj *dlo, ScmString *name)
533 {
534 ScmObj fptr = find_entry(dlo, name);
535 if (SCM_FALSEP(fptr)) {
536 /* locate the entry. Name always has '_'. Whether the actual
537 symbol dl_sym returns has '_' or not depends on the platform,
538 so we first try without '_', then '_'. */
539 const char *cname = Scm_GetStringConst(name);
540 void *ptr = dl_sym(dlo->handle, cname+1);
541 if (ptr == NULL) {
542 ptr = dl_sym(dlo->handle, cname);
543 if (ptr == NULL) {
544 return SCM_FALSE; /* not found */
545 }
546 }
547 fptr = add_entry(dlo, name, ptr);
548 }
549 return fptr;
550 }
551
552 /* Load the DSO. The caller holds the lock of dlobj. May throw an error;
553 the caller makes sure it releases the lock even in that case. */
554 static void load_dlo(ScmDLObj *dlo)
555 {
556 ScmVM *vm = Scm_VM();
557 if (SCM_VM_RUNTIME_FLAG_IS_SET(vm, SCM_LOAD_VERBOSE)) {
558 int len = Scm_Length(PARAM_REF(vm, load_history));
559 SCM_PUTZ(";;", 2, SCM_CURERR);
560 while (len-- > 0) Scm_Putz(" ", 2, SCM_CURERR);
561 Scm_Printf(SCM_CURERR, "Dynamically Loading %A...\n", dlo->path);
562 }
563 dlo->handle = dl_open(Scm_GetStringConst(dlo->path));
564 if (dlo->handle == NULL) {
565 const char *err = dl_error();
566 if (err == NULL) {
567 Scm_Error("failed to link %A dynamically", dlo->path);
568 } else {
569 Scm_Error("failed to link %A dynamically: %s", dlo->path, err);
570 }
571 /*NOTREACHED*/
572 }
573 dlo->loaded = TRUE;
574 }
575
576 /* Call the DSO's initfn. The caller holds the lock of dlobj, and responsible
577 to release the lock even when this fn throws an error. */
578 static void call_initfn(ScmDLObj *dlo, ScmString *name)
579 {
580 ScmObj fptr = lookup_entry(dlo, name);
581
582 if (!SCM_FOREIGN_POINTER_P(fptr)) {
583 dl_close(dlo->handle);
584 dlo->handle = NULL;
585 dlo->loaded = FALSE;
586 Scm_Error("dynamic linking of %A failed: "
587 "couldn't find initialization function %S",
588 dlo->path, name);
589 }
590
591 if (!SCM_FALSEP(Scm_ForeignPointerAttrGet(SCM_FOREIGN_POINTER(fptr),
592 SCM_SYM_CALLED, SCM_FALSE))) {
593 return;
594 }
595
596 /* Call initialization function. note that there can be arbitrary
597 complex stuff done within func(), including evaluation of
598 Scheme procedures and/or calling dynamic-load for other
599 object. There's a chance that, with some contrived case,
600 func() can trigger the dynamic loading of the same file we're
601 loading right now. However, if the code follows the Gauche's
602 standard module structure, such circular dependency is detected
603 by Scm_Load, so we don't worry about it here. */
604 ScmDynLoadEntry fn = SCM_FOREIGN_POINTER_REF(ScmDynLoadEntry, fptr);
605 fn();
606 Scm_ForeignPointerAttrSet(SCM_FOREIGN_POINTER(fptr),
607 SCM_SYM_NAME, SCM_TRUE);
608 }
609
610 /* Experimental: Prelink feature---we allow the extension module to be
611 statically linked, and (dynamic-load DSONAME) merely calls initfn.
612 The application needs to call Scm_RegisterPrelinked to tell the system
613 which DSO is statically linked. We pretend that the named DSO is
614 already loaded from a pseudo pathname "@/DSONAME" (e.g. for
615 "gauche--collection", we use "@/gauche--collection".) */
616
617 /* Register DSONAME as prelinked. DSONAME shouldn't have system's suffix.
618 INITFNS is an array of function pointers, NULL terminated.
619 INITFN_NAMES should have prefixed with '_', for call_initfn() searches
620 names with '_' first. */
621 void Scm_RegisterPrelinked(ScmString *dsoname,
622 const char *initfn_names[],
623 ScmDynLoadEntry initfns[])
624 {
625 ScmObj path = Scm_StringAppend2(SCM_STRING(SCM_MAKE_STR_IMMUTABLE("@/")),
626 dsoname);
627 ScmDLObj *dlo = find_dlobj(path);
628 dlo->loaded = TRUE;
629
630 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.dso_mutex);
631 for (int i=0; initfns[i] && initfn_names[i]; i++) {
632 add_entry(dlo, SCM_STRING(SCM_MAKE_STR_IMMUTABLE(initfn_names[i])),
633 initfns[i]);
634 }
635 ldinfo.dso_prelinked = Scm_Cons(SCM_OBJ(dsoname), ldinfo.dso_prelinked);
636 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.dso_mutex);
637 }
638
639 static ScmObj find_prelinked(ScmString *dsoname)
640 {
641 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.dso_mutex);
642 /* in general it is dangerous to invoke equal?-comparison during lock,
643 but in this case we know they're string comparison and won't raise
644 an error. */
645 ScmObj z = Scm_Member(SCM_OBJ(dsoname), ldinfo.dso_prelinked, SCM_CMP_EQUAL);
646 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.dso_mutex);
647 if (!SCM_FALSEP(z)) {
648 return Scm_StringAppend2(SCM_STRING(SCM_MAKE_STR_IMMUTABLE("@/")),
649 dsoname);
650 } else {
651 return SCM_FALSE;
652 }
653 }
654
655 /* Dynamically load the specified object by DSONAME.
656 DSONAME must not contain the system's suffix (.so, for example).
657 The same name of DSO can be only loaded once.
658
659 A DSO may contain multiple initialization functions (initfns), in
660 which case each initfn is called at most once.
661
662 If INITFN is SCM_TRUE, the name of initialization function is derived
663 from the DSO name (see %get-initfn-name in libeval.scm). This is
664 the default value of 'dynamic-load'.
665
666 If INITFN is SCM_FALSE, the initialization function won't be called.
667 It is to load DSO for FFI.
668 */
669 ScmObj Scm_DynLoad(ScmString *dsoname, ScmObj initfn,
670 u_long flags SCM_UNUSED /*reserved*/)
671 {
672 ScmObj dsopath = find_prelinked(dsoname);
673 if (SCM_FALSEP(dsopath)) {
674 static ScmObj find_load_file_proc = SCM_UNDEFINED;
675 SCM_BIND_PROC(find_load_file_proc, "find-load-file",
676 Scm_GaucheInternalModule());
677 ScmObj spath = Scm_ApplyRec3(find_load_file_proc,
678 SCM_OBJ(dsoname),
679 Scm_GetDynLoadPath(),
680 ldinfo.dso_suffixes);
681 if (!SCM_PAIRP(spath)) {
682 Scm_Error("can't find dlopen-able module %S", dsoname);
683 }
684 dsopath = SCM_CAR(spath);
685 SCM_ASSERT(SCM_STRINGP(dsopath));
686 }
687
688 ScmObj initname = SCM_FALSE;
689
690 if (SCM_EQ(initfn, SCM_TRUE) || SCM_STRINGP(initfn)) {
691 static ScmObj get_initfn_name_proc = SCM_UNDEFINED;
692 SCM_BIND_PROC(get_initfn_name_proc, "%get-initfn-name",
693 Scm_GaucheInternalModule());
694 initname = Scm_ApplyRec2(get_initfn_name_proc, initfn, dsopath);
695 } else if (!SCM_FALSEP(initfn)) {
696 SCM_TYPE_ERROR(initfn, "a string or a boolean");
697 }
698
699 ScmDLObj *dlo = find_dlobj(dsopath);
700
701 /* Load the dlobj if necessary. */
702 lock_dlobj(dlo);
703 if (!dlo->loaded) {
704 SCM_UNWIND_PROTECT { load_dlo(dlo); }
705 SCM_WHEN_ERROR { unlock_dlobj(dlo); SCM_NEXT_HANDLER; }
706 SCM_END_PROTECT;
707 }
708
709 /* Now the dlo is loaded. We need to call initializer. */
710 SCM_ASSERT(dlo->loaded);
711
712 if (SCM_STRINGP(initname)) {
713 SCM_UNWIND_PROTECT { call_initfn(dlo, SCM_STRING(initname)); }
714 SCM_WHEN_ERROR { unlock_dlobj(dlo); SCM_NEXT_HANDLER; }
715 SCM_END_PROTECT;
716 }
717
718 unlock_dlobj(dlo);
719 return SCM_OBJ(dlo);
720 }
721
722 /* Expose dlobj to Scheme world */
723
724 static ScmObj dlobj_path_get(ScmObj obj)
725 {
726 return SCM_OBJ(SCM_DLOBJ(obj)->path);
727 }
728
729 static ScmObj dlobj_loaded_get(ScmObj obj)
730 {
731 return SCM_MAKE_BOOL(SCM_DLOBJ(obj)->loaded);
732 }
733
734 static ScmObj dlobj_entries_get(ScmObj obj)
735 {
736 ScmObj h = SCM_NIL;
737 ScmObj t = SCM_NIL;
738 ScmDLObj *dlo = SCM_DLOBJ(obj);
739 ScmHashIter iter;
740
741 lock_dlobj(SCM_DLOBJ(obj));
742 Scm_HashIterInit(&iter, &dlo->entries);
743 for (;;) {
744 ScmDictEntry *e = Scm_HashIterNext(&iter);
745 if (e == NULL) break;
746 SCM_APPEND1(h, t, SCM_DICT_VALUE(e));
747 }
748 unlock_dlobj(SCM_DLOBJ(obj));
749 return h;
750 }
751
752 static ScmClassStaticSlotSpec dlobj_slots[] = {
753 SCM_CLASS_SLOT_SPEC("path", dlobj_path_get, NULL),
754 SCM_CLASS_SLOT_SPEC("loaded?", dlobj_loaded_get, NULL),
755 SCM_CLASS_SLOT_SPEC("entries", dlobj_entries_get, NULL),
756 SCM_CLASS_SLOT_SPEC_END()
757 };
758
759 ScmObj Scm_DLObjs()
760 {
761 ScmObj z = SCM_NIL;
762 ScmHashIter iter;
763 ScmDictEntry *e;
764 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.dso_mutex);
765 Scm_HashIterInit(&iter, SCM_HASH_TABLE_CORE(ldinfo.dso_table));
766 while ((e = Scm_HashIterNext(&iter)) != NULL) {
767 z = Scm_Cons(SCM_OBJ(SCM_DICT_VALUE(e)), z);
768 }
769 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.dso_mutex);
770 return z;
771 }
772
773 /* name should have '_' prefix. We look for a symbol with and without it.
774 Returns a foreign pointer or #f. */
775 ScmObj Scm_DLOGetEntryAddress(ScmDLObj *dlo, ScmString *name)
776 {
777 lock_dlobj(dlo);
778 ScmObj fptr = lookup_entry(dlo, name);
779 unlock_dlobj(dlo);
780 return fptr;
781 }
782
783 /* dlptr interface (we don't expose <dlptr> class pointer */
784 int Scm_DLPtrP(ScmObj obj)
785 {
786 return SCM_XTYPEP(obj, ldinfo.dlptr_class);
787 }
788
789 ScmObj Scm_DLPtrValue(ScmObj obj)
790 {
791 if (!Scm_DLPtrP(obj)) {
792 SCM_TYPE_ERROR(obj, "dlptr");
793 }
794 intptr_t val = SCM_FOREIGN_POINTER_REF(intptr_t, obj);
795 return Scm_IntptrToInteger(val);
796 }
797
798 /*------------------------------------------------------------------
799 * Require and provide
800 */
801
802 /* STk's require takes a string. SLIB's require takes a symbol.
803 For now, I allow only a string. */
804 /* Note that require and provide is recognized at compile time. */
805
806 static int do_require(ScmObj, int, ScmModule *, ScmLoadPacket *);
807
808 /* [Preventing Race Condition]
809 *
810 * Besides the list of provided features (ldinfo.provided), the
811 * system keeps two kind of global assoc list for transient information.
812 *
813 * ldinfo.providing keeps a list of (<feature> <thread> <provided> ...),
814 * where <thread> is currently loading a file for <feature>.
815 * ldinfo.waiting keeps a list of (<thread> . <feature>), where
816 * <thread> is waiting for <feature> to be provided.
817 * (The <provided> list is pushed by 'provide' while loading <feature>.
818 * It is used for autprovide feature. See below).
819 *
820 * Scm_Require first checks ldinfo.provided list; if the feature is
821 * already provided, no problem; just return.
822 * If not, ldinfo.providing is searched. If the feature is being provided
823 * by some other thread, the calling thread pushes itself onto
824 * ldinfo.waiting list and waits for the feature to be provided.
825 *
826 * There may be a case that the feature dependency forms a loop because
827 * of a bug. An error should be signaled in such a case, rather than going
828 * to deadlock. So, when the calling thread finds the required feature
829 * is in the ldinfo.providing alist, it checks the waiting chain of
830 * features, and no threads are waiting for a feature being provided by
831 * the calling thread.
832 *
833 * When the above checks are all false, the calling thread is responsible
834 * to load the required feature. It pushes the feature and itself
835 * onto the providing list and start loading the file.
836 *
837 * [Autoprovide Feature]
838 *
839 * When a file is loaded via 'require', it almost always provides the
840 * required feature. Thus we allow the file to omit the 'provide' form.
841 * That is, if a file X.scm is loaded because of (require "X"), and
842 * there's no 'provide' form in X.scm, the feature "X" is automatically
843 * provided upon a successful loading of X.scm.
844 *
845 * If a 'provide' form appears in X.scm, the autoprovide feature is
846 * turned off. It is allowed that X.scm provides features other than
847 * "X". As a special case, (provide #f) causes the autoprovide feature
848 * to be turned of without providing any feature.
849 *
850 * To track what is provided, the 'provide' form pushes its argument
851 * to the entry of 'providing' list whose thread matches the calling
852 * thread. (It is possible that there's more than one entry in the
853 * 'providing' list, for a required file may call another require form.
854 * The entry is always pushed at the beginning of the providing list,
855 * we know that the first matching entry is the current one.)
856 */
857
858 /* NB: It has never been explicit, but 'require' and 'extend' are expected to
859 work as if we load the module into #<module gauche>. Those forms only loads
860 the file once, so it doesn't make much sense to allow it to load into
861 different modules for each time, since you never know whether the file
862 is loaded at this time or it has already been loaded. With the same
863 reason, it doesn't make much sense to use the current module.
864
865 On 0.9.4 we always set the base module to #<module gauche> to do require,
866 so that we can guarantee the forms like define-module or define-library
867 to be visible from the loaded module (if we use the caller's current
868 module it is not guaranteed.) However, it had an unexpected side
869 effect: If the loaded module inserts toplevel definitions or imports
870 other modules without first setting its own module, it actually
871 modifies #<module gauche>.
872
873 As of 0.9.5, we use an immutable module #<module gauche.require-base>
874 as the base module. Since it is immutable, any toplevel definitions
875 or imports without first switching modules are rejected.
876 */
877 int Scm_Require(ScmObj feature, int flags, ScmLoadPacket *packet)
878 {
879 return do_require(feature, flags, Scm__RequireBaseModule(), packet);
880 }
881
882 /* Called when load fails during require. We need to reset the providing
883 chain.*/
884 static inline void require_error_cleanup(ScmVM *vm,
885 ScmObj feature,
886 ScmModule *prev_mod)
887 {
888 vm->module = prev_mod;
889 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.prov_mutex);
890 ldinfo.providing = Scm_AssocDeleteX(feature, ldinfo.providing, SCM_CMP_EQUAL);
891 (void)SCM_INTERNAL_COND_BROADCAST(ldinfo.prov_cv);
892 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.prov_mutex);
893 }
894
895 int do_require(ScmObj feature, int flags, ScmModule *base_mod,
896 ScmLoadPacket *packet)
897 {
898 ScmVM *vm = Scm_VM();
899 ScmObj provided;
900 int loop = FALSE;
901
902 load_packet_prepare(packet);
903 if (!SCM_STRINGP(feature)) {
904 ScmObj e = Scm_MakeError(Scm_Sprintf("require: string expected, but got %S\n", feature));
905 if (flags&SCM_LOAD_PROPAGATE_ERROR) Scm_Raise(e, 0);
906 else {
907 if (packet) packet->exception = e;
908 return -1;
909 }
910 }
911
912 /* Check provided, providing and waiting list. See the comment above. */
913 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.prov_mutex);
914 for (;;) {
915 provided = Scm_Member(feature, ldinfo.provided, SCM_CMP_EQUAL);
916 if (!SCM_FALSEP(provided)) break;
917 ScmObj providing = Scm_Assoc(feature, ldinfo.providing, SCM_CMP_EQUAL);
918 if (SCM_FALSEP(providing)) break;
919
920 /* Checks for dependencies */
921 ScmObj p = providing;
922 SCM_ASSERT(SCM_PAIRP(p) && SCM_PAIRP(SCM_CDR(p)));
923 if (SCM_CADR(p) == SCM_OBJ(vm)) { loop = TRUE; break; }
924
925 for (;;) {
926 ScmObj q = Scm_Assq(SCM_CDR(p), ldinfo.waiting);
927 if (SCM_FALSEP(q)) break;
928 SCM_ASSERT(SCM_PAIRP(q));
929 p = Scm_Assoc(SCM_CDR(q), ldinfo.providing, SCM_CMP_EQUAL);
930 SCM_ASSERT(SCM_PAIRP(p) && SCM_PAIRP(SCM_CDR(p)));
931 if (SCM_CADR(p) == SCM_OBJ(vm)) { loop = TRUE; break; }
932 }
933 if (loop) break;
934 ldinfo.waiting = Scm_Acons(SCM_OBJ(vm), feature, ldinfo.waiting);
935 (void)SCM_INTERNAL_COND_WAIT(ldinfo.prov_cv, ldinfo.prov_mutex);
936 ldinfo.waiting = Scm_AssocDeleteX(SCM_OBJ(vm), ldinfo.waiting, SCM_CMP_EQ);
937 }
938 if (!loop && SCM_FALSEP(provided)) {
939 ldinfo.providing =
940 Scm_Acons(feature, SCM_LIST1(SCM_OBJ(vm)), ldinfo.providing);
941 }
942 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.prov_mutex);
943
944 if (loop) {
945 ScmObj e = Scm_MakeError(Scm_Sprintf("a loop is detected in the require dependency involving feature %S", feature));
946 if (flags&SCM_LOAD_PROPAGATE_ERROR) Scm_Raise(e, 0);
947 else {
948 if (packet) packet->exception = e;
949 return -1;
950 }
951 }
952
953 if (!SCM_FALSEP(provided)) return 0; /* no work to do */
954 /* Make sure to load the file into base_mod. */
955 ScmLoadPacket xresult;
956 ScmModule *prev_mod = vm->module;
957 vm->module = base_mod;
958
959 /* A bit awkward, but if SCM_LOAD_PROPAGATE_ERROR is given, we don't
960 want to 'stop' the error, for we don't want to lose the stack trace.
961 */
962 if (flags&SCM_LOAD_PROPAGATE_ERROR) {
963 SCM_UNWIND_PROTECT {
964 (void)Scm_Load(Scm_GetStringConst(SCM_STRING(feature)),
965 SCM_LOAD_PROPAGATE_ERROR, &xresult);
966 } SCM_WHEN_ERROR {
967 require_error_cleanup(vm, feature, prev_mod);
968 SCM_NEXT_HANDLER;
969 } SCM_END_PROTECT;
970 } else {
971 int r = Scm_Load(Scm_GetStringConst(SCM_STRING(feature)), 0, &xresult);
972 if (packet) packet->exception = xresult.exception;
973
974 if (r < 0) {
975 require_error_cleanup(vm, feature, prev_mod);
976 return -1;
977 }
978 }
979 vm->module = prev_mod;
980
981 /* Success */
982 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.prov_mutex);
983 ScmObj p = Scm_Assoc(feature, ldinfo.providing, SCM_CMP_EQUAL);
984 ldinfo.providing = Scm_AssocDeleteX(feature, ldinfo.providing, SCM_CMP_EQUAL);
985 /* `Autoprovide' feature */
986 if (SCM_NULLP(SCM_CDDR(p))
987 && SCM_FALSEP(Scm_Member(feature, ldinfo.provided, SCM_CMP_EQUAL))) {
988 ldinfo.provided = Scm_Cons(feature, ldinfo.provided);
989 }
990 (void)SCM_INTERNAL_COND_BROADCAST(ldinfo.prov_cv);
991 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.prov_mutex);
992 if (packet) packet->loaded = TRUE;
993 return 0;
994 }
995
996 ScmObj Scm_Provide(ScmObj feature)
997 {
998 ScmVM *self = Scm_VM();
999
1000 if (!SCM_STRINGP(feature)&&!SCM_FALSEP(feature)) {
1001 SCM_TYPE_ERROR(feature, "string");
1002 }
1003 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.prov_mutex);
1004 if (SCM_STRINGP(feature)
1005 && SCM_FALSEP(Scm_Member(feature, ldinfo.provided, SCM_CMP_EQUAL))) {
1006 ldinfo.provided = Scm_Cons(feature, ldinfo.provided);
1007 }
1008 ScmObj cp;
1009 SCM_FOR_EACH(cp, ldinfo.providing) {
1010 if (SCM_CADR(SCM_CAR(cp)) == SCM_OBJ(self)) {
1011 SCM_SET_CDR_UNCHECKED(SCM_CDR(SCM_CAR(cp)), SCM_LIST1(feature));
1012 break;
1013 }
1014 }
1015 (void)SCM_INTERNAL_COND_SIGNAL(ldinfo.prov_cv);
1016 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.prov_mutex);
1017 return feature;
1018 }
1019
1020 int Scm_ProvidedP(ScmObj feature)
1021 {
1022 (void)SCM_INTERNAL_MUTEX_LOCK(ldinfo.prov_mutex);
1023 int r = !SCM_FALSEP(Scm_Member(feature, ldinfo.provided, SCM_CMP_EQUAL));
1024 (void)SCM_INTERNAL_MUTEX_UNLOCK(ldinfo.prov_mutex);
1025 return r;
1026 }
1027
1028 /*------------------------------------------------------------------
1029 * Autoload
1030 */
1031
1032 static void autoload_print(ScmObj obj, ScmPort *out,
1033 ScmWriteContext *ctx SCM_UNUSED)
1034 {
1035 Scm_Printf(out, "#<autoload %A::%A (%A)>",
1036 SCM_AUTOLOAD(obj)->module->name,
1037 SCM_AUTOLOAD(obj)->name, SCM_AUTOLOAD(obj)->path);
1038 }
1039
1040 SCM_DEFINE_BUILTIN_CLASS_SIMPLE(Scm_AutoloadClass, autoload_print);
1041
1042 ScmObj Scm_MakeAutoload(ScmModule *where,
1043 ScmSymbol *name,
1044 ScmString *path,
1045 ScmSymbol *import_from)
1046 {
1047 ScmAutoload *adata = SCM_NEW(ScmAutoload);
1048 SCM_SET_CLASS(adata, SCM_CLASS_AUTOLOAD);
1049 adata->name = name;
1050 adata->module = where;
1051 adata->path = path;
1052 adata->import_from = import_from;
1053 adata->loaded = FALSE;
1054 adata->value = SCM_UNBOUND;
1055 (void)SCM_INTERNAL_MUTEX_INIT(adata->mutex);
1056 (void)SCM_INTERNAL_COND_INIT(adata->cv);
1057 adata->locker = NULL;
1058 return SCM_OBJ(adata);
1059 }
1060
1061 void Scm_DefineAutoload(ScmModule *where,
1062 ScmObj file_or_module,
1063 ScmObj list)
1064 {
1065 ScmString *path = NULL;
1066 ScmSymbol *import_from = NULL;
1067
1068 if (SCM_STRINGP(file_or_module)) {
1069 path = SCM_STRING(file_or_module);
1070 } else if (SCM_SYMBOLP(file_or_module)) {
1071 import_from = SCM_SYMBOL(file_or_module);
1072 path = SCM_STRING(Scm_ModuleNameToPath(import_from));
1073 } else {
1074 Scm_Error("autoload: string or symbol required, but got %S",
1075 file_or_module);
1076 }
1077 ScmObj ep;
1078 SCM_FOR_EACH(ep, list) {
1079 ScmObj entry = SCM_CAR(ep);
1080 if (SCM_SYMBOLP(entry)) {
1081 Scm_Define(where, SCM_SYMBOL(entry),
1082 Scm_MakeAutoload(where, SCM_SYMBOL(entry),
1083 path, import_from));
1084 } else if (SCM_PAIRP(entry)
1085 && SCM_EQ(key_macro, SCM_CAR(entry))
1086 && SCM_PAIRP(SCM_CDR(entry))
1087 && SCM_SYMBOLP(SCM_CADR(entry))) {
1088 ScmSymbol *sym = SCM_SYMBOL(SCM_CADR(entry));
1089 ScmObj autoload = Scm_MakeAutoload(where, sym, path, import_from);
1090 Scm_Define(where, sym,
1091 Scm_MakeMacroAutoload(sym, SCM_AUTOLOAD(autoload)));
1092 } else {
1093 Scm_Error("autoload: bad autoload symbol entry: %S", entry);
1094 }
1095 }
1096 }
1097
1098
1099 ScmObj Scm_ResolveAutoload(ScmAutoload *adata, int flags SCM_UNUSED)
1100 {
1101 int circular = FALSE;
1102 ScmVM *vm = Scm_VM();
1103
1104 /* shortcut in case if somebody else already did the job. */
1105 if (adata->loaded) return adata->value;
1106
1107 /* check to see if this autoload is recursive. if so, we just return
1108 SCM_UNBOUND and let the caller handle the issue (NB: it isn't
1109 necessarily an error. For example, define-method searches if
1110 a generic function of the same name is already defined; if the
1111 name is set autoload and define-method is in the file that's being
1112 autoloaded, define-method finds the name is an autoload that points
1113 the currently autoloaded file.)
1114 we have to be careful to exclude the case that when one thread is
1115 resolving autoload another thread enters here and sees this autoload
1116 is already being resolved.
1117 */
1118 if ((adata->locker == NULL || adata->locker == vm)
1119 && !SCM_FALSEP(Scm_Assoc(SCM_OBJ(adata->path),
1120 ldinfo.providing,
1121 SCM_CMP_EQUAL))) {
1122 return SCM_UNBOUND;
1123 }
1124
1125 /* obtain the lock to load this autoload */
1126 (void)SCM_INTERNAL_MUTEX_LOCK(adata->mutex);
1127 do {
1128 if (adata->loaded) break;
1129 if (adata->locker == NULL) {
1130 adata->locker = vm;
1131 } else if (adata->locker == vm) {
1132 /* bad circular dependency */
1133 circular = TRUE;
1134 } else if (adata->locker->state == SCM_VM_TERMINATED) {
1135 /* the loading thread have died prematurely.
1136 let's take over the task. */
1137 adata->locker = vm;
1138 } else {
1139 (void)SCM_INTERNAL_COND_WAIT(adata->cv, adata->mutex);
1140 continue;
1141 }
1142 } while (0);
1143 SCM_INTERNAL_MUTEX_UNLOCK(adata->mutex);
1144 if (adata->loaded) {
1145 /* ok, somebody did the work for me. just use the result. */
1146 return adata->value;
1147 }
1148
1149 if (circular) {
1150 /* Since we have already checked recursive loading, it isn't normal
1151 if we reach here. Right now I have no idea how this happens, but
1152 just in case we raise an error. */
1153 adata->locker = NULL;
1154 SCM_INTERNAL_COND_BROADCAST(adata->cv);
1155 Scm_Error("Attempted to trigger the same autoload %S#%S recursively. Maybe circular autoload dependency?",
1156 adata->module, adata->name);
1157 }
1158
1159 SCM_UNWIND_PROTECT {
1160 do_require(SCM_OBJ(adata->path), SCM_LOAD_PROPAGATE_ERROR,
1161 adata->module, NULL);
1162
1163 if (adata->import_from) {
1164 /* autoloaded file defines import_from module. we need to
1165 import the binding individually. */
1166 ScmModule *m = Scm_FindModule(adata->import_from,
1167 SCM_FIND_MODULE_QUIET);
1168 if (m == NULL) {
1169 Scm_Error("Trying to autoload module %S from file %S, but the file doesn't define such a module",
1170 adata->import_from, adata->path);
1171 }
1172 ScmGloc *f = Scm_FindBinding(SCM_MODULE(m), adata->name, 0);
1173 ScmGloc *g = Scm_FindBinding(adata->module, adata->name, 0);
1174 SCM_ASSERT(f != NULL);
1175 SCM_ASSERT(g != NULL);
1176 adata->value = Scm_GlocGetValue(f);
1177 if (SCM_UNBOUNDP(adata->value) || SCM_AUTOLOADP(adata->value)) {
1178 Scm_Error("Autoloaded symbol %S is not defined in the module %S",
1179 adata->name, adata->import_from);
1180 }
1181 Scm_GlocSetValue(g, adata->value);
1182 } else {
1183 /* Normal import. The binding must have been inserted to
1184 adata->module */
1185 ScmGloc *g = Scm_FindBinding(adata->module, adata->name, 0);
1186 SCM_ASSERT(g != NULL);
1187 adata->value = Scm_GlocGetValue(g);
1188 if (SCM_UNBOUNDP(adata->value) || SCM_AUTOLOADP(adata->value)) {
1189 Scm_Error("Autoloaded symbol %S is not defined in the file %S",
1190 adata->name, adata->path);
1191 }
1192 }
1193 } SCM_WHEN_ERROR {
1194 adata->locker = NULL;
1195 SCM_INTERNAL_COND_BROADCAST(adata->cv);
1196 SCM_NEXT_HANDLER;
1197 } SCM_END_PROTECT;
1198
1199 adata->loaded = TRUE;
1200 adata->locker = NULL;
1201 SCM_INTERNAL_COND_BROADCAST(adata->cv);
1202 return adata->value;
1203 }
1204
1205 /*------------------------------------------------------------------
1206 * Dynamic parameter access
1207 */
1208 ScmObj Scm_CurrentLoadHistory() { return PARAM_REF(Scm_VM(), load_history); }
1209 ScmObj Scm_CurrentLoadNext() { return PARAM_REF(Scm_VM(), load_next); }
1210 ScmObj Scm_CurrentLoadPort() { return PARAM_REF(Scm_VM(), load_port); }
1211
1212 /*------------------------------------------------------------------
1213 * Initialization
1214 */
1215
1216 void Scm__InitLoad(void)
1217 {
1218 ScmModule *m = Scm_GaucheModule();
1219 ScmObj t;
1220
1221 ScmObj init_load_path = t = SCM_NIL;
1222 SCM_APPEND(init_load_path, t, break_env_paths("GAUCHE_LOAD_PATH"));
1223 SCM_APPEND1(init_load_path, t, Scm_SiteLibraryDirectory());
1224 SCM_APPEND1(init_load_path, t, Scm_LibraryDirectory());
1225
1226 ScmObj init_dynload_path = t = SCM_NIL;
1227 SCM_APPEND(init_dynload_path, t, break_env_paths("GAUCHE_DYNLOAD_PATH"));
1228 SCM_APPEND1(init_dynload_path, t, Scm_SiteArchitectureDirectory());
1229 SCM_APPEND1(init_dynload_path, t, Scm_ArchitectureDirectory());
1230
1231 ScmObj init_load_suffixes = t = SCM_NIL;
1232 SCM_APPEND1(init_load_suffixes, t, SCM_MAKE_STR(".sld")); /* R7RS library */
1233 SCM_APPEND1(init_load_suffixes, t, SCM_MAKE_STR(".sci"));
1234 SCM_APPEND1(init_load_suffixes, t, SCM_MAKE_STR(".scm"));
1235
1236 (void)SCM_INTERNAL_MUTEX_INIT(ldinfo.path_mutex);
1237 (void)SCM_INTERNAL_MUTEX_INIT(ldinfo.prov_mutex);
1238 (void)SCM_INTERNAL_COND_INIT(ldinfo.prov_cv);
1239 (void)SCM_INTERNAL_MUTEX_INIT(ldinfo.dso_mutex);
1240
1241 key_error_if_not_found = SCM_MAKE_KEYWORD("error-if-not-found");
1242 key_macro = SCM_MAKE_KEYWORD("macro");
1243 key_ignore_coding = SCM_MAKE_KEYWORD("ignore-coding");
1244 key_paths = SCM_MAKE_KEYWORD("paths");
1245 key_environment = SCM_MAKE_KEYWORD("environment");
1246 key_main_script = SCM_MAKE_KEYWORD("main-script");
1247
1248 Scm_InitStaticClass(SCM_CLASS_DLOBJ, "<dlobj>",
1249 m, dlobj_slots, 0);
1250
1251 #define DEF(rec, sym, val) \
1252 rec = SCM_GLOC(Scm_Define(m, SCM_SYMBOL(sym), val))
1253
1254 DEF(ldinfo.load_path_rec, SCM_SYM_LOAD_PATH, init_load_path);
1255 DEF(ldinfo.dynload_path_rec, SCM_SYM_DYNAMIC_LOAD_PATH, init_dynload_path);
1256 DEF(ldinfo.load_suffixes_rec, SCM_SYM_LOAD_SUFFIXES, init_load_suffixes);
1257 DEF(ldinfo.load_path_hooks_rec, SCM_SYM_LOAD_PATH_HOOKS, SCM_NIL);
1258
1259 /* NB: Some modules are built-in. We'll register them to the
1260 provided list, in libomega.scm. */
1261 ldinfo.provided = SCM_NIL;
1262 ldinfo.providing = SCM_NIL;
1263 ldinfo.waiting = SCM_NIL;
1264 ldinfo.dso_suffixes = SCM_LIST2(SCM_MAKE_STR(".la"),
1265 SCM_MAKE_STR("." SHLIB_SO_SUFFIX));
1266 ldinfo.dso_table = SCM_HASH_TABLE(Scm_MakeHashTableSimple(SCM_HASH_STRING,0));
1267 ldinfo.dso_prelinked = SCM_NIL;
1268
1269 ldinfo.dlptr_class = Scm_MakeForeignPointerClass(m, "<dlptr>",
1270 NULL, NULL, 0);
1271
1272 #define PARAM_INIT(var, name, val) ldinfo.var = Scm_BindPrimitiveParameter(m, name, val, 0)
1273 PARAM_INIT(load_history, "current-load-history", SCM_NIL);
1274 PARAM_INIT(load_next, "current-load-next", SCM_NIL);
1275 PARAM_INIT(load_port, "current-load-port", SCM_FALSE);
1276 }