summaryrefslogtreecommitdiff
path: root/3rdparty/plibsys/src/plibraryloader-amiga.c
blob: 463e350a23db34ecd888fd50cb1ebd58419ef136 (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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/*
 * The MIT License
 *
 * Copyright (C) 2017-2018 Alexander Saprykin <saprykin.spb@gmail.com>
 * Copyright (C) 2002-2015 by Olaf Barthel <obarthel (at) gmx.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Path conversion code was taken and adopted from clib2 project:
 * https://github.com/adtools/clib2
 *
 * This part of code is distributed under the BSD-3-Clause license:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Neither the name of Olaf Barthel nor the names of contributors
 *     may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "perror.h"
#include "pfile.h"
#include "plibraryloader.h"
#include "pmem.h"
#include "pstring.h"

#include <string.h>

#include <proto/dos.h>
#include <proto/elf.h>

#if defined (__CLIB2__)
#  include <dos.h>
#elif defined (__NEWLIB__)
#  include <amiga_platform.h>
#endif

typedef APTR plibrary_handle;

struct PLibraryLoader_ {
	plibrary_handle	handle;
	Elf32_Error	last_error;
};

static Elf32_Handle pp_library_loader_elf_root = NULL;

static void pp_library_loader_clean_handle (plibrary_handle handle);
static pint pp_library_loader_translate_path (const pchar *in, pchar *out, psize out_len);

/*
 * The following patterns must translate properly:
 *
 *		foo/
 *		///
 *		foo//bar
 *		foo//bar//baz
 *		./foo
 *		././foo
 *		foo/./baz
 *		foo/./bar/./baz
 *		foo/./././bar
 *		foo/.
 *		/.
 *		/tmp
 *		/tmp/foo
 *		/dev/null
 *		/dev/null/foo
 *		/dev/nullX
 *		/foo
 *		/foo/
 *		/foo/bar
 *		/foo/bar/baz
 *		foo/../bar
 *		foo/bar/../../baz
 *		foo/bar/..
 *		../foo
 *		../../foo
 *		.
 *		..
 */

static pint
pp_library_loader_translate_path (const pchar *in, pchar *out, psize out_len)
{
	pchar volume_name[MAXPATHLEN];
	psize len, volume_name_len;
	pint i, j;

	len = strlen (in);

	if (out_len < MAXPATHLEN || len > MAXPATHLEN)
		return -1;

	strcpy (out, in);

	/* Just copy is path is already an Amiga one */

	if (strchr (in, ':') != NULL)
		return 0;

	in = out;

	/* Strip neighbouring slashes: ('foo//bar' -> 'foo/bar').
	 * The "//" pattern in a Unix file name is apparently harmless,
	 * but on AmigaDOS it has a very definite meaning. */

	if (len > 2) {
		pboolean have_double_slash = FALSE;

		for (i = 0; i < len - 1; ++i) {
			if (in[i] == '/' && in[i + 1] == '/') {
				have_double_slash = TRUE;
				break;
			}
		}

		if (have_double_slash) {
			pboolean have_slash;
			pchar c;

			have_slash = FALSE;

			for (i = j = 0; i < len; ++i) {
				c = in[i];

				if (c == '/') {
					if (!have_slash)
						out[j++] = c;

					have_slash = TRUE;
				} else {
					out[j++] = c;
					have_slash = FALSE;
				}
			}

			len = j;
			out[len] = '\0';
		}
	}

	/* Strip trailing slashes ('foo/' -> 'foo'). A leading '/' must
	 * be preserved, though ('///' -> '/'). */

	if(len > 1) {
		psize num_trailing_slashes = 0;

		while ((num_trailing_slashes < len - 1) && (in[len - (num_trailing_slashes + 1)] == '/'))
			num_trailing_slashes++;

		if (num_trailing_slashes > 0) {
			len -= num_trailing_slashes;
			out[len] = '\0';
		}
	}

	/* Ditch all leading './' ('./foo' -> 'foo'). */

	while (len > 2 && out[0] == '.' && out[1] == '/') {
		len -= 2;
		memmove (out, &out[2], len);
		out[len] = '\0';
	}

	/* Ditch all embedded '/./' ('foo/./bar' -> 'foo/bar', 'foo/././bar' -> 'foo/bar'). */

	if (len > 2) {
		pboolean have_slash_dot_slash = FALSE;

		for (i = j = 0; i < len - 2; ++i) {
			if(in[i] == '/' && in[i + 1] == '.' && in[i + 2] == '/') {
				have_slash_dot_slash = TRUE;
				break;
			}
		}

		if (have_slash_dot_slash) {
			for (i = j = 0; i < len; ++i) {
				while (i < len - 2 && in[i] == '/' && in[i + 1] == '.' && in[i + 2] == '/')
					i += 2;

				if (i < len)
					out[j++] = in[i];
			}
	
			len = j;
			out[len] = '\0';
		}
	}

	/* Special case: the path name may end with "/." signifying that the
	 * directory itself is requested ('foo/.' -> 'foo'). */

	if (len >= 2 && strncmp (&in[len - 2], "/.", 2) == 0) {
		/* If it's just '/.' then it's really '/'. */
		if (len == 2) {
			strcpy (out, "/");
			len = 1;
		} else {
			len -= 2;
			out[len] = '\0';
		}
	}

	/* Check for absolute path. */

	if (in[0] == '/') {
		/* OK, so this is an absolute path. We begin by checking
		 * for a few special cases, the first being a reference
		 * to "/tmp". */
		if ((strncmp (in, "/tmp", 4) == 0) && (in[4] == '/' || len == 4)) {
			if (in[4] == '/') {
				/* Convert "/tmp/foo" to "T:foo". */
				memmove (&out[2], &in[5], len - 5);
				memmove (out, "T:", 2);

				len -= 3;
			} else {
				/* Convert "/tmp" to "T:". */
				strcpy (out, "T:");

				len = 2;
			}

			out[len] = '\0';
		} else if ((strncmp (in, "/dev/null", 9)) == 0 && (len == 9 || in[9] == '/')) {
			strcpy (out, "NIL:");
			len = 4;
		} else {
			psize path_name_start = 0;
			volume_name_len       = 0;

			/* Find out how long the first component of the absolute path is. */
			for (i = 1; i <= len; ++i) {
				if (i == len || in[i] == '/') {
					volume_name_len = i - 1;

					/* Is there anything following the path name? */
					if (i < len)
						path_name_start = i + 1;

					break;
				}
			}

			/* Copy the first component and attach a colon. "/foo" becomes "foo:". */
			memmove (out, &in[1], volume_name_len);
			out[volume_name_len++] = ':';

			/* Now add the finishing touches. "/foo/bar" finally
			 * becomes "foo:bar" and "/foo" becomes "foo:". */
			if (path_name_start > 0) {
				memmove (&out[volume_name_len], &in[path_name_start], len - path_name_start);

				len--;
			}

			out[len] = '\0';
		}
	}

	/* Extract and remove the volume name from the path. We
	 * are going to need it later. */

	volume_name_len = 0;

	for (i = 0; i < len; ++i) {
		if (in[i] == ':') {
			/* Look for extra colon characters embedded in the name
		         * (as in "foo/bar:baz") which really don't belong here. */
			for (j = 0 ; j < i ; j++) {
				if(in[j] == '/')
					return -1;
			}

			volume_name_len = i + 1;
			len -= volume_name_len;

			memmove (volume_name, in, volume_name_len);
			memmove (out, &out[volume_name_len], len);
			
			out[len] = '\0';

			break;
		}
	}

	/* Look for extra colon characters embedded in the name
         * (as in "foo:bar:baz") which really don't belong here. */

	for (i = 0; i < len; ++i) {
		if (in[i] == ':')
			return -1;
	}	

	/* Now parse the path name and replace all embedded '..' with
	 * the AmigaDOS counterparts ('foo/../bar' -> 'foo//bar'). */

	if (len > 3) {
		pboolean have_slash_dot_dot_slash = FALSE;

		for (i = j = 0; i < len - 3; ++i) {
			if (in[i] == '/' && in[i + 1] == '.' && in[i + 2] == '.' && in[i + 3] == '/') {
				have_slash_dot_dot_slash = TRUE;
				break;
			}
		}

		if (have_slash_dot_dot_slash) {
			pboolean have_before = FALSE;

			for (i = j = 0; i < len; ++i) {
				if(i < len - 3 && in[i] == '/' && in[i + 1] == '.' && in[i + 2] == '.' && in[i + 3] == '/') {
					out[j++] = in[i];

					if (have_before)
						out[j++] = '/';

					i += 2;

					have_before = TRUE;
				} else {
					have_before = FALSE;
					out[j++] = in[i];
				}
			}

			len = j;
			out[len] = '\0';
		}
	}

	/* Translate a trailing '/..' to '//' */

	if (len >= 3 && strncmp (&in[len - 3], "/..", 3) == 0) {
		len -= 2;
		out[len++] = '/';
		out[len] = '\0';
	}

	/* Translate a leading '../' ('../foo' -> '/foo') */

	if (len >= 3 && strncmp (in, "../", 3) == 0) {
		memmove (out, &in[2], len - 2);
		
		len -= 2;
		out[len] = '\0';
	}

	/* Translate the '..' ('..' -> '/') */

	if (len == 2 && strncmp (in, "..", 2) == 0) {
		strcpy (out, "/");

		len = 1;
	}

	/* Translate the '.' ('.' -> '') */

	if (len == 1 && in[0] == '.') {
		strcpy (out, "");

		len = 0;
	}

	/* Now put it all together again. */

	if(volume_name_len > 0) {
		memmove (&out[volume_name_len], in, len);
		memmove (out, volume_name, volume_name_len);

		len += volume_name_len;
		out[len] = '\0';
	}

	return 0;
}

static void
pp_library_loader_clean_handle (plibrary_handle handle)
{
	IElf->DLClose (pp_library_loader_elf_root, handle);
}

P_LIB_API PLibraryLoader *
p_library_loader_new (const pchar *path)
{
	PLibraryLoader	*loader = NULL;
	plibrary_handle	handle  = NULL;
	pchar		path_buffer[MAXPATHLEN];
	
	if (!p_file_is_exists (path))
		return NULL;

	if (pp_library_loader_elf_root == NULL) {
		P_ERROR ("PLibraryLoader::p_library_loader_new: shared library subsystem is not initialized");
		return NULL;
	}

	if (strlen (path) >= MAXPATHLEN) {
		P_ERROR ("PLibraryLoader::p_library_loader_new: too long file path or name");
		return NULL;
	}

	if (pp_library_loader_translate_path (path, path_buffer, MAXPATHLEN) != 0) {
		P_ERROR ("PLibraryLoader::p_library_loader_new: failed to convert to UNIX path");
		return NULL;
	}

	path = path_buffer;

	handle = IElf->DLOpen (pp_library_loader_elf_root, (CONST_STRPTR) path, ELF32_RTLD_LOCAL);

	if (P_UNLIKELY (handle == NULL)) {
		P_ERROR ("PLibraryLoader::p_library_loader_new: DLOpen() failed");
		return NULL;
	}

	if (P_UNLIKELY ((loader = p_malloc0 (sizeof (PLibraryLoader))) == NULL)) {
		P_ERROR ("PLibraryLoader::p_library_loader_new: failed to allocate memory");
		pp_library_loader_clean_handle (handle);
		return NULL;
	}

	loader->handle     = handle;
	loader->last_error = ELF32_NO_ERROR;

	return loader;
}

P_LIB_API PFuncAddr
p_library_loader_get_symbol (PLibraryLoader *loader, const pchar *sym)
{
	APTR func_addr = NULL;

	if (P_UNLIKELY (loader == NULL || sym == NULL || loader->handle == NULL))
		return NULL;

	if (pp_library_loader_elf_root == NULL) {
		P_ERROR ("PLibraryLoader::p_library_loader_new: shared library subsystem is not initialized");
		return NULL;
	}

	loader->last_error = IElf->DLSym (pp_library_loader_elf_root,
					  loader->handle,
					  (CONST_STRPTR) sym,
					  &func_addr);

	return (PFuncAddr) func_addr;
}

P_LIB_API void
p_library_loader_free (PLibraryLoader *loader)
{
	if (P_UNLIKELY (loader == NULL))
		return;

	pp_library_loader_clean_handle (loader->handle);

	p_free (loader);
}

P_LIB_API pchar *
p_library_loader_get_last_error (PLibraryLoader *loader)
{
	if (P_UNLIKELY (loader == NULL))
		return NULL;

	switch (loader->last_error) {
		case ELF32_NO_ERROR:
			return NULL;
		case ELF32_OUT_OF_MEMORY:
			return p_strdup ("Out of memory");
		case ELF32_INVALID_HANDLE:
			return p_strdup ("Invalid resource handler");
		case ELF32_NO_MORE_RELOCS:
			return p_strdup ("No more relocations left");
		case ELF32_SECTION_NOT_LOADED:
			return p_strdup ("Section not loaded");
		case ELF32_UNKNOWN_RELOC:
			return p_strdup ("Unknown relocation");
		case ELF32_READ_ERROR:
			return p_strdup ("Read error");
		case ELF32_INVALID_SDA_BASE:
			return p_strdup ("Invalid SDA base");
		case ELF32_SYMBOL_NOT_FOUND:
			return p_strdup ("Symbol not found");
		case ELF32_INVALID_NAME:
			return p_strdup ("Invalid procedure name");
		case ELF32_REQUIRED_OBJECT_MISSING:
			return p_strdup ("Required object is missing");
		default:
			return p_strdup ("Unknown error");
	}
}

P_LIB_API pboolean
p_library_loader_is_ref_counted (void)
{
	return TRUE;
}

void
p_library_loader_init (void)
{
	BPTR		segment_list;
	Elf32_Handle	elf_handle;

	if (pp_library_loader_elf_root != NULL)
		return;

	segment_list = IDOS->GetProcSegList (NULL, GPSLF_RUN);

	if (P_UNLIKELY (segment_list == 0)) {
		P_ERROR ("PLibraryLoader::p_library_loader_init: GetProcSegList() failed");
		return;
	}

	if (P_UNLIKELY (IDOS->GetSegListInfoTags (segment_list,
						  GSLI_ElfHandle,
						  &elf_handle,
						  TAG_DONE) != 1)) {
		P_ERROR ("PLibraryLoader::p_library_loader_init: GetSegListInfoTags() failed");
		return;
	}

	if (P_UNLIKELY (elf_handle == NULL)) {
		P_ERROR ("PLibraryLoader::p_library_loader_init: failed to finf proper GSLI_ElfHandle");
		return;
	}

	pp_library_loader_elf_root = IElf->OpenElfTags (OET_ElfHandle, elf_handle, TAG_DONE);

	if (P_UNLIKELY (pp_library_loader_elf_root == NULL)) {
		P_ERROR ("PLibraryLoader::p_library_loader_init: OpenElfTags() failed");
		return;
	}
}

void
p_library_loader_shutdown (void)
{
	if (pp_library_loader_elf_root == NULL)
		return;

	IElf->CloseElfTags (pp_library_loader_elf_root, CET_ReClose, TRUE, TAG_DONE);

	pp_library_loader_elf_root = NULL;
}