2 * Init and cleanup code of libcaptive to be called by client application
3 * Copyright (C) 2002-2003 Jan Kratochvil <project-captive@jankratochvil.net>
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
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.
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
22 #include "init.h" /* self */
23 #include "captive/ldr.h"
24 #include "captive/ldr_exports.h"
25 #include "captive/unicode.h"
26 #include "captive/rtl-file.h"
27 #include <glib/gtypes.h>
28 #include <glib/gmessages.h>
29 #include "reactos/internal/ldr.h"
30 #include "reactos/napi/types.h"
31 #include "reactos/internal/kd.h" /* for KDB_LOADDRIVER_HOOK */
33 #include <sys/mman.h> /* for PROT_READ, MAP_SHARED */
34 #include "reactos/ddk/kefuncs.h" /* for KeInitializeSpinLock() */
35 #include "reactos/internal/ntoskrnl.h" /* for IoInit() */
36 #include "reactos/internal/ps.h" /* for PsInitProcessManagment() and PsInitThreadManagment() */
37 #include "reactos/ddk/iofuncs.h" /* for IoCreateFile() */
38 #include "captive/storage.h"
39 #include "captive/signal.h" /* for captive_signal_init() */
40 #include "reactos/ddk/psfuncs.h" /* for PsGetCurrentThread() */
43 #include <glib/gstrfuncs.h>
44 #include <glib/glist.h>
45 #include "giochannel-blind.h"
46 #include <glib-object.h>
47 #include "reactos/internal/se.h" /* for SeInit2() */
48 #include "captive/leave.h"
49 #include "captive/options.h"
50 #include <libgnomevfs/gnome-vfs-result.h>
52 #include <reactos/ddk/obfuncs.h>
54 #include "captive/macros.h"
55 #include "../storage/relastblock.h" /* for captive_storage_relastblock() */
58 struct captive_options *captive_options;
60 /* Are we initialized? */
61 static gboolean active;
63 /* Module of fs module itself loaded by captive_w32_init() */
64 static PMODULE_OBJECT ModuleObject;
66 /* Driver in fs module loaded by captive_w32_init() */
67 DRIVER_OBJECT captive_DriverObject;
68 PDRIVER_REINITIALIZE captive_DriverObject_ReinitRoutine;
69 PVOID captive_DriverObject_ReinitRoutine_Context;
71 /* Structure holding the pointer to the toplevel IRP */
72 static TOP_LEVEL_IRP TopLevelIrp; /* TODO:thread */
75 void *_local_unwind2_addr;
78 gboolean captive_debug_messages_disabled=FALSE;
80 static gboolean captive_w32_init(void)
85 g_return_val_if_fail(captive_options!=NULL,FALSE);
86 g_return_val_if_fail(captive_options->filesystem.type!=CAPTIVE_OPTIONS_MODULE_TYPE_EMPTY,FALSE);
88 /* captive_giochannel_size() only _after_ g_io_channel_set_encoding() ! */
89 captive_image_size=captive_giochannel_size(captive_image_iochannel);
90 g_return_val_if_fail(captive_image_size>0,FALSE);
92 /* Part of reactos/ntoskrnl/ke/main.c/KiSystemStartup() begins. */
93 /* ExpInitializeExecutive(); */
94 /* Part of reactos/ntoskrnl/ke/main.c/ExpInitializeExecutive() begins
95 * here as the rest of the function does a lot of hardware initializations.
98 /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInit1() begins. */
99 InitializeListHead(&ModuleTextListHead);
100 /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInit1() ends. */
101 KeLowerIrql(DISPATCH_LEVEL);
103 /* FIXME: create default nls tables? Really still needed? */
104 /* Obsolete: RtlpInitNlsTables(); */
108 KeInitializeDispatcher();
110 KeLowerIrql(PASSIVE_LEVEL);
112 g_assert(errbool==TRUE);
115 g_assert(errbool==TRUE);
116 /* PiInitProcessManager(); */
117 /* Part of reactos/ntoskrnl/ps/psmgr.c/PiInitProcessManager() begins. */
118 PsInitProcessManagment();
119 PsInitThreadManagment();
120 /* Part of reactos/ntoskrnl/ps/psmgr.c/PiInitProcessManager() ends. */
124 /* LdrInitModuleManagement(); */
125 /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInitModuleManagement() begins
126 * here as the rest "Create module object for {NTOSKRNL,HAL}"
127 * is dependent on {NTOSKRNL,HAL} PE image headers not provided by libcaptive.
129 /* Initialize the module list and spinlock */
130 InitializeListHead(&ModuleListHead);
131 KeInitializeSpinLock(&ModuleListLock);
132 /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInitModuleManagement ends. */
135 NtInitializeEventImplementation();
137 /* Part of reactos/ntoskrnl/ke/main.c/ExpInitializeExecutive() ends. */
138 /* Part of reactos/ntoskrnl/ke/main.c/KiSystemStartup() ends. */
140 /* Simulate our PE headers and export the symbols of our complete libraries */
141 captive_kernel_exports();
143 errbool=captive_cdrom_init();
144 g_return_val_if_fail(errbool==TRUE,FALSE);
145 errbool=captive_disk_init();
146 g_return_val_if_fail(errbool==TRUE,FALSE);
148 while (captive_options->load_module) {
149 PMODULE_OBJECT ModuleObject_tmp;
152 /* load the module */
153 err=captive_LdrLoadModule(
154 captive_options->load_module->data,
155 &ModuleObject_tmp); /* ModuleObjectp */
156 g_return_val_if_fail(NT_SUCCESS(err),FALSE);
158 captive_options_module_free(captive_options->load_module->data);
159 /* also frees 'options->load_module->data' */
160 captive_options->load_module=g_list_delete_link(captive_options->load_module,captive_options->load_module);
163 /* Patch 'ntoskrnl.exe' loaded by 'captive_options->load_module' above. */
165 CHAR *KeNumberProcessorsp=captive_Module_GetExportAddress("ntoskrnl.exe","KeNumberProcessors");
167 g_assert(*KeNumberProcessorsp==0);
168 *KeNumberProcessorsp=KeNumberProcessors;
169 g_assert(*KeNumberProcessorsp==1);
171 /* Apply AFTER any symbols sanity checks above! */
172 if (captive_options->debug_messages)
173 captive_kernel_patches_debug();
175 captive_kernel_patches_nondebug();
177 _local_unwind2_addr=captive_Module_GetExportAddress("ntoskrnl.exe","_local_unwind2");
179 /* Initialize 'FsRtlLegalAnsiCharacterArray'.
180 * It requires 'ntoskrnl.exe' loaded by 'captive_options->load_module' above;
181 * captive_kernel_patches_debug()/captive_kernel_patches_nondebug() should not be needed.
183 captive_FsRtlLegalAnsiCharacterArray_init();
185 /* set TopLevelIrp() - FIXME: where is it set by native reactos? */
186 PsGetCurrentThread()->TopLevelIrp=&TopLevelIrp; /* otherwise Io{Get,Set}TopLevelIrp() would SIGSEGV */
188 /* Begin possible handling of foreign W32 binary code here */
189 /* If you want to disable SIGSEGV handler if not needed:
190 * if (ModuleObject->Flags & MODULE_FLAG_PE)
192 captive_signal_init();
194 /* You must have already captive_signal_init() passed here as the module may
195 * call some functions from W32 ntoskrnl.exe.
197 captive_DriverObject_ReinitRoutine=NULL;
198 err=captive_LdrpLoadAndCallImage(
199 &ModuleObject, /* ModuleObjectp */
200 &captive_options->filesystem, /* options_module */
201 &captive_DriverObject, /* DriverEntry_DriverObject */
202 captive_utf8_to_UnicodeString_alloca("\\captive\\filesystem")); /* DriverEntry_RegistryPath */
203 g_return_val_if_fail(NT_SUCCESS(err),FALSE);
204 if (captive_DriverObject_ReinitRoutine) {
205 captive_stdcall_call_12((CaptiveStdCallFunc12)captive_DriverObject_ReinitRoutine,
206 &captive_DriverObject, /* DriverObject */
207 captive_DriverObject_ReinitRoutine_Context, /* Context */
208 (gpointer)1); /* Count: # of calls of ReinitRoutine incl. the current one */
215 static void captive_log_init_g_log_func_discard
216 (const gchar *log_domain,GLogLevelFlags log_level,const gchar *message,gpointer user_data)
218 g_return_if_fail(message!=NULL);
223 static void captive_log_init_g_log_func
224 (const gchar *log_domain,GLogLevelFlags log_level,const gchar *message,gpointer user_data /* unused */)
228 g_return_if_fail(message!=NULL);
230 /* unused: LOG_EMERG */
231 /* unused: LOG_ALERT */
232 /**/ if (log_level&G_LOG_LEVEL_ERROR)
234 else if (log_level&G_LOG_LEVEL_CRITICAL)
236 else if (log_level&G_LOG_LEVEL_WARNING)
237 priority=LOG_WARNING;
238 else if (log_level&G_LOG_LEVEL_MESSAGE)
240 else if (log_level&G_LOG_LEVEL_INFO)
242 else if (log_level&G_LOG_LEVEL_DEBUG)
245 priority=LOG_WARNING;
247 syslog(priority,"%s%s%s",
248 (!(log_level&G_LOG_FLAG_RECURSION) ? "" : "RECURSION: "),
249 (!(log_level&G_LOG_FLAG_FATAL ) ? "" : "FATAL: "),
253 void captive_log_init(const struct captive_options *captive_options)
255 g_return_if_fail(captive_options!=NULL);
257 /* FIXME: Fix sharing of different 'debug_messages' for various sandboxes. */
258 captive_debug_messages_disabled=!captive_options->debug_messages;
260 /* FIXME: Fix sharing of different 'debug_messages' for various sandboxes. */
261 if (!captive_options->debug_messages) {
262 /* FIXME: Save handler_id and destroy it in captive_vfs_close(). */
264 G_LOG_DOMAIN, /* log_domain; "Captive" */
266 | G_LOG_FLAG_RECURSION
268 /* The same mask is in:
269 * libcaptive/sandbox/server-GLogFunc.c
270 * libcaptive/client/init.c
272 | G_LOG_LEVEL_MESSAGE
275 captive_log_init_g_log_func_discard, /* log_func */
276 NULL); /* user_data */
278 /* We are not the sandboxed slave;
279 * 'syslog_facility' would be '-1' in slave anyway as it is not transferred through CORBA.
281 if (!captive_options->sandbox || (captive_options->sandbox_server_argv || captive_options->sandbox_server_ior)) {
282 if (captive_options->syslog_facility!=-1) {
284 /* FIXME: Prefix 'ident' by device/mountpoint. */
285 G_LOG_DOMAIN, /* ident; "Captive"; FIXME: lowercase it for syslog(3)? */
286 LOG_CONS|LOG_PID, /* options */
287 captive_options->syslog_facility); /* facility */
288 /* FIXME: Save handler_id and destroy it in captive_vfs_close(). */
290 G_LOG_DOMAIN, /* log_domain; "Captive" */
292 | 0 /* !G_LOG_FLAG_RECURSION */
294 | (G_LOG_LEVEL_MASK & ~(captive_options->debug_messages ? 0 : 0
295 /* The same mask is in:
296 * libcaptive/sandbox/server-GLogFunc.c
297 * libcaptive/client/init.c
299 | G_LOG_LEVEL_MESSAGE
301 | G_LOG_LEVEL_DEBUG)),
302 (GLogFunc)captive_log_init_g_log_func, /* log_func */
303 NULL); /* user_data */
311 * Expects #captive_options: Parsed by captive_options_parse().
312 * %NULL value is forbidden. Field #image_iochannel %NULL value is forbidden.
314 * Initializes %libcaptive and loads the specified filesystem.
316 * Returns: %TRUE if successfuly initialized.
318 gboolean captive_init(void)
322 /* We are in sandbox child and we have the right to fail. */
323 g_log_set_always_fatal(~(0
329 g_return_val_if_fail(active==FALSE,FALSE);
331 g_return_val_if_fail(captive_options!=NULL,FALSE);
332 g_return_val_if_fail(captive_options->image_iochannel!=NULL,FALSE);
334 /* Initialize GObject subsystem of GLib. */
337 captive_log_init(captive_options);
339 captive_image_iochannel=captive_options->image_iochannel;
340 g_io_channel_ref(captive_image_iochannel);
342 captive_image_iochannel=captive_storage_relastblock(captive_image_iochannel);
344 if (captive_options->rwmode==CAPTIVE_OPTION_RWMODE_BLIND) {
345 GIOChannel *captive_image_iochannel_orig;
347 captive_image_iochannel_orig=captive_image_iochannel;
348 captive_image_iochannel=(GIOChannel *)captive_giochannel_blind_new(captive_image_iochannel,
349 TRUE); /* writeable */
350 g_io_channel_unref(captive_image_iochannel_orig); /* reffed by captive_giochannel_blind_new() */
353 /* Do not initialize 'captive_image_size' by captive_giochannel_size() here
354 * as we yet need to do g_io_channel_set_encoding().
357 errbool=captive_w32_init();
358 g_return_val_if_fail(errbool==TRUE,FALSE);
365 static void dismount_volume(void)
367 IO_STATUS_BLOCK IoStatusBlock;
368 PIO_STACK_LOCATION StackPtr;
371 DEVICE_OBJECT *DeviceObject=captive_DriverObject.DeviceObject;
372 OBJECT_ATTRIBUTES dir_ObjectAttributes;
374 FILE_OBJECT *FileObject;
375 GnomeVFSResult errvfsresult;
377 IO_STATUS_BLOCK dir_IoStatusBlock;
379 static const ULONG fsctls[2]={ FSCTL_LOCK_VOLUME,FSCTL_DISMOUNT_VOLUME };
384 errvfsresult=captive_ObjectAttributes_init("/!Captive!del",&dir_ObjectAttributes);
385 g_return_if_fail(errvfsresult==GNOME_VFS_OK);
387 /* wanted: * IoCreateFile()->ObCreateObject(,,,IoFileObjectType)->
388 * ->(IoFileObjectType->Create==IopCreateFile)()->IoMountVolume()
390 CAPTIVE_MEMZERO(&dir_IoStatusBlock); /* FIXME: Try to pre-clear it - uninitialized otherwise? */
391 dir_IoStatusBlock.Information=FILE_OPENED; /* FIXME: Try to pre-set it - uninitialized otherwise? */
393 &dir_Handle, /* FileHandle */
394 GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE|0x80, /* DesiredAccess; 0xC0100080=GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE|0x80 */
395 &dir_ObjectAttributes, /* ObjectAttributes */
396 &dir_IoStatusBlock, /* IoStatusBlock */
397 NULL, /* AllocationSize; ignored for open */
398 FILE_ATTRIBUTE_NORMAL, /* FileAttributes; ignored for open */
399 (FILE_SHARE_READ | FILE_SHARE_WRITE), /* ShareAccess; 0 means exclusive */
400 FILE_OPEN, /* CreateDisposition */
401 /* FILE_SYNCHRONOUS_IO_{,NON}ALERT: We need to allow W32 filesystem
402 * any waits to not to let it return STATUS_CANT_WAIT us.
403 * Alertability should have only effect on asynchronous events
404 * from KeWaitForSingleObject() by setting/clearing its parameter 'Alertable'.
406 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE, /* CreateOptions; FILE_DIRECTORY_FILE is forbidden */
409 CreateFileTypeNone, /* CreateFileType */
410 NULL, /* ExtraCreateParameters */
412 g_free(dir_ObjectAttributes.ObjectName); /* left from captive_gnomevfs_uri_parent_init() */
413 g_return_if_fail(NT_SUCCESS(err));
414 g_return_if_fail(NT_SUCCESS(err)==NT_SUCCESS(dir_IoStatusBlock.Status));
415 g_return_if_fail(dir_IoStatusBlock.Information==FILE_OPENED);
417 Status=ObReferenceObjectByHandle(dir_Handle,FILE_LIST_DIRECTORY,IoFileObjectType,UserMode,(PVOID *)&FileObject,NULL);
418 g_assert(NT_SUCCESS(Status));
420 g_assert(FileObject->FileName.Length==0);
421 /* 'FileObject->FileName.MaximumLength' is not reset by IoCreateFile(). */
422 g_assert(FileObject->FileName.Buffer==NULL);
423 FileObject->FileName.MaximumLength=2;
424 FileObject->FileName.Buffer=&wzero;
427 for (fsctlsi=0;fsctlsi<2;fsctlsi++)
430 Irp=IoAllocateIrp(DeviceObject->StackSize,TRUE);
431 g_return_if_fail(Irp!=NULL);
433 Irp->UserIosb=&IoStatusBlock;
434 Irp->UserEvent=&FileObject->Event;
435 Irp->Tail.Overlay.Thread=PsGetCurrentThread();
437 StackPtr=IoGetNextIrpStackLocation(Irp);
439 StackPtr->MajorFunction=IRP_MJ_FILE_SYSTEM_CONTROL;
440 StackPtr->MinorFunction=IRP_MN_USER_FS_REQUEST;
442 StackPtr->MajorFunction=IRP_MJ_FLUSH_BUFFERS;
446 StackPtr->DeviceObject=DeviceObject; /* FIXME: FileObject->Vpb->DeviceObject ? */
447 StackPtr->FileObject=FileObject;
448 StackPtr->CompletionRoutine=NULL;
451 StackPtr->Parameters.FileSystemControl.OutputBufferLength=0;
452 StackPtr->Parameters.FileSystemControl.InputBufferLength=0;
453 StackPtr->Parameters.FileSystemControl.FsControlCode=fsctls[fsctlsi];
454 StackPtr->Parameters.FileSystemControl.Type3InputBuffer=NULL;
457 /* IoCallDriver() will do one ObDereferenceObject(FileObject)
458 * in its IoSecondStageCompletion().
459 * Do not leave to dereference it itself as we need its 'FileObject->Event'.
461 ObReferenceObject(FileObject);
463 Status=IoCallDriver(DeviceObject,Irp);
464 if (Status==STATUS_PENDING) {
465 KeWaitForSingleObject(&FileObject->Event,Executive,KernelMode,FALSE,NULL);
466 Status=IoStatusBlock.Status;
468 g_assert(NT_SUCCESS(Status)
469 || (Status==STATUS_MEDIA_WRITE_PROTECTED && captive_options->rwmode==CAPTIVE_OPTION_RWMODE_RO));
472 ObDereferenceObject(FileObject);
476 BOOLEAN captive_cc_FileObject_delete(FILE_OBJECT *FileObject);
477 void captive_cc_flush(void);
482 * Closes down %libcaptive. It should flush all pending buffers and successfuly
483 * close the filesystem. Variable #captive_options->image_iochannel will not be set to %NULL,
484 * you should close such channel yourself.
486 * Returns: %TRUE if successfuly shutdown.
488 gboolean captive_shutdown(void)
490 GIOStatus erriostatus;
492 g_return_val_if_fail(active==TRUE,FALSE);
493 g_return_val_if_fail(captive_image_iochannel!=NULL,FALSE);
494 g_return_val_if_fail(captive_options->image_iochannel!=NULL,FALSE);
496 /* Invoke all pending idle functions just to not to forget for anything... */
497 while (g_main_context_iteration(
498 NULL, /* context; NULL means default one */
499 FALSE)) /* may_block */
500 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: g_main_context_iteration() proceeded",G_STRLOC);
502 /* Do not: captive_cc_flush(); * based on captive_leave(), not g_main idle *
503 * replaced by IRP_MJ_FLUSH_BUFFERS.
508 /* Invoke all pending idle functions just to not to forget for anything... */
509 while (g_main_context_iteration(
510 NULL, /* context; NULL means default one */
511 FALSE)) /* may_block */
512 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: g_main_context_iteration() proceeded",G_STRLOC);
515 captive_PoQueueShutdownWorkItem_hooklist_invoke();
518 /* Do not: captive_cc_flush();
519 * as the dirty blocks should have been already commited by dismount_volume(),
520 * any further commits would get us just STATUS_VOLUME_DISMOUNTED.
523 /* Do not: captive_cc_unmounting=TRUE;
524 * Without dismount_volume() it was:
525 * During IoShutdownRegisteredFileSystems() - IRP_MJ_SHUTDOWN to be specific
526 * some buffers will be written but after the IofCallDriver() it will be
527 * no longer possible to flush such buffers to their DeviceVolumeFile.
528 * Therefore we must flush such buffers on the fly although such behaviour
529 * would crash us in regular case as filesystems access BCBs even after their
531 * Currently the dirty blocks should have been already commited by dismount_volume(),
534 /* FIXME: ntoskrnl/ex/power.c/NtShutdownSystem() does
535 * IoShutdownRegistered{Devices,FileSystems} order; is it correct?
537 IoShutdownRegisteredFileSystems();
539 /* Do not: captive_cc_FileObject_delete(NULL);
540 * as the dirty blocks should have been already commited by dismount_volume(),
541 * any further commits would get us just STATUS_VOLUME_DISMOUNTED.
544 IoShutdownRegisteredDevices();
546 /* Just a sanity if 'captive_image_iochannel' is already reffed a bit more... */
547 erriostatus=g_io_channel_flush(
548 captive_image_iochannel, /* channel */
550 g_assert(erriostatus==G_IO_STATUS_NORMAL);
552 g_io_channel_unref(captive_image_iochannel);
553 captive_image_iochannel=NULL;