summaryrefslogtreecommitdiffstats
path: root/unix/tclLoadDyld.c
blob: 60ec6805fe62a033af3644e1adae6661f863f3b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/* 
 * tclLoadDyld.c --
 *
 *     This procedure provides a version of the TclLoadFile that
 *     works with Apple's dyld dynamic loading.  This file
 *     provided by Wilfredo Sanchez (wsanchez@apple.com).
 *     This works on Mac OS X.
 *
 * Copyright (c) 1995 Apple Computer, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tclLoadDyld.c,v 1.17 2005/05/23 20:19:47 das Exp $
 */

#include "tclInt.h"
#include <mach-o/dyld.h>
#include <mach/mach.h>

typedef struct Tcl_DyldModuleHandle {
    struct Tcl_DyldModuleHandle *nextModuleHandle;
    NSModule module;
} Tcl_DyldModuleHandle;

typedef struct Tcl_DyldLoadHandle {
    CONST struct mach_header *dyld_lib;
    Tcl_DyldModuleHandle *firstModuleHandle;
} Tcl_DyldLoadHandle;

#ifdef TCL_LOAD_FROM_MEMORY
typedef struct ThreadSpecificData {
     int haveLoadMemory;
} ThreadSpecificData;

static Tcl_ThreadDataKey dataKey;
#endif

/*
 *----------------------------------------------------------------------
 *
 * DyldOFIErrorMsg --
 *
 *	Converts a numerical NSObjectFileImage error into an
 *	error message string.
 *
 * Results:
 *     Error message string. 
 *
 * Side effects:
 *     None.
 *
 *----------------------------------------------------------------------
 */

static CONST char* DyldOFIErrorMsg(int err) {
    CONST char *ofi_msg = NULL;
    
    if (err != NSObjectFileImageSuccess) {
        switch(err) {
        case NSObjectFileImageFailure:
            ofi_msg = "object file setup failure";
            break;
        case NSObjectFileImageInappropriateFile:
            ofi_msg = "not a Mach-O MH_BUNDLE file";
            break;
        case NSObjectFileImageArch:
            ofi_msg = "no object for this architecture";
            break;
        case NSObjectFileImageFormat:
            ofi_msg = "bad object file format";
            break;
        case NSObjectFileImageAccess:
            ofi_msg = "can't read object file";
            break;
        default:
            ofi_msg = "unknown error";
            break;
        }
    }
    return ofi_msg;
}

