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() */
56 #include "../cc/sharedcachemap.h" /* for captive_shared_cache_map_flush_all() */
59 struct captive_options *captive_options;
61 /* Are we initialized? */
62 static gboolean active;
64 /* Module of fs module itself loaded by captive_w32_init() */
65 static PMODULE_OBJECT ModuleObject;
67 /* Driver in fs module loaded by captive_w32_init() */
68 DRIVER_OBJECT captive_DriverObject;
69 PDRIVER_REINITIALIZE captive_DriverObject_ReinitRoutine;
70 PVOID captive_DriverObject_ReinitRoutine_Context;
72 /* Structure holding the pointer to the toplevel IRP */
73 static TOP_LEVEL_IRP TopLevelIrp; /* TODO:thread */
76 void *_local_unwind2_addr;
79 gboolean captive_debug_messages_disabled=FALSE;
81 static gboolean captive_w32_init(void)
86 g_return_val_if_fail(captive_options!=NULL,FALSE);
87 g_return_val_if_fail(captive_options->filesystem.type!=CAPTIVE_OPTIONS_MODULE_TYPE_EMPTY,FALSE);
89 /* captive_giochannel_size() only _after_ g_io_channel_set_encoding() ! */
90 captive_image_size=captive_giochannel_size(captive_image_iochannel);
91 g_return_val_if_fail(captive_image_size>0,FALSE);
93 /* Part of reactos/ntoskrnl/ke/main.c/KiSystemStartup() begins. */
94 /* ExpInitializeExecutive(); */
95 /* Part of reactos/ntoskrnl/ke/main.c/ExpInitializeExecutive() begins
96 * here as the rest of the function does a lot of hardware initializations.
99 /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInit1() begins. */
100 InitializeListHead(&ModuleTextListHead);
101 /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInit1() ends. */
102 KeLowerIrql(DISPATCH_LEVEL);
104 /* FIXME: create default nls tables? Really still needed? */
105 /* Obsolete: RtlpInitNlsTables(); */
109 KeInitializeDispatcher();
111 KeLowerIrql(PASSIVE_LEVEL);
113 g_assert(errbool==TRUE);
116 g_assert(errbool==TRUE);
117 /* PiInitProcessManager(); */
118 /* Part of reactos/ntoskrnl/ps/psmgr.c/PiInitProcessManager() begins. */
119 PsInitProcessManagment();
120 PsInitThreadManagment();
121 /* Part of reactos/ntoskrnl/ps/psmgr.c/PiInitProcessManager() ends. */
125 /* LdrInitModuleManagement(); */
126 /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInitModuleManagement() begins
127 * here as the rest "Create module object for {NTOSKRNL,HAL}"
128 * is dependent on {NTOSKRNL,HAL} PE image headers not provided by libcaptive.
130 /* Initialize the module list and spinlock */
131 InitializeListHead(&ModuleListHead);
132 KeInitializeSpinLock(&ModuleListLock);
133 /* Part of reactos/ntoskrnl/ldr/loader.c/LdrInitModuleManagement ends. */
136 NtInitializeEventImplementation();
138 /* Part of reactos/ntoskrnl/ke/main.c/ExpInitializeExecutive() ends. */
139 /* Part of reactos/ntoskrnl/ke/main.c/KiSystemStartup() ends. */
141 /* Simulate our PE headers and export the symbols of our complete libraries */
142 captive_kernel_exports();
144 errbool=captive_cdrom_init();
145 g_return_val_if_fail(errbool==TRUE,FALSE);
146 errbool=captive_disk_init();
147 g_return_val_if_fail(errbool==TRUE,FALSE);
149 while (captive_options->load_module) {
150 PMODULE_OBJECT ModuleObject_tmp;
153 /* load the module */
154 err=captive_LdrLoadModule(
155 captive_options->load_module->data,
156 &ModuleObject_tmp); /* ModuleObjectp */
157 g_return_val_if_fail(NT_SUCCESS(err),FALSE);
159 captive_options_module_free(captive_options->load_module->data);
160 /* also frees 'options->load_module->data' */
161 captive_options->load_module=g_list_delete_link(captive_options->load_module,captive_options->load_module);
164 /* Patch 'ntoskrnl.exe' loaded by 'captive_options->load_module' above. */
166 CHAR *KeNumberProcessorsp=captive_Module_GetExportAddress("ntoskrnl.exe","KeNumberProcessors");
168 g_assert(*KeNumberProcessorsp==0);
169 *KeNumberProcessorsp=KeNumberProcessors;
170 g_assert(*KeNumberProcessorsp==1);
172 /* Apply AFTER any symbols sanity checks above! */
173 if (captive_options->debug_messages)
174 captive_kernel_patches_debug();
176 captive_kernel_patches_nondebug();
178 _local_unwind2_addr=captive_Module_GetExportAddress("ntoskrnl.exe","_local_unwind2");
180 /* Initialize 'FsRtlLegalAnsiCharacterArray'.
181 * It requires 'ntoskrnl.exe' loaded by 'captive_options->load_module' above;
182 * captive_kernel_patches_debug()/captive_kernel_patches_nondebug() should not be needed.
184 captive_FsRtlLegalAnsiCharacterArray_init();
186 /* set TopLevelIrp() - FIXME: where is it set by native reactos? */
187 PsGetCurrentThread()->TopLevelIrp=&TopLevelIrp; /* otherwise Io{Get,Set}TopLevelIrp() would SIGSEGV */
189 /* Begin possible handling of foreign W32 binary code here */
190 /* If you want to disable SIGSEGV handler if not needed:
191 * if (ModuleObject->Flags & MODULE_FLAG_PE)
193 captive_signal_init();
195 /* You must have already captive_signal_init() passed here as the module may
196 * call some functions from W32 ntoskrnl.exe.
198 captive_DriverObject_ReinitRoutine=NULL;
199 err=captive_LdrpLoadAndCallImage(
200 &ModuleObject, /* ModuleObjectp */
201 &captive_options->filesystem, /* options_module */
202 &captive_DriverObject, /* DriverEntry_DriverObject */
203 captive_utf8_to_UnicodeString_alloca("\\captive\\filesystem")); /* DriverEntry_RegistryPath */
204 g_return_val_if_fail(NT_SUCCESS(err),FALSE);
205 if (captive_DriverObject_ReinitRoutine) {
206 captive_stdcall_call_12((CaptiveStdCallFunc12)captive_DriverObject_ReinitRoutine,
207 &captive_DriverObject, /* DriverObject */
208 captive_DriverObject_ReinitRoutine_Context, /* Context */
209 (gpointer)1); /* Count: # of calls of ReinitRoutine incl. the current one */
216 static void captive_log_init_g_log_func_discard
217 (const gchar *log_domain,GLogLevelFlags log_level,const gchar *message,gpointer user_data)
219 g_return_if_fail(message!=NULL);
224 static void captive_log_init_g_log_func
225 (const gchar *log_domain,GLogLevelFlags log_level,const gchar *message,gpointer user_data /* unused */)
229 g_return_if_fail(message!=NULL);
231 /* unused: LOG_EMERG */
232 /* unused: LOG_ALERT */
233 /**/ if (log_level&G_LOG_LEVEL_ERROR)
235 else if (log_level&G_LOG_LEVEL_CRITICAL)
237 else if (log_level&G_LOG_LEVEL_WARNING)
238 priority=LOG_WARNING;
239 else if (log_level&G_LOG_LEVEL_MESSAGE)
241 else if (log_level&G_LOG_LEVEL_INFO)
243 else if (log_level&G_LOG_LEVEL_DEBUG)
246 priority=LOG_WARNING;
248 syslog(priority,"%s%s%s",
249 (!(log_level&G_LOG_FLAG_RECURSION) ? "" : "RECURSION: "),
250 (!(log_level&G_LOG_FLAG_FATAL ) ? "" : "FATAL: "),
254 void captive_log_init(const struct captive_options *captive_options)
256 g_return_if_fail(captive_options!=NULL);
258 /* FIXME: Fix sharing of different 'debug_messages' for various sandboxes. */
259 captive_debug_messages_disabled=!captive_options->debug_messages;
261 /* FIXME: Fix sharing of different 'debug_messages' for various sandboxes. */
262 if (!captive_options->debug_messages) {
263 /* FIXME: Save handler_id and destroy it in captive_vfs_close(). */
265 G_LOG_DOMAIN, /* log_domain; "Captive" */
267 | G_LOG_FLAG_RECURSION
269 /* The same mask is in:
270 * libcaptive/sandbox/server-GLogFunc.c
271 * libcaptive/client/init.c
273 | G_LOG_LEVEL_MESSAGE
276 captive_log_init_g_log_func_discard, /* log_func */
277 NULL); /* user_data */
279 /* We are not the sandboxed slave;
280 * 'syslog_facility' would be '-1' in slave anyway as it is not transferred through CORBA.
282 if (!captive_options->sandbox || (captive_options->sandbox_server_argv || captive_options->sandbox_server_ior)) {
283 if (captive_options->syslog_facility!=-1) {
285 /* FIXME: Prefix 'ident' by device/mountpoint. */
286 G_LOG_DOMAIN, /* ident; "Captive"; FIXME: lowercase it for syslog(3)? */
287 LOG_CONS|LOG_PID, /* options */
288 captive_options->syslog_facility); /* facility */
289 /* FIXME: Save handler_id and destroy it in captive_vfs_close(). */
291 G_LOG_DOMAIN, /* log_domain; "Captive" */
293 | 0 /* !G_LOG_FLAG_RECURSION */
295 | (G_LOG_LEVEL_MASK & ~(captive_options->debug_messages ? 0 : 0
296 /* The same mask is in:
297 * libcaptive/sandbox/server-GLogFunc.c
298 * libcaptive/client/init.c
300 | G_LOG_LEVEL_MESSAGE
302 | G_LOG_LEVEL_DEBUG)),
303 (GLogFunc)captive_log_init_g_log_func, /* log_func */
304 NULL); /* user_data */
312 * Expects #captive_options: Parsed by captive_options_parse().
313 * %NULL value is forbidden. Field #image_iochannel %NULL value is forbidden.
315 * Initializes %libcaptive and loads the specified filesystem.
317 * Returns: %TRUE if successfuly initialized.
319 gboolean captive_init(void)
323 /* We are in sandbox child and we have the right to fail. */
324 g_log_set_always_fatal(~(0
330 g_return_val_if_fail(active==FALSE,FALSE);
332 g_return_val_if_fail(captive_options!=NULL,FALSE);
333 g_return_val_if_fail(captive_options->image_iochannel!=NULL,FALSE);
335 /* Initialize GObject subsystem of GLib. */
338 captive_log_init(captive_options);
340 if (captive_options->rwmode==CAPTIVE_OPTION_RWMODE_RW && !captive_options->sandbox)
341 g_error(_("Rejecting --rw --no-sandbox operation as too dangerous - use --blind or --sandbox"));
343 captive_image_iochannel=captive_options->image_iochannel;
344 g_io_channel_ref(captive_image_iochannel);
346 captive_image_iochannel=captive_storage_relastblock(captive_image_iochannel);
348 if (captive_options->rwmode==CAPTIVE_OPTION_RWMODE_BLIND) {
349 GIOChannel *captive_image_iochannel_orig;
351 captive_image_iochannel_orig=captive_image_iochannel;
352 captive_image_iochannel=(GIOChannel *)captive_giochannel_blind_new(captive_image_iochannel,
353 TRUE); /* writeable */
354 g_io_channel_unref(captive_image_iochannel_orig); /* reffed by captive_giochannel_blind_new() */
357 /* Do not initialize 'captive_image_size' by captive_giochannel_size() here
358 * as we yet need to do g_io_channel_set_encoding().
361 errbool=captive_w32_init();
362 g_return_val_if_fail(errbool==TRUE,FALSE);
369 static void dismount_volume(void)
371 IO_STATUS_BLOCK IoStatusBlock;
372 PEXTENDED_IO_STACK_LOCATION StackPtr;
375 DEVICE_OBJECT *DeviceObject=captive_DriverObject.DeviceObject;
376 OBJECT_ATTRIBUTES dir_ObjectAttributes;
378 FILE_OBJECT *FileObject;
379 GnomeVFSResult errvfsresult;
381 IO_STATUS_BLOCK dir_IoStatusBlock;
383 * TraceFS reported only IRP_MJ_FLUSH_BUFFERS
384 * and IRP_MJ_SHUTDOWN.
385 * Apparently it is not enough, FSCTL_DISMOUNT_VOLUME is needed,
386 * otherwise NT-5.1 autochkdsks the disk and W2000 may give BSOD during boot.
389 /* First item value assumed to be 0. */
390 STEP_IRP_MJ_FLUSH_BUFFERS_PRE,
392 /* DISABLED: STATUS_ACCESS_DENIED; FIXME: Why?
393 * The official way of device modification is: LOCK,DISMOUNT
394 * but LOCK fails for Captive if any file was written (and closed).
396 STEP_FSCTL_LOCK_VOLUME,
398 STEP_FSCTL_DISMOUNT_VOLUME,
399 STEP_IRP_MJ_FLUSH_BUFFERS_POST,
404 errvfsresult=captive_ObjectAttributes_init("/!Captive!del",&dir_ObjectAttributes);
405 g_return_if_fail(errvfsresult==GNOME_VFS_OK);
407 /* wanted: * IoCreateFile()->ObCreateObject(,,,IoFileObjectType)->
408 * ->(IoFileObjectType->Create==IopCreateFile)()->IoMountVolume()
410 CAPTIVE_MEMZERO(&dir_IoStatusBlock); /* FIXME: Try to pre-clear it - uninitialized otherwise? */
411 dir_IoStatusBlock.Information=FILE_OPENED; /* FIXME: Try to pre-set it - uninitialized otherwise? */
413 &dir_Handle, /* FileHandle */
414 GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE|0x80, /* DesiredAccess; 0xC0100080=GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE|0x80 */
415 &dir_ObjectAttributes, /* ObjectAttributes */
416 &dir_IoStatusBlock, /* IoStatusBlock */
417 NULL, /* AllocationSize; ignored for open */
418 FILE_ATTRIBUTE_NORMAL, /* FileAttributes; ignored for open */
419 (FILE_SHARE_READ | FILE_SHARE_WRITE), /* ShareAccess; 0 means exclusive */
420 FILE_OPEN, /* CreateDisposition */
421 /* FILE_SYNCHRONOUS_IO_{,NON}ALERT: We need to allow W32 filesystem
422 * any waits to not to let it return STATUS_CANT_WAIT us.
423 * Alertability should have only effect on asynchronous events
424 * from KeWaitForSingleObject() by setting/clearing its parameter 'Alertable'.
426 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE, /* CreateOptions; FILE_DIRECTORY_FILE is forbidden */
429 CreateFileTypeNone, /* CreateFileType */
430 NULL, /* ExtraCreateParameters */
432 g_free(dir_ObjectAttributes.ObjectName); /* left from captive_gnomevfs_uri_parent_init() */
433 g_return_if_fail(NT_SUCCESS(err));
434 g_return_if_fail(NT_SUCCESS(err)==NT_SUCCESS(dir_IoStatusBlock.Status));
435 g_return_if_fail(dir_IoStatusBlock.Information==FILE_OPENED);
437 Status=ObReferenceObjectByHandle(dir_Handle,FILE_LIST_DIRECTORY,IoFileObjectType,UserMode,(PVOID *)&FileObject,NULL);
438 g_assert(NT_SUCCESS(Status));
440 g_assert(FileObject->FileName.Length==0);
441 /* 'FileObject->FileName.MaximumLength' is not reset by IoCreateFile(). */
442 g_assert(FileObject->FileName.Buffer==NULL);
443 FileObject->FileName.MaximumLength=2;
444 FileObject->FileName.Buffer=&wzero;
446 for (stepi=0;stepi<STEP_MAX;stepi++) {
447 Irp=IoAllocateIrp(DeviceObject->StackSize,TRUE);
448 g_return_if_fail(Irp!=NULL);
450 Irp->UserIosb=&IoStatusBlock;
451 Irp->UserEvent=&FileObject->Event;
452 Irp->Tail.Overlay.Thread=PsGetCurrentThread();
454 StackPtr=(EXTENDED_IO_STACK_LOCATION *)IoGetNextIrpStackLocation(Irp);
456 case STEP_IRP_MJ_FLUSH_BUFFERS_PRE:
457 StackPtr->MajorFunction=IRP_MJ_FLUSH_BUFFERS;
459 #if 0 /* Disabled, see 'STEP_FSCTL_LOCK_VOLUME'. */
460 case STEP_FSCTL_LOCK_VOLUME:
461 StackPtr->MajorFunction=IRP_MJ_FILE_SYSTEM_CONTROL;
462 StackPtr->MinorFunction=IRP_MN_USER_FS_REQUEST;
463 StackPtr->Parameters.FileSystemControl.OutputBufferLength=0;
464 StackPtr->Parameters.FileSystemControl.InputBufferLength=0;
465 StackPtr->Parameters.FileSystemControl.FsControlCode=FSCTL_LOCK_VOLUME;
466 StackPtr->Parameters.FileSystemControl.Type3InputBuffer=NULL;
469 case STEP_FSCTL_DISMOUNT_VOLUME:
470 StackPtr->MajorFunction=IRP_MJ_FILE_SYSTEM_CONTROL;
471 StackPtr->MinorFunction=IRP_MN_USER_FS_REQUEST;
472 StackPtr->Parameters.FileSystemControl.OutputBufferLength=0;
473 StackPtr->Parameters.FileSystemControl.InputBufferLength=0;
474 StackPtr->Parameters.FileSystemControl.FsControlCode=FSCTL_DISMOUNT_VOLUME;
475 StackPtr->Parameters.FileSystemControl.Type3InputBuffer=NULL;
477 case STEP_IRP_MJ_FLUSH_BUFFERS_POST:
478 StackPtr->MajorFunction=IRP_MJ_FLUSH_BUFFERS;
480 default: g_assert_not_reached();
484 StackPtr->DeviceObject=DeviceObject; /* FIXME: FileObject->Vpb->DeviceObject ? */
485 StackPtr->FileObject=FileObject;
486 StackPtr->CompletionRoutine=NULL;
488 /* IoCallDriver() will do one ObDereferenceObject(FileObject)
489 * in its IoSecondStageCompletion().
490 * Do not leave to dereference it itself as we need its 'FileObject->Event'.
492 ObReferenceObject(FileObject);
494 Status=IoCallDriver(DeviceObject,Irp);
495 if (Status==STATUS_PENDING) {
496 KeWaitForSingleObject(&FileObject->Event,Executive,KernelMode,FALSE,NULL);
497 Status=IoStatusBlock.Status;
499 g_assert(NT_SUCCESS(Status)
500 || (Status==STATUS_MEDIA_WRITE_PROTECTED && captive_options->rwmode==CAPTIVE_OPTION_RWMODE_RO));
503 ObDereferenceObject(FileObject);
507 BOOLEAN captive_cc_FileObject_delete(FILE_OBJECT *FileObject);
508 void captive_cc_flush(void);
513 * Closes down %libcaptive. It should flush all pending buffers and successfuly
514 * close the filesystem. Variable #captive_options->image_iochannel will not be set to %NULL,
515 * you should close such channel yourself.
517 * Returns: %TRUE if successfuly shutdown.
519 gboolean captive_shutdown(void)
521 GIOStatus erriostatus;
523 g_return_val_if_fail(active==TRUE,FALSE);
524 g_return_val_if_fail(captive_image_iochannel!=NULL,FALSE);
525 g_return_val_if_fail(captive_options->image_iochannel!=NULL,FALSE);
527 /* Invoke all pending idle functions just to not to forget for anything... */
528 while (g_main_context_iteration(
529 NULL, /* context; NULL means default one */
530 FALSE)) /* may_block */
531 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: g_main_context_iteration() proceeded",G_STRLOC);
533 /* Do not: captive_cc_flush(); * based on captive_leave(), not g_main idle *
534 * replaced by IRP_MJ_FLUSH_BUFFERS.
537 /* Probably not needed: captive_shared_cache_map_flush_all();
542 /* Probably not needed: captive_shared_cache_map_flush_all();
545 /* Invoke all pending idle functions just to not to forget for anything... */
546 while (g_main_context_iteration(
547 NULL, /* context; NULL means default one */
548 FALSE)) /* may_block */
549 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: g_main_context_iteration() proceeded",G_STRLOC);
552 captive_PoQueueShutdownWorkItem_hooklist_invoke();
555 /* Do not: captive_cc_flush();
556 * as the dirty blocks should have been already commited by dismount_volume(),
557 * any further commits would get us just STATUS_VOLUME_DISMOUNTED.
560 /* Do not: captive_cc_unmounting=TRUE;
561 * Without dismount_volume() it was:
562 * During IoShutdownRegisteredFileSystems() - IRP_MJ_SHUTDOWN to be specific
563 * some buffers will be written but after the IofCallDriver() it will be
564 * no longer possible to flush such buffers to their DeviceVolumeFile.
565 * Therefore we must flush such buffers on the fly although such behaviour
566 * would crash us in regular case as filesystems access BCBs even after their
568 * Currently the dirty blocks should have been already commited by dismount_volume(),
571 /* FIXME: ntoskrnl/ex/power.c/NtShutdownSystem() does
572 * IoShutdownRegistered{Devices,FileSystems} order; is it correct?
574 IoShutdownRegisteredFileSystems();
576 /* Do not: captive_cc_FileObject_delete(NULL);
577 * as the dirty blocks should have been already commited by dismount_volume(),
578 * any further commits would get us just STATUS_VOLUME_DISMOUNTED.
581 IoShutdownRegisteredDevices();
583 /* Just a sanity if 'captive_image_iochannel' is already reffed a bit more... */
584 erriostatus=g_io_channel_flush(
585 captive_image_iochannel, /* channel */
587 g_assert(erriostatus==G_IO_STATUS_NORMAL);
589 g_io_channel_unref(captive_image_iochannel);
590 captive_image_iochannel=NULL;