xref: /haiku/src/system/runtime_loader/runtime_loader.cpp (revision 9829800d2c60d6aba146af7fde09601929161730)
1 /*
2  * Copyright 2005-2009, Axel Dörfler, axeld@pinc-software.de.
3  * Distributed under the terms of the MIT License.
4  *
5  * Copyright 2002, Manuel J. Petit. All rights reserved.
6  * Distributed under the terms of the NewOS License.
7  */
8 
9 
10 #include "runtime_loader_private.h"
11 
12 #include <elf32.h>
13 #include <syscalls.h>
14 #include <user_runtime.h>
15 
16 #include <string.h>
17 #include <stdlib.h>
18 #include <sys/stat.h>
19 
20 #include <algorithm>
21 
22 
23 struct user_space_program_args *gProgramArgs;
24 
25 
26 static const char *
27 search_path_for_type(image_type type)
28 {
29 	const char *path = NULL;
30 
31 	switch (type) {
32 		case B_APP_IMAGE:
33 			path = getenv("PATH");
34 			break;
35 		case B_LIBRARY_IMAGE:
36 			path = getenv("LIBRARY_PATH");
37 			break;
38 		case B_ADD_ON_IMAGE:
39 			path = getenv("ADDON_PATH");
40 			break;
41 
42 		default:
43 			return NULL;
44 	}
45 
46 	if (path != NULL)
47 		return path;
48 
49 	// The environment variables may not have been set yet - in that case,
50 	// we're returning some useful defaults.
51 	// Since the kernel does not set any variables, this is also needed
52 	// to start the root shell.
53 
54 	switch (type) {
55 		case B_APP_IMAGE:
56 			return "/boot/home/config/bin"
57 						// TODO: Remove!
58 				":/boot/common/bin"
59 				":/bin"
60 				":/boot/apps"
61 				":/boot/preferences"
62 				":/boot/system/apps"
63 				":/boot/system/preferences"
64 				":/boot/develop/tools/gnupro/bin";
65 
66 		case B_LIBRARY_IMAGE:
67 			return "%A/lib"
68 				":/boot/home/config/lib"
69 					// TODO: Remove!
70 				":/boot/common/lib:/boot/system/lib";
71 
72 		case B_ADD_ON_IMAGE:
73 			return "%A/add-ons"
74 				":/boot/home/config/add-ons"
75 					// TODO: Remove!
76 				":/boot/common/add-ons"
77 				":/boot/system/add-ons";
78 
79 		default:
80 			return NULL;
81 	}
82 }
83 
84 
85 static int
86 try_open_executable(const char *dir, int dirLength, const char *name,
87 	const char *programPath, const char *compatibilitySubDir, char *path,
88 	size_t pathLength)
89 {
90 	size_t nameLength = strlen(name);
91 	struct stat stat;
92 	status_t status;
93 
94 	// construct the path
95 	if (dirLength > 0) {
96 		char *buffer = path;
97 		size_t subDirLen = 0;
98 
99 		if (programPath == NULL)
100 			programPath = gProgramArgs->program_path;
101 
102 		if (dirLength >= 2 && strncmp(dir, "%A", 2) == 0) {
103 			// Replace %A with current app folder path (of course,
104 			// this must be the first part of the path)
105 			char *lastSlash = strrchr(programPath, '/');
106 			int bytesCopied;
107 
108 			// copy what's left (when the application name is removed)
109 			if (lastSlash != NULL) {
110 				strlcpy(buffer, programPath,
111 					std::min((long)pathLength, lastSlash + 1 - programPath));
112 			} else
113 				strlcpy(buffer, ".", pathLength);
114 
115 			bytesCopied = strlen(buffer);
116 			buffer += bytesCopied;
117 			pathLength -= bytesCopied;
118 			dir += 2;
119 			dirLength -= 2;
120 		} else if (compatibilitySubDir != NULL) {
121 			// We're looking for a library or an add-on and the executable has
122 			// not been compiled with a compiler compatible with the one the
123 			// OS has been built with. Thus we only look in specific subdirs.
124 			subDirLen = strlen(compatibilitySubDir) + 1;
125 		}
126 
127 		if (dirLength + 1 + subDirLen + nameLength >= pathLength)
128 			return B_NAME_TOO_LONG;
129 
130 		memcpy(buffer, dir, dirLength);
131 		buffer[dirLength] = '/';
132 		if (subDirLen > 0) {
133 			memcpy(buffer + dirLength + 1, compatibilitySubDir, subDirLen - 1);
134 			buffer[dirLength + subDirLen] = '/';
135 		}
136 		strcpy(buffer + dirLength + 1 + subDirLen, name);
137 	} else {
138 		if (nameLength >= pathLength)
139 			return B_NAME_TOO_LONG;
140 
141 		strcpy(path + dirLength + 1, name);
142 	}
143 
144 	TRACE(("runtime_loader: try_open_container(): %s\n", path));
145 
146 	// Test if the target is a symbolic link, and correct the path in this case
147 
148 	status = _kern_read_stat(-1, path, false, &stat, sizeof(struct stat));
149 	if (status < B_OK)
150 		return status;
151 
152 	if (S_ISLNK(stat.st_mode)) {
153 		char buffer[PATH_MAX];
154 		size_t length = PATH_MAX - 1;
155 		char *lastSlash;
156 
157 		// it's a link, indeed
158 		status = _kern_read_link(-1, path, buffer, &length);
159 		if (status < B_OK)
160 			return status;
161 		buffer[length] = '\0';
162 
163 		lastSlash = strrchr(path, '/');
164 		if (buffer[0] != '/' && lastSlash != NULL) {
165 			// relative path
166 			strlcpy(lastSlash + 1, buffer, lastSlash + 1 - path + pathLength);
167 		} else
168 			strlcpy(path, buffer, pathLength);
169 	}
170 
171 	return _kern_open(-1, path, O_RDONLY, 0);
172 }
173 
174 
175 static int
176 search_executable_in_path_list(const char *name, const char *pathList,
177 	int pathListLen, const char *programPath, const char *compatibilitySubDir,
178 	char *pathBuffer, size_t pathBufferLength)
179 {
180 	const char *pathListEnd = pathList + pathListLen;
181 	status_t status = B_ENTRY_NOT_FOUND;
182 
183 	TRACE(("runtime_loader: search_container_in_path_list() %s in %.*s\n", name,
184 		pathListLen, pathList));
185 
186 	while (pathListLen > 0) {
187 		const char *pathEnd = pathList;
188 		int fd;
189 
190 		// find the next ':' or run till the end of the string
191 		while (pathEnd < pathListEnd && *pathEnd != ':')
192 			pathEnd++;
193 
194 		fd = try_open_executable(pathList, pathEnd - pathList, name,
195 			programPath, compatibilitySubDir, pathBuffer, pathBufferLength);
196 		if (fd >= 0) {
197 			// see if it's a dir
198 			struct stat stat;
199 			status = _kern_read_stat(fd, NULL, true, &stat, sizeof(struct stat));
200 			if (status == B_OK) {
201 				if (!S_ISDIR(stat.st_mode))
202 					return fd;
203 				status = B_IS_A_DIRECTORY;
204 			}
205 			_kern_close(fd);
206 		}
207 
208 		pathListLen = pathListEnd - pathEnd - 1;
209 		pathList = pathEnd + 1;
210 	}
211 
212 	return status;
213 }
214 
215 
216 int
217 open_executable(char *name, image_type type, const char *rpath,
218 	const char *programPath, const char *compatibilitySubDir)
219 {
220 	char buffer[PATH_MAX];
221 	int fd = B_ENTRY_NOT_FOUND;
222 
223 	if (strchr(name, '/')) {
224 		// the name already contains a path, we don't have to search for it
225 		fd = _kern_open(-1, name, O_RDONLY, 0);
226 		if (fd >= 0 || type == B_APP_IMAGE)
227 			return fd;
228 
229 		// can't search harder an absolute path add-on name!
230 		if (type == B_ADD_ON_IMAGE && name[0] == '/')
231 			return fd;
232 
233 		// Even though ELF specs don't say this, we give shared libraries
234 		// and relative path based add-ons another chance and look
235 		// them up in the usual search paths - at
236 		// least that seems to be what BeOS does, and since it doesn't hurt...
237 		if (type == B_LIBRARY_IMAGE) {
238 			// For library (but not add-on), strip any path from name.
239 			// Relative path of add-on is kept.
240 			const char* paths = strrchr(name, '/') + 1;
241 			memmove(name, paths, strlen(paths) + 1);
242 		}
243 	}
244 
245 	// try rpath (DT_RPATH)
246 	if (rpath != NULL) {
247 		// It consists of a colon-separated search path list. Optionally a
248 		// second search path list follows, separated from the first by a
249 		// semicolon.
250 		const char *semicolon = strchr(rpath, ';');
251 		const char *firstList = (semicolon ? rpath : NULL);
252 		const char *secondList = (semicolon ? semicolon + 1 : rpath);
253 			// If there is no ';', we set only secondList to simplify things.
254 		if (firstList) {
255 			fd = search_executable_in_path_list(name, firstList,
256 				semicolon - firstList, programPath, NULL, buffer,
257 				sizeof(buffer));
258 		}
259 		if (fd < 0) {
260 			fd = search_executable_in_path_list(name, secondList,
261 				strlen(secondList), programPath, NULL, buffer, sizeof(buffer));
262 		}
263 	}
264 
265 	// If not found yet, let's evaluate the system path variables to find the
266 	// shared object.
267 	if (fd < 0) {
268 		if (const char *paths = search_path_for_type(type)) {
269 			fd = search_executable_in_path_list(name, paths, strlen(paths),
270 				programPath, compatibilitySubDir, buffer, sizeof(buffer));
271 
272 			// If not found and a compatibility sub directory has been
273 			// specified, look again in the standard search paths.
274 			if (fd == B_ENTRY_NOT_FOUND && compatibilitySubDir != NULL) {
275 				fd = search_executable_in_path_list(name, paths, strlen(paths),
276 					programPath, NULL, buffer, sizeof(buffer));
277 			}
278 		}
279 	}
280 
281 	if (fd >= 0) {
282 		// we found it, copy path!
283 		TRACE(("runtime_loader: open_executable(%s): found at %s\n", name, buffer));
284 		strlcpy(name, buffer, PATH_MAX);
285 	}
286 
287 	return fd;
288 }
289 
290 
291 /*!
292 	Tests if there is an executable file at the provided path. It will
293 	also test if the file has a valid ELF header or is a shell script.
294 	Even if the runtime loader does not need to be able to deal with
295 	both types, the caller will give scripts a proper treatment.
296 */
297 status_t
298 test_executable(const char *name, char *invoker)
299 {
300 	char path[B_PATH_NAME_LENGTH];
301 	char buffer[B_FILE_NAME_LENGTH];
302 		// must be large enough to hold the ELF header
303 	status_t status;
304 	ssize_t length;
305 	int fd;
306 
307 	if (name == NULL)
308 		return B_BAD_VALUE;
309 
310 	strlcpy(path, name, sizeof(path));
311 
312 	fd = open_executable(path, B_APP_IMAGE, NULL, NULL, NULL);
313 	if (fd < B_OK)
314 		return fd;
315 
316 	// see if it's executable at all
317 	status = _kern_access(-1, path, X_OK, false);
318 	if (status != B_OK)
319 		goto out;
320 
321 	// read and verify the ELF header
322 
323 	length = _kern_read(fd, 0, buffer, sizeof(buffer));
324 	if (length < 0) {
325 		status = length;
326 		goto out;
327 	}
328 
329 	status = elf_verify_header(buffer, length);
330 	if (status == B_NOT_AN_EXECUTABLE) {
331 		// test for shell scripts
332 		if (!strncmp(buffer, "#!", 2)) {
333 			char *end;
334 			buffer[min_c((size_t)length, sizeof(buffer) - 1)] = '\0';
335 
336 			end = strchr(buffer, '\n');
337 			if (end == NULL) {
338 				status = E2BIG;
339 				goto out;
340 			} else
341 				end[0] = '\0';
342 
343 			if (invoker)
344 				strcpy(invoker, buffer + 2);
345 
346 			status = B_OK;
347 		}
348 	} else if (status == B_OK) {
349 		struct Elf32_Ehdr *elfHeader = (struct Elf32_Ehdr *)buffer;
350 		if (elfHeader->e_entry == 0) {
351 			// we don't like to open shared libraries
352 			status = B_NOT_AN_EXECUTABLE;
353 		} else if (invoker)
354 			invoker[0] = '\0';
355 	}
356 
357 out:
358 	_kern_close(fd);
359 	return status;
360 }
361 
362 
363 /*!
364 	This is the main entry point of the runtime loader as
365 	specified by its ld-script.
366 */
367 int
368 runtime_loader(void *_args)
369 {
370 	void *entry = NULL;
371 	int returnCode;
372 
373 	gProgramArgs = (struct user_space_program_args *)_args;
374 
375 	// Relocate the args and env arrays -- they are organized in a contiguous
376 	// buffer which the kernel just copied into user space without adjusting the
377 	// pointers.
378 	{
379 		int32 i;
380 		addr_t relocationOffset = 0;
381 
382 		if (gProgramArgs->arg_count > 0)
383 			relocationOffset = (addr_t)gProgramArgs->args[0];
384 		else if (gProgramArgs->env_count > 0)
385 			relocationOffset = (addr_t)gProgramArgs->env[0];
386 
387 		// That's basically: <new buffer address> - <old buffer address>.
388 		// It looks a little complicated, since we don't have the latter one at
389 		// hand and thus need to reconstruct it (<first string pointer> -
390 		// <arguments + environment array sizes>).
391 		relocationOffset = (addr_t)gProgramArgs->args - relocationOffset
392 			+ (gProgramArgs->arg_count + gProgramArgs->env_count + 2)
393 				* sizeof(char*);
394 
395 		for (i = 0; i < gProgramArgs->arg_count; i++)
396 			gProgramArgs->args[i] += relocationOffset;
397 
398 		for (i = 0; i < gProgramArgs->env_count; i++)
399 			gProgramArgs->env[i] += relocationOffset;
400 	}
401 
402 	if (!strcmp(gProgramArgs->program_path, "/boot/system/runtime_loader")) {
403 		// TODO: this is a (temporary) work-around for bug #2273 which causes
404 		// the cache's mutex to be locked twice when starting the runtime_loader
405 		// itself.
406 		return 1;
407 	}
408 
409 #if DEBUG_RLD
410 	close(0); open("/dev/console", 0); /* stdin   */
411 	close(1); open("/dev/console", 0); /* stdout  */
412 	close(2); open("/dev/console", 0); /* stderr  */
413 #endif
414 
415 	if (heap_init() < B_OK)
416 		return 1;
417 
418 	rldexport_init();
419 	rldelf_init();
420 
421 	load_program(gProgramArgs->program_path, &entry);
422 
423 	if (entry == NULL)
424 		return -1;
425 
426 	// call the program entry point (usually _start())
427 	returnCode = ((int (*)(int, void *, void *))entry)(gProgramArgs->arg_count,
428 		gProgramArgs->args, gProgramArgs->env);
429 
430 	terminate_program();
431 
432 	return returnCode;
433 }
434