[interp] Fix resuming from finally block (#8195)
[mono-project.git] / mono / mini / main.c
blob0192135f7d17cfd81bc5d301ec8642bc92a83bf9
1 /**
2 * \file
3 * The main entry point for the mono executable
5 * The main entry point does a few things:
6 *
7 * * It probes whether the executable has a bundle appended
8 * at the end, and if so, registers the various bundled
9 * resources with Mono and executes the contained bundle
11 * * Parses the MONO_ENV_OPTIONS variable to treat the
12 * contents of the variable as command line arguments for
13 * the mono runtime
15 * * Launches Mono, by calling mono_main.
17 #include <config.h>
18 #include <fcntl.h>
19 #ifndef HOST_WIN32
20 #include <dirent.h>
21 #endif
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/mono-config.h>
24 #include <mono/utils/mono-mmap.h>
25 #include <mono/utils/mono-dl.h>
26 #include "mini.h"
27 #include "mini-runtime.h"
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32 #ifdef HOST_WIN32
33 # include <io.h>
34 #else
35 # ifndef BUILDVER_INCLUDED
36 # include "buildver-boehm.h"
37 # endif
38 #endif
41 * If the MONO_ENV_OPTIONS environment variable is set, it uses this as a
42 * source of command line arguments that are passed to Mono before the
43 * command line arguments specified in the command line.
45 static int
46 mono_main_with_options (int argc, char *argv [])
48 mono_parse_env_options (&argc, &argv);
50 return mono_main (argc, argv);
54 * The Mono executable can initialize itself from a payload attached
55 * at the end of the main program. The payload contains the
56 * main assembly, one or more managed assemblies, configuration
57 * files and other assets that are used instead of launching a
58 * program from the command line.
60 * The startup sequence probes for a magical signature at the end of
61 * the executable, if the 16 characters "xmonkeysloveplay" are found,
62 * the code expects the 64-bits just before it to contain an offset
63 * within the executable with a directory of assets.
65 * All pointers in the file format are encoded as little-endian values
67 * The format of the file is thus:
69 * Location Content
70 * -------- -------
71 * lenght-16 Optional "xmonkeysloveplay", indicating that a
72 * bundled payload is contained in the executable.
73 * length-24 pointer to the directory in the file, address DIR
75 * DIR 32-bit value with the number of entries in the directory
76 * DIR+4 First directory entry.
78 * Each directory entry is made up of:
79 * 4-bytes uint32_t containing the size of a string (STR)
80 * STRING UTF8 encoded and \0 terminated string
81 * 8-bytes uint64_t offset in the file with the payload associated with STRING
82 * 4-bytes uint32_t size of the asset
84 * The following are the known directory entries, without the quotes:
85 * "assembly:NAME" An assembly with the name NAME, assembly is in the payload
86 * "config:NAME" A configuration file (usually file.dll.config) in the payload that is
87 * loaded as the config file for an assembly
88 * "systemconfig:" Treats as a Mono system configuration, payload contains the config file.
89 * "options:" The payload contains command line options to initialize Mono, as if you
90 had set them on MONO_ENV_OPTIONS
91 * "config_dir:DIR" Configures the MONO_PATH to point to point to DIR
92 * "machineconfig:" The payload contains the machine.config file to use at runtime
93 * "env:" Sets the environment variable to the value encoded in the payload
94 * payload contains: 1-byte lenght for the \0 terminated variable,
95 * followed by the value.
96 * "library:NAME" Bundled dynamic library NAME, payload contains the dynamic library
98 #define STREAM_INT(x) GUINT32_TO_LE((*(uint32_t*)x))
99 #define STREAM_LONG(x) GUINT64_TO_LE((*(uint64_t*)x))
102 * Loads a chunk of data from the file pointed to by the
103 * @fd starting at the file offset @offset for @size bytes
104 * and returns an allocated version of that string, or NULL
105 * on error.
107 static char *
108 load_from_region (int fd, uint64_t offset, uint64_t size)
110 char *buffer;
111 off_t loc;
112 int status;
114 do {
115 loc = lseek (fd, offset, SEEK_SET);
116 } while (loc == -1 && errno == EINTR);
117 if (loc == -1)
118 return NULL;
119 buffer = g_malloc (size + 1);
120 if (buffer == NULL)
121 return NULL;
122 buffer [size] = 0;
123 do {
124 status = read (fd, buffer, size);
125 } while (status == -1 && errno == EINTR);
126 if (status == -1){
127 g_free (buffer);
128 return NULL;
130 return buffer;
133 /* Did we initialize the temporary directory for dynamic libraries */
134 static int bundle_save_library_initialized;
136 /* List of bundled libraries we unpacked */
137 static GSList *bundle_library_paths;
139 /* Directory where we unpacked dynamic libraries */
140 static char *bundled_dylibrary_directory;
142 static void
143 delete_bundled_libraries (void)
145 GSList *list;
147 for (list = bundle_library_paths; list != NULL; list = list->next){
148 unlink (list->data);
150 rmdir (bundled_dylibrary_directory);
153 static void
154 bundle_save_library_initialize (void)
156 bundle_save_library_initialized = 1;
157 char *path = g_build_filename (g_get_tmp_dir (), "mono-bundle-XXXXXX", NULL);
158 bundled_dylibrary_directory = g_mkdtemp (path);
159 g_free (path);
160 if (bundled_dylibrary_directory == NULL)
161 return;
162 atexit (delete_bundled_libraries);
165 static void
166 save_library (int fd, uint64_t offset, uint64_t size, const char *destfname)
168 MonoDl *lib;
169 char *file, *buffer, *err, *internal_path;
170 if (!bundle_save_library_initialized)
171 bundle_save_library_initialize ();
173 file = g_build_filename (bundled_dylibrary_directory, destfname, NULL);
174 buffer = load_from_region (fd, offset, size);
175 g_file_set_contents (file, buffer, size, NULL);
177 lib = mono_dl_open (file, MONO_DL_LAZY, &err);
178 if (lib == NULL){
179 fprintf (stderr, "Error loading shared library: %s %s\n", file, err);
180 exit (1);
182 // Register the name with "." as this is how it will be found when embedded
183 internal_path = g_build_filename (".", destfname, NULL);
184 mono_loader_register_module (internal_path, lib);
185 g_free (internal_path);
186 bundle_library_paths = g_slist_append (bundle_library_paths, file);
188 g_free (buffer);
191 #ifndef HOST_WIN32
192 static gboolean
193 search_directories(const char *envPath, const char *program, char **new_program)
195 gchar **paths = NULL;
196 gint i;
198 paths = g_strsplit (envPath, G_SEARCHPATH_SEPARATOR_S, 0);
199 g_assert (paths);
201 for (i = 0; paths [i]; ++i) {
202 gchar *path = paths [i];
203 gint path_len = strlen (path);
204 DIR *dir;
205 struct dirent *ent;
207 if (path_len == 0)
208 continue;
210 dir = opendir (path);
211 if (!dir)
212 continue;
214 while ((ent = readdir (dir))){
215 if (!strcmp (ent->d_name, program)){
216 *new_program = g_strdup_printf ("%s%s%s", path, path [path_len - 1] == '/' ? "" : "/", program);
217 closedir (dir);
218 g_strfreev (paths);
219 return TRUE;
223 closedir (dir);
226 *new_program = NULL;
227 g_strfreev (paths);
228 return FALSE;
230 #endif
232 static gboolean
233 probe_embedded (const char *program, int *ref_argc, char **ref_argv [])
235 MonoBundledAssembly last = { NULL, 0, 0 };
236 char sigbuffer [16+sizeof (uint64_t)];
237 gboolean status = FALSE;
238 uint64_t directory_location;
239 off_t sigstart, baseline = 0;
240 uint64_t directory_size;
241 char *directory, *p;
242 int items, i;
243 unsigned char *mapaddress = NULL;
244 void *maphandle = NULL;
245 GArray *assemblies;
246 char *entry_point = NULL;
247 char **new_argv;
248 int j;
250 int fd = open (program, O_RDONLY);
251 #ifndef HOST_WIN32
252 if (fd == -1){
253 // Also search through the PATH in case the program was run from a different directory
254 gchar* envPath = getenv ("PATH");
255 if (envPath){
256 gchar *new_program = NULL;
257 if (search_directories (envPath, program, &new_program)){
258 fd = open (new_program, O_RDONLY);
259 g_free (new_program);
260 new_program = NULL;
264 #endif
265 if (fd == -1)
266 return FALSE;
267 if ((sigstart = lseek (fd, -24, SEEK_END)) == -1)
268 goto doclose;
269 if (read (fd, sigbuffer, sizeof (sigbuffer)) == -1)
270 goto doclose;
271 if (memcmp (sigbuffer+sizeof(uint64_t), "xmonkeysloveplay", 16) != 0)
272 goto doclose;
273 directory_location = GUINT64_FROM_LE ((*(uint64_t *) &sigbuffer [0]));
274 if (lseek (fd, directory_location, SEEK_SET) == -1)
275 goto doclose;
276 directory_size = sigstart-directory_location;
277 directory = g_malloc (directory_size);
278 if (directory == NULL)
279 goto doclose;
280 if (read (fd, directory, directory_size) == -1)
281 goto dofree;
283 items = STREAM_INT (directory);
284 p = directory+4;
286 assemblies = g_array_new (0, 0, sizeof (MonoBundledAssembly*));
287 for (i = 0; i < items; i++){
288 char *kind;
289 int strsize = STREAM_INT (p);
290 uint64_t offset, item_size;
291 kind = p+4;
292 p += 4 + strsize;
293 offset = STREAM_LONG(p);
294 p += 8;
295 item_size = STREAM_INT (p);
296 p += 4;
298 if (mapaddress == NULL){
299 mapaddress = mono_file_map (directory_location-offset, MONO_MMAP_READ | MONO_MMAP_PRIVATE, fd, offset, &maphandle);
300 if (mapaddress == NULL){
301 perror ("Error mapping file");
302 exit (1);
304 baseline = offset;
306 if (strncmp (kind, "assembly:", strlen ("assembly:")) == 0){
307 char *aname = kind + strlen ("assembly:");
308 MonoBundledAssembly mba = { aname, mapaddress + offset - baseline, item_size }, *ptr;
309 ptr = g_new (MonoBundledAssembly, 1);
310 memcpy (ptr, &mba, sizeof (MonoBundledAssembly));
311 g_array_append_val (assemblies, ptr);
312 if (entry_point == NULL)
313 entry_point = aname;
314 } else if (strncmp (kind, "config:", strlen ("config:")) == 0){
315 char *config = kind + strlen ("config:");
316 char *aname = g_strdup (config);
317 aname [strlen(aname)-strlen(".config")] = 0;
318 mono_register_config_for_assembly (aname, load_from_region (fd, offset, item_size));
319 } else if (strncmp (kind, "systemconfig:", strlen ("systemconfig:")) == 0){
320 mono_config_parse_memory (load_from_region (fd, offset, item_size));
321 } else if (strncmp (kind, "options:", strlen ("options:")) == 0){
322 mono_parse_options_from (load_from_region (fd, offset, item_size), ref_argc, ref_argv);
323 } else if (strncmp (kind, "config_dir:", strlen ("config_dir:")) == 0){
324 mono_set_dirs (getenv ("MONO_PATH"), load_from_region (fd, offset, item_size));
325 } else if (strncmp (kind, "machineconfig:", strlen ("machineconfig:")) == 0) {
326 mono_register_machine_config (load_from_region (fd, offset, item_size));
327 } else if (strncmp (kind, "env:", strlen ("env:")) == 0){
328 char *data = load_from_region (fd, offset, item_size);
329 uint8_t count = *data++;
330 char *value = data + count + 1;
331 g_setenv (data, value, FALSE);
332 } else if (strncmp (kind, "library:", strlen ("library:")) == 0){
333 save_library (fd, offset, item_size, kind + strlen ("library:"));
334 } else {
335 fprintf (stderr, "Unknown stream on embedded package: %s\n", kind);
336 exit (1);
339 g_array_append_val (assemblies, last);
341 mono_register_bundled_assemblies ((const MonoBundledAssembly **) assemblies->data);
342 new_argv = g_new (char *, (*ref_argc)+1);
343 new_argv [0] = (*ref_argv)[0];
344 new_argv [1] = entry_point;
345 for (j = 1; j < *ref_argc; j++)
346 new_argv [j+1] = (*ref_argv)[j];
347 *ref_argv = new_argv;
348 (*ref_argc)++;
350 return TRUE;
352 dofree:
353 g_free (directory);
354 doclose:
355 if (!status)
356 close (fd);
357 return status;
360 #ifdef HOST_WIN32
362 #include <shellapi.h>
365 main (void)
367 TCHAR szFileName[MAX_PATH];
368 int argc;
369 gunichar2** argvw;
370 gchar** argv;
371 int i;
372 DWORD count;
374 argvw = CommandLineToArgvW (GetCommandLine (), &argc);
375 argv = g_new0 (gchar*, argc + 1);
376 for (i = 0; i < argc; i++)
377 argv [i] = g_utf16_to_utf8 (argvw [i], -1, NULL, NULL, NULL);
378 argv [argc] = NULL;
380 LocalFree (argvw);
382 if ((count = GetModuleFileName (NULL, szFileName, MAX_PATH)) != 0){
383 char *entry = g_utf16_to_utf8 (szFileName, count, NULL, NULL, NULL);
384 probe_embedded (entry, &argc, &argv);
387 return mono_main_with_options (argc, argv);
390 #else
393 main (int argc, char* argv[])
395 mono_build_date = build_date;
397 probe_embedded (argv [0], &argc, &argv);
398 return mono_main_with_options (argc, argv);
401 #endif