/*
 *----------------------------------------------------------------------
 *
 * TclpDlopen --
 *
 *	Dynamically loads a binary code file into memory and returns
 *	a handle to the new code.
 *
 * Results:
 *     A standard Tcl completion code.  If an error occurs, an error
 *     message is left in the interpreter's result. 
 *
 * Side effects:
 *     New code suddenly appears in memory.
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE int
TclpDlopen(interp, pathPtr, loadHandle, unloadProcPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    Tcl_Obj *pathPtr;		/* Name of the file containing the desired
				 * code (UTF-8). */
    Tcl_LoadHandle *loadHandle;	/* Filled with token for dynamically loaded
				 * file which will be passed back to 
				 * (*unloadProcPtr)() to unload the file. */
    Tcl_FSUnloadFileProc **unloadProcPtr;	
				/* Filled with address of Tcl_FSUnloadFileProc
				 * function which should be used for
				 * this file. */
{
    Tcl_DyldLoadHandle *dyldLoadHandle;
    CONST struct mach_header *dyld_lib;
    NSObjectFileImage dyld_ofi = NULL;
    Tcl_DyldModuleHandle *dyldModuleHandle = NULL;
    CONST char *native;

    /* 
     * First try the full path the user gave us.  This is particularly
     * important if the cwd is inside a vfs, and we are trying to load
     * using a relative path.
     */
    native = Tcl_FSGetNativePath(pathPtr);
    dyld_lib = NSAddImage(native, 
			  NSADDIMAGE_OPTION_WITH_SEARCHING | 
			  NSADDIMAGE_OPTION_RETURN_ON_ERROR);
    
    if (!dyld_lib) {
        NSLinkEditErrors editError;
        CONST char *name, *msg, *ofi_msg = NULL;
        
        NSLinkEditError(&editError, &errno, &name, &msg);
        if (editError == NSLinkEditFileAccessError) {
            /* The requested file was not found: 
             * let the OS loader examine the binary search path for
             * whatever string the user gave us which hopefully refers
             * to a file on the binary path
             */
            Tcl_DString ds;
            char *fileName = Tcl_GetString(pathPtr);
            CONST char *native = Tcl_UtfToExternalDString(NULL, fileName, -1, &ds);
            dyld_lib = NSAddImage(native, 
                                  NSADDIMAGE_OPTION_WITH_SEARCHING | 
                                  NSADDIMAGE_OPTION_RETURN_ON_ERROR);
            Tcl_DStringFree(&ds);
            if (!dyld_lib) {
                NSLinkEditError(&editError, &errno, &name, &msg);
            }
        } else if ((editError == NSLinkEditFileFormatError && errno == EBADMACHO)) {
            /* The requested file was found but was not of type MH_DYLIB, 
             * attempt to load it as a MH_BUNDLE: */
            NSObjectFileImageReturnCode err;
            err = NSCreateObjectFileImageFromFile(native, &dyld_ofi);
            ofi_msg = DyldOFIErrorMsg(err);
         }
        if (!dyld_lib && !dyld_ofi) {
            Tcl_AppendResult(interp, msg, (char *) NULL);
            if (ofi_msg) {
                Tcl_AppendResult(interp, "NSCreateObjectFileImageFromFile() error: ",
                        ofi_msg, (char *) NULL);
            }
            return TCL_ERROR;
        }
    }
    
    if (dyld_ofi) {
        NSModule module;
        module = NSLinkModule(dyld_ofi, native, NSLINKMODULE_OPTION_BINDNOW |
                                                NSLINKMODULE_OPTION_RETURN_ON_ERROR);
        NSDestroyObjectFileImage(dyld_ofi);
        if (module) {
            dyldModuleHandle = (Tcl_DyldModuleHandle *) 
                    ckalloc(sizeof(Tcl_DyldModuleHandle));
            if (!dyldModuleHandle) return TCL_ERROR;
            dyldModuleHandle->module = module;
            dyldModuleHandle->nextModuleHandle = NULL;
        } else {
            NSLinkEditErrors editError;
            CONST char *name, *msg;
            NSLinkEditError(&editError, &errno, &name, &msg);
            Tcl_AppendResult(interp, msg, (char *) NULL);
            return TCL_ERROR;
        }
    }
    dyldLoadHandle = (Tcl_DyldLoadHandle *) ckalloc(sizeof(Tcl_DyldLoadHandle));
    if (!dyldLoadHandle) return TCL_ERROR;
    dyldLoadHandle->dyld_lib = dyld_lib;
    dyldLoadHandle->firstModuleHandle = dyldModuleHandle;
    *loadHandle = (Tcl_LoadHandle) dyldLoadHandle;
    *unloadProcPtr = &TclpUnloadFile;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TclpFindSymbol --
 *
 *	Looks up a symbol, by name, through a handle associated with
 *	a previously loaded piece of code (shared library).
 *
 * Results:
 *	Returns a pointer to the function associated with 'symbol' if
 *	it is found.  Otherwise returns NULL and may leave an error
 *	message in the interp's result.
 *
 *----------------------------------------------------------------------
 */
MODULE_SCOPE Tcl_PackageInitProc*
TclpFindSymbol(interp, loadHandle, symbol) 
    Tcl_Interp *interp;
    Tcl_LoadHandle loadHandle;
    CONST char *symbol;
{
    NSSymbol nsSymbol;
    CONST char *native;
    Tcl_DString newName, ds;
    Tcl_PackageInitProc* proc = NULL;
    Tcl_DyldLoadHandle *dyldLoadHandle = (Tcl_DyldLoadHandle *) loadHandle;
    /* 
     * dyld adds an underscore to the beginning of symbol names.
     */
    native = Tcl_UtfToExternalDString(NULL, symbol, -1, &ds);
    Tcl_DStringInit(&newName);
    Tcl_DStringAppend(&newName, "_", 1);
    native = Tcl_DStringAppend(&newName, native, -1);
    if (dyldLoadHandle->dyld_lib) {
        nsSymbol = NSLookupSymbolInImage(dyldLoadHandle->dyld_lib, native, 
            NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW | 
            NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
        if(nsSymbol) {
            /* until dyld supports unloading of MY_DYLIB binaries, the
             * following is not needed: */
#ifdef DYLD_SUPPORTS_DYLIB_UNLOADING
            NSModule module = NSModuleForSymbol(nsSymbol);
            Tcl_DyldModuleHandle *dyldModuleHandle = dyldLoadHandle->firstModuleHandle;
            while (dyldModuleHandle) {
                if (module == dyldModuleHandle->module) break;
                dyldModuleHandle = dyldModuleHandle->nextModuleHandle;
            }
            if (!dyldModuleHandle) {
                dyldModuleHandle = (Tcl_DyldModuleHandle *)
                        ckalloc(sizeof(Tcl_DyldModuleHandle));
                if (dyldModuleHandle) {
                    dyldModuleHandle->module = module;
                    dyldModuleHandle->nextModuleHandle = 
                            dyldLoadHandle->firstModuleHandle;
                    dyldLoadHandle->firstModuleHandle = dyldModuleHandle;
                }
            }
#endif /* DYLD_SUPPORTS_DYLIB_UNLOADING */
       } else {
            NSLinkEditErrors editError;
            CONST char *name, *msg;
            NSLinkEditError(&editError, &errno, &name, &msg);
            Tcl_AppendResult(interp, msg, (char *) NULL);
        }
    } else {
        nsSymbol = NSLookupSymbolInModule(dyldLoadHandle->firstModuleHandle->module, 
                                          native);
    }
    if(nsSymbol) {
        proc = NSAddressOfSymbol(nsSymbol);
    }
    Tcl_DStringFree(&newName);
    Tcl_DStringFree(&ds);
    
    return proc;
}

/*
 *----------------------------------------------------------------------
 *
 * TclpUnloadFile --
 *
 *     Unloads a dynamically loaded binary code file from memory.
 *     Code pointers in the formerly loaded file are no longer valid
 *     after calling this function.
 *
 * Results:
 *     None.
 *
 * Side effects:
 *     Code dissapears from memory.
 *     Note that dyld currently only supports unloading of binaries of
 *     type MH_BUNDLE loaded with NSLinkModule() in TclpDlopen() above.
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE void
TclpUnloadFile(loadHandle)
    Tcl_LoadHandle loadHandle;	/* loadHandle returned by a previous call
				 * to TclpDlopen().  The loadHandle is 
				 * a token that represents the loaded 
				 * file. */
{
    Tcl_DyldLoadHandle *dyldLoadHandle = (Tcl_DyldLoadHandle *) loadHandle;
    Tcl_DyldModuleHandle *dyldModuleHandle = dyldLoadHandle->firstModuleHandle;
    void *ptr;

    while (dyldModuleHandle) {
	NSUnLinkModule(dyldModuleHandle->module, 
	               NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES);
	ptr = dyldModuleHandle;
	dyldModuleHandle = dyldModuleHandle->nextModuleHandle;
	ckfree(ptr);
    }
    ckfree((char*) dyldLoadHandle);
}

/*
 *----------------------------------------------------------------------
 *
 * TclGuessPackageName --
 *
 *     If the "load" command is invoked without providing a package
 *     name, this procedure is invoked to try to figure it out.
 *
 * Results:
 *     Always returns 0 to indicate that we couldn't figure out a
 *     package name;  generic code will then try to guess the package
 *     from the file name.  A return value of 1 would have meant that
 *     we figured out the package name and put it in bufPtr.
 *
 * Side effects:
 *     None.
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE int
TclGuessPackageName(fileName, bufPtr)
    CONST char *fileName;      /* Name of file containing package (already
				* translated to local form if needed). */
    Tcl_DString *bufPtr;       /* Initialized empty dstring.  Append
				* package name to this if possible. */
{
    return 0;
}

#ifdef TCL_LOAD_FROM_MEMORY
/*
 *----------------------------------------------------------------------
 *
 * TclpLoadMemoryGetBuffer --
 *
 *	Allocate a buffer that can be used with TclpLoadMemory() below.
 *
 * Results:
 *     Pointer to allocated buffer or NULL if an error occurs.
 *
 * Side effects:
 *     Buffer is allocated.
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE void*
TclpLoadMemoryGetBuffer(interp, size)
    Tcl_Interp *interp;		/* Used for error reporting. */
    int size;                   /* Size of desired buffer */
{
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
    void * buffer = NULL;
    
    if (!tsdPtr->haveLoadMemory) {
        /* NSCreateObjectFileImageFromMemory is available but always 
         * fails prior to Darwin 7 */
        struct utsname name;
        if (!uname(&name)) {
            long release = strtol(name.release, NULL, 10);
            tsdPtr->haveLoadMemory = (release >= 7) ? 1 : -1;
        }
    }
    if (tsdPtr->haveLoadMemory > 0) {
        /* We must allocate the  buffer using vm_allocate, because
         * NSCreateObjectFileImageFromMemory  will dispose of it
         * using vm_deallocate.
         */
        int err = vm_allocate(mach_task_self(), 
                              (vm_address_t*)&buffer, size, 1);
        if (err) {
            buffer = NULL;
        }
    }
    return buffer;
}

/*
 *----------------------------------------------------------------------
 *
 * TclpLoadMemory --
 *
 *	Dynamically loads binary code file from memory and returns
 *	a handle to the new code.
 *
 * Results:
 *     A standard Tcl completion code.  If an error occurs, an error
 *     message is left in the interpreter's result. 
 *
 * Side effects:
 *     New code is loaded from memory.
 *
 *----------------------------------------------------------------------
 */

MODULE_SCOPE int
TclpLoadMemory(interp, buffer, size, codeSize, loadHandle, unloadProcPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    void *buffer;		/* Buffer containing the desired code
				 * (allocated with TclpLoadMemoryGetBuffer). */
    int size;                   /* Allocation size of buffer. */
    int codeSize;               /* Size of code data read into buffer or -1 if
                                 * an error occurred and the buffer should
                                 * just be freed. */
    Tcl_LoadHandle *loadHandle;	/* Filled with token for dynamically loaded
				 * file which will be passed back to 
				 * (*unloadProcPtr)() to unload the file. */
    Tcl_FSUnloadFileProc **unloadProcPtr;	
				/* Filled with address of Tcl_FSUnloadFileProc
				 * function which should be used for
				 * this file. */
{
    Tcl_DyldLoadHandle *dyldLoadHandle;
    NSObjectFileImage dyld_ofi = NULL;
    Tcl_DyldModuleHandle *dyldModuleHandle;
    CONST char *ofi_msg = NULL;

    if (codeSize >= 0) {
        NSObjectFileImageReturnCode err;
        err = NSCreateObjectFileImageFromMemory(buffer, codeSize, &dyld_ofi);
        ofi_msg = DyldOFIErrorMsg(err);
    }
    if (!dyld_ofi) {
        vm_deallocate(mach_task_self(), (vm_address_t) buffer, size);
        if (ofi_msg) {
            Tcl_AppendResult(interp, "NSCreateObjectFileImageFromFile() error: ",
                    ofi_msg, (char *) NULL);
        }
        return TCL_ERROR;
    } else {
        NSModule module;
        module = NSLinkModule(dyld_ofi, "[Memory Based Bundle]", 
                NSLINKMODULE_OPTION_BINDNOW |NSLINKMODULE_OPTION_RETURN_ON_ERROR);
        NSDestroyObjectFileImage(dyld_ofi);
        if (module) {
            dyldModuleHandle = (Tcl_DyldModuleHandle *) 
                    ckalloc(sizeof(Tcl_DyldModuleHandle));
            if (!dyldModuleHandle) return TCL_ERROR;
            dyldModuleHandle->module = module;
            dyldModuleHandle->nextModuleHandle = NULL;
        } else {
            NSLinkEditErrors editError;
            CONST char *name, *msg;
            NSLinkEditError(&editError, &errno, &name, &msg);
            Tcl_AppendResult(interp, msg, (char *) NULL);
            return TCL_ERROR;
        }
    }
    dyldLoadHandle = (Tcl_DyldLoadHandle *) ckalloc(sizeof(Tcl_DyldLoadHandle));
    if (!dyldLoadHandle) return TCL_ERROR;
    dyldLoadHandle->dyld_lib = NULL;
    dyldLoadHandle->firstModuleHandle = dyldModuleHandle;
    *loadHandle = (Tcl_LoadHandle) dyldLoadHandle;
    *unloadProcPtr = &TclpUnloadFile;
    return TCL_OK;
}
#endif