Finished and deployed CORBA sandbox separation
[captive.git] / src / libcaptive / client / init.c
1 /* $Id$
2  * Init and cleanup code of libcaptive to be called by client application
3  * Copyright (C) 2002 Jan Kratochvil <project-captive@jankratochvil.net>
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; exactly version 2 of June 1991 is required
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19
20 #include "config.h"
21
22 #include "captive/ldr.h"
23 #include "captive/ldr_exports.h"
24 #include "captive/unicode.h"
25 #include "captive/rtl-file.h"
26 #include <glib/gtypes.h>
27 #include <glib/gmessages.h>
28 #include "reactos/internal/ldr.h"
29 #include "reactos/napi/types.h"
30 #include "reactos/internal/kd.h"        /* for KDB_LOADDRIVER_HOOK */
31 #include <fcntl.h>
32 #include <sys/mman.h>   /* for PROT_READ, MAP_SHARED */
33 #include "reactos/ddk/kefuncs.h"        /* for KeInitializeSpinLock() */
34 #include "reactos/internal/ntoskrnl.h"  /* for RtlpInitNlsTables() and IoInit() */
35 #include "reactos/internal/ps.h"        /* for PsInitProcessManagment() and PsInitThreadManagment() */
36 #include "reactos/ddk/iofuncs.h"        /* for IoCreateFile() */
37 #include "captive/storage.h"
38 #include "captive/signal.h"     /* for captive_signal_init() */
39 #include "reactos/ddk/psfuncs.h"        /* for PsGetCurrentThread() */
40 #include <stdio.h>
41 #include <popt.h>
42 #include <glib/gstrfuncs.h>
43 #include <glib/glist.h>
44 #include "giochannel-blind.h"
45 #include <glib-object.h>
46 #include "reactos/internal/se.h"        /* for SeInit2() */
47 #include "captive/leave.h"
48 #include "captive/options.h"
49
50
51 struct captive_options *captive_options;
52
53 /* Are we initialized? */
54 static gboolean active;
55
56 /* Module of fs module itself loaded by captive_w32_init() */
57 static PMODULE_OBJECT ModuleObject;
58
59 /* Driver in fs module loaded by captive_w32_init() */
60 DRIVER_OBJECT captive_DriverObject;
61 PDRIVER_REINITIALIZE captive_DriverObject_ReinitRoutine;
62 PVOID captive_DriverObject_ReinitRoutine_Context;
63
64 /* Structure holding the pointer to the toplevel IRP */
65 static TOP_LEVEL_IRP TopLevelIrp;       /* TODO:thread */
66
67
68 void *_local_unwind2_addr;
69
70
71 /* Acceleration hack for ntoskrnl/dbg/print.c/DbgPrint() */
72 gboolean captive_get_debug_messages(void)
73 {
74         g_return_val_if_fail(captive_options!=NULL,TRUE);
75
76         return captive_options->debug_messages;
77 }
78
79
80 static gboolean captive_w32_init(void)
81 {
82 NTSTATUS err;
83 gboolean errbool;
84 GIOStatus erriostatus;
85
86         g_return_val_if_fail(captive_options!=NULL,FALSE);
87         g_return_val_if_fail(captive_options->filesystem!=NULL,FALSE);
88
89         erriostatus=g_io_channel_set_encoding(captive_image_iochannel,
90                         NULL,   /* encoding; force binary data */
91                         NULL);  /* error */
92         g_assert(erriostatus==G_IO_STATUS_NORMAL);
93
94         /* captive_giochannel_size() only _after_ g_io_channel_set_encoding() ! */
95         captive_image_size=captive_giochannel_size(captive_image_iochannel);
96         g_return_val_if_fail(captive_image_size>0,FALSE);
97
98         /* Part of reactos/ntoskrnl/ke/main.c/KiSystemStartup() begins. */
99         /* ExpInitializeExecutive(); */
100                 /* Part of reactos/ntoskrnl/ke/main.c/ExpInitializeExecutive() begins
101                  * here as the rest of the function does a lot of hardware initializations.
102                  */
103                 /* LdrInit1(); */
104                         /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInit1() begins. */
105                         InitializeListHead(&ModuleTextListHead);
106                         /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInit1() ends. */
107                 KeLowerIrql(DISPATCH_LEVEL);
108                 /*...*/
109                 /* create default nls tables */
110                 RtlpInitNlsTables();
111                 /*...*/
112                 /* KeInit2() */
113                         /*...*/
114                         KeInitializeDispatcher();
115                         /*...*/
116                 KeLowerIrql(PASSIVE_LEVEL);
117                 errbool=SeInit1();
118                 g_assert(errbool==TRUE);
119                 ObInit();
120                 errbool=SeInit2();
121                 g_assert(errbool==TRUE);
122                 /* PiInitProcessManager(); */
123                         /* Part of reactos/ntoskrnl/ps/psmgr.c/PiInitProcessManager() begins. */
124                         PsInitProcessManagment();
125                         PsInitThreadManagment();
126                         /* Part of reactos/ntoskrnl/ps/psmgr.c/PiInitProcessManager() ends. */
127                 /*...*/
128                 IoInit();
129                 /*...*/
130                 /* LdrInitModuleManagement(); */
131                         /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInitModuleManagement() begins
132                          * here as the rest "Create module object for {NTOSKRNL,HAL}"
133                          * is dependent on {NTOSKRNL,HAL} PE image headers not provided by libcaptive.
134                          */
135                         /* Initialize the module list and spinlock */
136                         InitializeListHead(&ModuleListHead);
137                         KeInitializeSpinLock(&ModuleListLock);
138                         /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInitModuleManagement ends. */
139                 /*...*/
140                 /* Ntinit(); */
141                         NtInitializeEventImplementation();
142                         /*...*/
143                 /* Part of reactos/ntoskrnl/ke/main.c/ExpInitializeExecutive() ends. */
144         /* Part of reactos/ntoskrnl/ke/main.c/KiSystemStartup() ends. */
145
146         /* Simulate our PE headers and export the symbols of our complete libraries */
147         captive_kernel_exports();
148
149         errbool=captive_cdrom_init();
150         g_return_val_if_fail(errbool==TRUE,FALSE);
151         errbool=captive_disk_init();
152         g_return_val_if_fail(errbool==TRUE,FALSE);
153
154         while (captive_options->load_module) {
155 gchar *modulename=captive_options->load_module->data;
156 PMODULE_OBJECT ModuleObject_tmp;
157 NTSTATUS err;
158
159                 /* load the module */
160                 err=LdrLoadModule(
161                                 captive_utf8_to_UnicodeString_alloca(modulename),       /* ModuleName */
162                                 &ModuleObject_tmp);     /* ModuleObjectp */
163                 g_return_val_if_fail(NT_SUCCESS(err),FALSE);
164
165                 captive_options->load_module=g_list_remove(captive_options->load_module,modulename);
166                 }
167
168         /* Patch 'ntoskrnl.exe' loaded by 'captive_options->load_module' above. */
169         {
170         CHAR *KeNumberProcessorsp=captive_Module_GetExportAddress("ntoskrnl.exe","KeNumberProcessors");
171         
172                 g_assert(*KeNumberProcessorsp==0);
173                 *KeNumberProcessorsp=KeNumberProcessors;
174                 g_assert(*KeNumberProcessorsp==1);
175                 }
176         /* Apply captive_kernel_patches() AFTER any symbols sanity checks above! */
177         captive_kernel_patches();
178
179         _local_unwind2_addr=captive_Module_GetExportAddress("ntoskrnl.exe","_local_unwind2");
180
181         /* Initialize 'FsRtlLegalAnsiCharacterArray'.
182          * It requires 'ntoskrnl.exe' loaded by 'captive_options->load_module' above;
183          * captive_kernel_patches() should not be needed.
184          */
185         captive_FsRtlLegalAnsiCharacterArray_init();
186
187         /* set TopLevelIrp() - FIXME: where is it set by native reactos? */
188         PsGetCurrentThread()->TopLevelIrp=&TopLevelIrp; /* otherwise Io{Get,Set}TopLevelIrp() would SIGSEGV */
189
190         /* Begin possible handling of foreign W32 binary code here */
191         /* If you want to disable SIGSEGV handler if not needed:
192          *      if (ModuleObject->Flags & MODULE_FLAG_PE)
193          */
194         captive_signal_init();
195
196         /* You must have already captive_signal_init() passed here as the module may
197          * call some functions from W32 ntoskrnl.exe.
198          */
199         captive_DriverObject_ReinitRoutine=NULL;
200         err=captive_LdrpLoadAndCallImage(
201                         &ModuleObject,  /* ModuleObjectp */
202                         captive_utf8_to_UnicodeString_alloca(captive_options->filesystem),      /* ModuleName */
203                         &captive_DriverObject,  /* DriverEntry_DriverObject */
204                         captive_utf8_to_UnicodeString_alloca("\\captive\\filesystem")); /* DriverEntry_RegistryPath */
205         g_return_val_if_fail(NT_SUCCESS(err),FALSE);
206         if (captive_DriverObject_ReinitRoutine) {
207                 (*captive_DriverObject_ReinitRoutine)(
208                                 &captive_DriverObject,  /* DriverObject */
209                                 captive_DriverObject_ReinitRoutine_Context,     /* Context */
210                                 1);     /* Count: # of calls of ReinitRoutine incl. the current one */
211                 }
212
213         return TRUE;
214 }
215
216
217 static void     log_discard_func(const gchar *log_domain,GLogLevelFlags log_level,const gchar *message,gpointer user_data)
218 {
219         /* NOP */
220 }
221
222
223 /**
224  * captive_init:
225  *
226  * Expects #captive_options: Parsed by captive_options_parse().
227  * %NULL value is forbidden. Field #image_iochannel %NULL value is forbidden.
228  *
229  * Initializes %libcaptive and loads the specified filesystem.
230  *
231  * Returns: %TRUE if successfuly initialized.
232  */
233 gboolean captive_init(void)
234 {
235 gboolean errbool;
236
237 #ifdef MAINTAINER_MODE
238         g_log_set_always_fatal(~(0
239                         |G_LOG_LEVEL_MESSAGE
240                         |G_LOG_LEVEL_INFO
241                         |G_LOG_LEVEL_DEBUG
242                         ));
243 #endif
244
245         g_return_val_if_fail(active==FALSE,FALSE);
246
247         g_return_val_if_fail(captive_options!=NULL,FALSE);
248         g_return_val_if_fail(captive_options->image_iochannel!=NULL,FALSE);
249
250         /* Initialize GObject subsystem of GLib. */
251         g_type_init();
252
253         if (!captive_options->debug_messages) {
254                 g_log_set_handler(
255                                 G_LOG_DOMAIN,   /* log_domain; "Captive" */
256                                 0       /* log_levels */
257                                                 | G_LOG_FLAG_RECURSION
258                                                 | G_LOG_FLAG_FATAL
259                                                 /* The same mask is in libcaptive/sandbox/server-GlibLogFunc.c ! */
260                                                 | G_LOG_LEVEL_MESSAGE
261                                                 | G_LOG_LEVEL_INFO
262                                                 | G_LOG_LEVEL_DEBUG,
263                                 log_discard_func,       /* log_func */
264                                 NULL);  /* user_data */
265                 }
266
267         if (captive_options->rwmode==CAPTIVE_OPTION_RWMODE_BLIND)
268                 captive_image_iochannel=(GIOChannel *)captive_giochannel_blind_new(captive_options->image_iochannel);
269         else
270                 captive_image_iochannel=captive_options->image_iochannel;
271
272         /* Do not initialize 'captive_image_size' by captive_giochannel_size() here
273          * as we yet need to do g_io_channel_set_encoding().
274          */
275
276         errbool=captive_w32_init();
277         g_return_val_if_fail(errbool==TRUE,FALSE);
278
279         active=TRUE;
280         return TRUE;
281 }
282
283
284 BOOLEAN captive_cc_FileObject_delete(FILE_OBJECT *FileObject);
285 void captive_cc_flush(void);
286
287 /**
288  * captive_shutdown:
289  *
290  * Closes down %libcaptive. It should flush all pending buffers and successfuly
291  * close the filesystem. Variable #captive_options->image_iochannel will not be set to %NULL,
292  * you should close such channel yourself.
293  *
294  * Returns: %TRUE if successfuly shutdown.
295  */
296 gboolean captive_shutdown(void)
297 {
298 GIOStatus erriostatus;
299
300         g_return_val_if_fail(active==TRUE,FALSE);
301         g_return_val_if_fail(captive_image_iochannel!=NULL,FALSE);
302         g_return_val_if_fail(captive_options->image_iochannel!=NULL,FALSE);
303
304         /* Invoke all pending idle functions just to not to forget for anything... */
305         while (g_main_context_iteration(
306                         NULL,   /* context; NULL means default one */
307                         FALSE)) /* may_block */
308                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: g_main_context_iteration() proceeded",G_STRLOC);
309
310         captive_PoQueueShutdownWorkItem_hooklist_invoke();
311         captive_cc_flush();
312
313         /* During IoShutdownRegisteredFileSystems() - IRP_MJ_SHUTDOWN to be specific
314          * some buffers will be written but after the IofCallDriver() it will be
315          * no longer possible to flush such buffers to their DeviceVolumeFile.
316          * Therefore we must flush such buffers on the fly although such behaviour
317          * would crash us in regular case as filesystems access BCBs even after their
318          * CcUnpinData().
319          */
320         captive_cc_unmounting=TRUE;
321
322         /* FIXME: ntoskrnl/ex/power.c/NtShutdownSystem() does
323          * IoShutdownRegistered{Devices,FileSystems} order; is it correct?
324          */
325         IoShutdownRegisteredFileSystems();
326
327         /* Just a sanity check as all the dirty data should
328          * get already flushed during IoShutdownRegisteredFileSystems().
329          */
330         captive_cc_FileObject_delete(
331                         NULL);  /* FileObject */
332
333         IoShutdownRegisteredDevices();
334
335         /* libcaptive is not authorized to shutdown 'captive_image_channel'. */
336         erriostatus=g_io_channel_flush(
337                         captive_image_iochannel,        /* channel */
338                         NULL);  /* error */
339         g_assert(erriostatus==G_IO_STATUS_NORMAL);
340
341         /* 'captive_image_iochannel' may be blinded wrapper of 'captive_options->image_iochannel'. */
342         if (captive_image_iochannel!=captive_options->image_iochannel) {
343                 erriostatus=g_io_channel_flush(
344                                 captive_options->image_iochannel,       /* channel */
345                                 NULL);  /* error */
346                 g_assert(erriostatus==G_IO_STATUS_NORMAL);
347                 g_io_channel_unref(captive_image_iochannel);
348                 }
349
350         captive_image_iochannel=NULL;
351
352         active=FALSE;
353         return TRUE;
354 }