newlib/winsup/cygwin/dll_init.cc

432 lines
11 KiB
C++
Raw Normal View History

2000-02-17 20:38:33 +01:00
/* dll_init.cc
Copyright 1998, 1999, 2000, 2001, 2002, 2003, 2004 Red Hat, Inc.
2000-02-17 20:38:33 +01:00
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#include "winsup.h"
#include <stdlib.h>
#include "cygerrno.h"
#include "perprocess.h"
#include "dll_init.h"
#include "environ.h"
#include "security.h"
Add "path.h" include throughout, where needed. Use new path_conv methods and operators to simplify testing for directory and attributes, throughout. * path.h (path_conv::exists): New method. (path_conv::has_attribute): Ditto. (path_conv::isdir): Ditto. (path_conv::DWORD &): New operator. (path_conv::int &): Ditto. * dir.cc (rmdir): Eliminate a goto. * dtable.cc (dtable::build_fhandler): Accept opt and suffix info for path_conv.check. Return fh == NULL on path_conv error. Pass unit to set_name as appropriate. (dtable::reset_unix_path_name): New method. * dtable.h (dtable): Declare new method. Reflect arg changes to build_fhandler. * fhandler.cc (fhandler_disk_dummy_name): Eliminate. (fhandler_base::set_name): Expect paths to be NULL. Build unix_path_name from win32_path_name when it is a device. (fhandler_base::reset_unix_path_name): New method. (fhandler_base::raw_read): Report EISDIR when ERROR_INVALID_FUNCTION or ERROR_INVALID_PARAMETER and reading a directory. (fhandler_disk_file::fstat): Don't call stat_dev since we should now never be calling fhandler_disk_file methods with devices. (fhandler_base::fhandler_base): Clear {unix,win32}_path_name. (fhandler_base::~fhandler_base): Always free {unix,win32}_path_name. (fhandler_disk_file::fhandler_disk_file): Remove set_no_free_names kludge. (fhandler_disk_file::open): Ditto. * fhandler.h (fhandler_base::no_free_names): Eliminate. (fhandler_base::set_no_free_names): Ditto. * fhandler_tty.cc (fhandler_tty_slave::fhandler_tty_slave): Don't set unix_path_name here. * path.cc (fchdir): Lock fd table throughout. Use new dtable::reset_unix_path_name method to reset path. * syscalls.cc (stat_worker): Reorganize to always call fstat method. Pass path_conv method to fhandler_*::open. (chroot): Elminate a goto.
2001-10-01 06:10:07 +02:00
#include "path.h"
* devices.cc: New file. * devices.gperf: New file. * devices.shilka: New file. * cygwin-gperf: New file. * cygwin-shilka: New file. * fhandler_fifo.cc: New file. * fhandler_nodevice.cc : New file. Reorganize headers so that path.h precedes fhandler.h throughout. Remove device argument and unit arguments from fhandler constructors throughout. Remove pc arguments to fhandler functions and use internal pc element instead, throughout. Use dev element in pc throughout. Use major/minor elements rather than units and device numbers previously in fhandler class. Use correct methods for fhandler file names rather than directly accessing file name variables, throughout. * Makefile.in (DLL_OFILES): Add devices.o, fhandler_fifo.o * dcrt0.cc (dll_crt0_1): Call device::init. * devices.h: Renumber devices based on more Linux-like major/minor numbers. Add more devices. Declare standard device storage. (device): Declare struct. * dir.cc (opendir): Use new 'build_fh_name' to construct a fhandler_* type. * dtable.cc (dtable::get_debugger_info): Ditto. (cygwin_attach_handle_to_fd): Ditto. (dtable::release): Remove special FH_SOCKET case in favor of generic "need_fixup_before" test. (dtable::init_std_file_from_handle): Use either build_fh_dev or build_fh_name to build standard fhandler. (dtable::build_fh_name): Renamed from dtable::build_fhandler_from_name. Move out of dtable class. Don't accept a path_conv argument. Just build it here and pass it to: (build_fh_pc): Renamed from dtable::build_fhandler. Move out of dtable class. Use intrinsic device type in path_conv to create new fhandler. (build_fh_dev): Renamed from dtable::build_fhandler. Move out of dtable class. Simplify arguments to just take new 'device' type and a name. Just return pointer to fhandler rather than trying to insert into dtable. (dtable::dup_worker): Accommodate above build_fh name changes. (dtable::find_fifo): New (currently broken) function. (handle_to_fn): Use strechr for efficiency. * dtable.h: Reflect above build_fh name changes and argument differences. (fhandler_base *&operator []): Return self rather than copy of self. * fhandler.cc (fhandler_base::operator =): Use pc element to set normalized path. (fhandler_base::set_name): Ditto. (fhandler_base::raw_read): Use method to access name. (fhandler_base::write): Correctly use get_output_handle rather than get_handle. (handler_base::device_access_denied): New function. (fhandler_base::open): Eliminate pc argument and use pc element of fhandler_base throughout. (fhandler_base::fstat): Detect if device is based in filesystem and use fstat_fs to calculate stat, if so. (fhandler_base::fhandler_base): Eliminate handling of file names and, instead, just free appropriate component from pc. (fhandler_base::opendir): Remove path_conv parameter. * fhandler.h: Remove all device flags. (fhandler_base::pc): New element. (fhandler_base::set_name): Change argument to path_conv. (fhandler_base::error): New function. (fhandler_base::exists): New function. (fhandler_base::pc_binmode): New function. (fhandler_base::dev): New function. (fhandler_base::open_fs): New function. (fhandler_base::fstat_fs): New function. (fhandler_base::fstat_by_name): New function. (fhandler_base::fstat_by_handle): New function. (fhandler_base::isfifo): New function. (fhandler_base::is_slow): New function. (fhandler_base::is_auto_device): New function. (fhandler_base::is_fs_special): New function. (fhandler_base::device_access_denied): New function. (fhandler_base::operator DWORD&): New operator. (fhandler_base::get_name): Return normalized path from pc. (fhandler_base::get_win32_name): Return windows path from pc. (fhandler_base::isdevice): Renamed from is_device. (fhandler_base::get_native_name): Return device format. (fhandler_fifo): New class. (fhandler_nodevice): New class. (select_stuff::device_specific): Remove array. (select_stuff::device_specific_pipe): New class element. (select_stuff::device_specific_socket): New class element. (select_stuff::device_specific_serial): New class element. (select_stuff::select_stuff): Initialize new elements. * fhandler_disk_file.cc (fhandler_base::fstat_by_handle): Move to base class from fhandler_disk_file. (fhandler_base::fstat_by_name): Ditto. (fhandler_base::fstat_by_name): Ditto. (fhandler_disk_file::open): Move most functionality into fhandler_base::open_fs. (fhandler_base::open_fs): New function. (fhandler_disk_file::close): Move most functionality into fhandler_base::close_fs. (fhandler_base::close_fs): New function. * fhandler_mem.cc (fhandler_dev_mem::open): Use device name in debugging output. * fhandler_socket.cc (fhandler_socket::set_connect_secret): Copy standard urandom device into appropriate place. (fhandler_socket::accept): Reflect change in fdsock return value. * fhandler_tty.cc: See "throughouts" above. * net.cc: Accommodate fdsock change throughout. (fdsock): Return success or failure, accept fd argument and device argument. * path.cc (symlink_info::major): New element. (symlink_info::minor): New element. (symlink_info::parse_device): Declare new function. (fs_info::update): Accommodate changes in path_conv class. (path_conv::fillin): Ditto. (path_conv::return_and_clear_normalized_path): Eliminate. (path_conv::set_normalized_path): New function. (path_conv::path_conv): Set info in dev element. Use path_conv methods Check for FH_FS rather than FH_BAD to indicate when to fill in filesystem stuff. where appropriate rather than direct access. Use set_normalized_path to set normalized path. (windows_device_names): Eliminate. (get_dev): Ditto. (get_raw_device_number): Ditto. (get_device_number): Ditto. (win32_device_name): Call new device name parser to do most of the heavy lifting. (mount_info::conv_to_win32_path): Fill in dev field as appropriate. (symlink_worker): Handle new device files. (symlink_info::check): Ditto. (symlink_info::parse_device): Define new function. * path.h (executable_states): Move here from fhandler.h. (fs_info): Rename variables to *_storage and create methods for accessing same. (path_conv): Add dev element, remove devn and unit and adjust inline methods to accommodate. (set_normalized_path): Declare new function. * pinfo.cc (_pinfo::commune_recv): Add broken support for handling fifos. (_pinfo::commune_send): Ditto. * pipe.cc (fhandler_pipe::close): check for existence of handle before closing it. (handler_pipe::create): Rename from make_pipe. Change arguments to accept fhandler_pipe array. Accommodate fifos. (pipe): Rework to deal with fhandler_pipe::create changes. (_pipe): Ditto. * select.cc: Use individual device_specific types throughout rather than indexing with obsolete device number. (set_bits): Use is_socket call rather than checking device number. * shared_info.h (CURR_MOUNT_MAGIC): Update. (conv_to_win32_path): Reflect addition of device argument. * syscalls.cc (mknod_worker): New function. (open): Use build_fh_name to build fhandler. (chown_worker): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. (chmod_device): New function. (chmod): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. Use chmod_device to set mode of in-filesystem devices. (stat_worker): Eliminate path_conv argument. Call build_fh_name to construct fhandler. Use fh->error() rather than pc->error to detect errors in fhandler construction. (access_worker): New function pulled from access. Accommodate in-filesystem devices. (access): Use access_worker. (fpathconf): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. (mknod_worker): New function. (mknod32): New function. (chroot): Free normalized path -- assuming it was actually cmalloced. * tty.cc (create_tty_master): Tweak for new device class. (tty::common_init): Ditto. * winsup.h (stat_worker): Remove. (symlink_worker): Declare. * exceptions.cc (set_process_mask): Just call sig_dispatch_pending and don't worry about pending_signals since sig_dispatch_pending should always do the right thing now. (sig_handle): Reorganize SIGCONT handling to more closely conform to SUSv3. * pinfo.h: Move __SIG enum to sigproc.h. (PICOM_FIFO): New enum element. (_pinfo): Remove 'thread2signal' stuff throughout class. (_pinfo::commune_send): Make varargs. (_pinfo::sigtodo): Eliminate. (_pinfo::thread2signal): Ditto. * signal.cc (kill_worker): Eliminate call to setthread2signal. * sigproc.cc (local_sigtodo): Eliminate. (getlocal_sigtodo): Ditto. (sigelem): New class. (pending_signals): New class. (sigqueue): New variable, start of sigqueue linked list. (sigcatch_nonmain): Eliminate. (sigcatch_main): Eliminate. (sigcatch_nosync): Eliminate. (sigcomplete_nonmain): Eliminate. (pending_signals): Eliminate. (sig_clear): Call signal thread to clear pending signals, unless already in signal thread. (sigpending): Call signal thread to get pending signals. (sig_dispatch_pending): Eliminate use of pending_signals and just check sigqueue. (sigproc_terminate): Eliminate all of the obsolete semaphore stuff. Close signal pipe handle. (sig_send): Eliminate all of the obsolete semaphore stuff and use pipe to send signals. (getevent): Eliminate. (pending_signals::add): New function. (pending_signals::del): New function. (pending_signals::next): New function. (wait_sig): Eliminate all of the obsolete semaphore stuff. Use pipe to communicate and maintain a linked list of signals. * sigproc.h: Move __SIG defines here. Add __SIGPENDING. (sig_dispatch_pending): Remove "C" specifier. (sig_handle): Accept a mask argument. * thread.cc: Remove signal handling considerations throughout.
2003-09-25 02:37:18 +02:00
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "pinfo.h"
2000-02-17 20:38:33 +01:00
extern void __stdcall check_sanity_and_sync (per_process *);
dll_list NO_COPY dlls;
2000-02-17 20:38:33 +01:00
static int NO_COPY in_forkee;
static int dll_global_dtors_recorded;
2000-02-17 20:38:33 +01:00
/* Run destructors for all DLLs on exit. */
2000-02-17 20:38:33 +01:00
static void
dll_global_dtors ()
2000-02-17 20:38:33 +01:00
{
for (dll *d = dlls.istart (DLL_ANY); d; d = dlls.inext ())
d->p.run_dtors ();
2000-02-17 20:38:33 +01:00
}
/* Run all constructors associated with a dll */
void
per_module::run_ctors ()
2000-02-17 20:38:33 +01:00
{
void (**pfunc)() = ctors;
2000-02-17 20:38:33 +01:00
/* Run ctors backwards, so skip the first entry and find how many
there are, then run them. */
if (pfunc)
{
int i;
for (i = 1; pfunc[i]; i++);
for (int j = i - 1; j > 0; j--)
2000-02-17 20:38:33 +01:00
(pfunc[j]) ();
}
}
/* Run all destructors associated with a dll */
void
per_module::run_dtors ()
2000-02-17 20:38:33 +01:00
{
void (**pfunc)() = dtors;
2000-02-17 20:38:33 +01:00
for (int i = 1; pfunc[i]; i++)
(pfunc[i]) ();
}
/* Initialize an individual DLL */
int
dll::init ()
2000-02-17 20:38:33 +01:00
{
int ret = 1;
2000-02-17 20:38:33 +01:00
/* Why didn't we just import this variable? */
*(p.envptr) = __cygwin_environ;
2000-02-17 20:38:33 +01:00
/* Don't run constructors or the "main" if we've forked. */
if (!in_forkee)
2000-02-17 20:38:33 +01:00
{
/* global contructors */
p.run_ctors ();
2000-02-17 20:38:33 +01:00
/* entry point of dll (use main of per_process with null args...) */
if (p.main)
ret = (*(p.main)) (0, 0, 0);
2000-02-17 20:38:33 +01:00
}
return ret;
}
/* Look for a dll based on name */
dll *
dll_list::operator[] (const char *name)
2000-02-17 20:38:33 +01:00
{
dll *d = &start;
while ((d = d->next) != NULL)
if (strcasematch (name, d->name))
return d;
2000-02-17 20:38:33 +01:00
return NULL;
2000-02-17 20:38:33 +01:00
}
#define RETRIES 1000
2000-07-16 06:10:33 +02:00
/* Allocate space for a dll struct contiguous with the just-loaded dll. */
dll *
dll_list::alloc (HINSTANCE h, per_process *p, dll_type type)
2000-02-17 20:38:33 +01:00
{
char name[CYG_MAX_PATH + 1];
DWORD namelen = GetModuleFileName (h, name, sizeof (name));
2000-02-17 20:38:33 +01:00
/* Already loaded? */
dll *d = dlls[name];
if (d)
2000-02-17 20:38:33 +01:00
{
d->count++; /* Yes. Bump the usage count. */
return d; /* Return previously allocated pointer. */
2000-02-17 20:38:33 +01:00
}
SYSTEM_INFO s1;
GetSystemInfo (&s1);
int i;
void *s = p->bss_end;
DWORD n;
MEMORY_BASIC_INFORMATION m;
/* Search for space after the DLL */
for (i = 0; i <= RETRIES; i++, s = (char *) m.BaseAddress + m.RegionSize)
2000-02-17 20:38:33 +01:00
{
if (!VirtualQuery (s, &m, sizeof (m)))
return NULL; /* Can't do it. */
if (m.State == MEM_FREE)
{
/* Couldn't find any. Uh oh. FIXME: Issue an error? */
if (i == RETRIES)
return NULL; /* Oh well. Couldn't locate free space. */
/* Ensure that this is rounded to the nearest page boundary.
FIXME: Should this be ensured by VirtualQuery? */
n = (DWORD) m.BaseAddress;
DWORD r = n % s1.dwAllocationGranularity;
if (r)
n = ((n - r) + s1.dwAllocationGranularity);
/* First reserve the area of memory, then commit it. */
if (VirtualAlloc ((void *) n, sizeof (dll), MEM_RESERVE, PAGE_READWRITE))
d = (dll *) VirtualAlloc ((void *) n, sizeof (dll), MEM_COMMIT,
PAGE_READWRITE);
if (d)
break;
}
2000-02-17 20:38:33 +01:00
}
2000-07-16 06:10:33 +02:00
/* Did we succeed? */
if (d == NULL)
2000-07-16 06:10:33 +02:00
{ /* Nope. */
#ifdef DEBUGGING
system_printf ("VirtualAlloc failed, %E");
#endif
__seterrno ();
return NULL;
}
/* Now we've allocated a block of information. Fill it in with the supplied
info about this DLL. */
d->count = 1;
d->namelen = namelen;
strcpy (d->name, name);
d->handle = h;
d->p = p;
d->type = type;
if (end == NULL)
end = &start; /* Point to "end" of dll chain. */
end->next = d; /* Standard linked list stuff. */
d->next = NULL;
d->prev = end;
end = d;
tot++;
if (type == DLL_LOAD)
loaded_dlls++;
return d;
2000-02-17 20:38:33 +01:00
}
/* Detach a DLL from the chain. */
2000-02-17 20:38:33 +01:00
void
dll_list::detach (void *retaddr)
2000-02-17 20:38:33 +01:00
{
if (!myself || exit_state)
return;
MEMORY_BASIC_INFORMATION m;
if (!VirtualQuery (retaddr, &m, sizeof m))
return;
HMODULE h = (HMODULE) m.AllocationBase;
dll *d = &start;
while ((d = d->next))
if (d->handle != h)
continue;
else if (d->count <= 0)
* cygtls.h (_threadinfo::call): Remove regparm declaration to work around compiler bug. * autoload.cc (TryEnterCriticalSection): Remove. * dcrt0.cc (dll_crt0_0): Delete inappropriate setting of _my_tls.stackptr to NULL since it has really bad consequences. Make 'si' an automatic variable. * cygtls.cc (_threadinfo::init_thread): Correct thinko which caused thread list to be allocated every time. * cygtls.h (CYGTLS_PADSIZE): Define as const int. * sync.h: Make multiple inclusion safe. (muto::next): Eliminate. (muto::exiting_thread): New variable. (muto::set_exiting_thread): New function. (new_muto): Change to use different section for mutos since c++ give inexplicable warning in some cases otherwise. (new_muto1): Ditto. * dcrt0.cc (do_exit): Call muto::set_exiting_thread here. * sync.cc (muto_start): Eliminate. (muto::acquire): Always give exiting thread a lock. Never give thread a lock if exiting. (muto::release): Ditto for releasing. * dtable.cc (dtable::init_lock): Unline function and define here. * dtable.h (lock_cs): Define as a muto since critical sections seem to work oddly on Windows Me. (lock): Accommodate switch to muto. (unlock): Ditto. * exceptions.cc (setup_handler): Don't worry about acquiring mutos since that hasn't mattered for a long time. (signal_exit): Ditto: muto stuff will be handled automatically on exit now. * Makefile.in (DLL_IMPORTS): Link advapi32 to ensure proper DLL initialization. * autoload.cc (RegCloseKey): Arbitrarily choose this function as a "seed" to pull the advapi32 link library in. So, comment out the autoloading. * cygtls.cc (_threadinfo::init_thread): Just clear CYGTLS_PADSIZE. (_threadinfo::remove): Add debugging. (_threadinfo::find_tls): Ditto. * cygtls.h (_threadinfo::padding): Make zero length (for now?). * dcrt0.cc (dll_crt0_0): Move more initialization here from dll_crt0_1. (dll_crt0_1): See above. * dtable.h (dtable::lock): Remove commented out critical section locking. * dtable.h (dtable::init_lock): Remove commented out critical section locking. * dtable.h (dtable::unlock): Remove commented out critical section locking. * exceptions.cc (interruptible): bool'ize. * init.cc (threadfunc_fe): Revert to storing threadfunc at stack bottom. (munge_threadfunc): Ditto. Avoid adding overhead to calibration_thread. (prime_threads): Don't initialize tls stuff. (dll_entry): Make minor change to initialization order. * tlsoffsets.h: Regenerate. * sigproc.cc (wait_sig): Add sanity check for end of process thread exit. * select.h: Make minor formatting change. * Makefile.in: Add still more -fomit-frame-pointer functions. * dtable.h (dtable::lock): New function. (dtable::unlock): New function. (dtable::init_lock): New function. * cygheap.h (HEAP_TLS): Declare new enum value. (init_cygheap::threadlist): Declare new array. (init_cygheap::sthreads): Declare new variable. (cygheap_fdmanip::~cygheap_fdmanip): Use new dtable lock/unlock functions. (cygheap_fdnew::cygheap_fdnew): Ditto. (cygheap_fdget::cygheap_fdget): Ditto. * dtable.cc (dtable_init): Initialize fdtab critical section. (dtable::fixup_after_fork): Ditto. (dtable::fixup_after_exec): Ditto. (dtable::dup2): Use lock/unlock calls to protect access to fdtab. (dtable::find_fifo): Ditto. (dtable::fixup_before_fork): Ditto. (dtable::fixup_before_exec): Ditto. (dtable::set_file_pointers_for_exec): Ditto. (dtable::vfork_child_dup): Ditto. (dtable::vfork_parent_restore): Ditto. * syscalls.cc (close_all_files): Ditto. * sync.h (muto::acquired): Declare new function. (new_muto1): Declare new macro used to specify name of muto storage. * sync.cc (muto::acquired): Define new function. * cygthread.cc (cygthread::stub): Remove signal chain removal call since it is handled during initialization now. * cygthread.cc (cygthread::simplestub): Remove signal chain removal call since it is handled during initialization now. * cygtls.cc (sentry): New class used for locking. Use throughout. (_threadinfo::reset_exception): Don't pop stack. (_threadinfo::find_tls): Move from exceptions.cc. (_threadinfo::init_thread): Initialize array of threads rather than linked list. Take second argument indicating thread function for this thread. (_threadinfo::remove): Search thread array rather than linked list. Use sentry to lock. Only unlock if we got the lock. (_threadinfo::find_tls): Ditto for first two. (handle_threadlist_exception): Handle exceptions when manipulating the thread list in case of premature thread termination. (_threadinfo::init_threadlist_exceptions): Ditto. * cygtls.h (TLS_STACK_SIZE): Decrease size. (_threadinfo::padding): Add element to avoid overwriting lower part of stack. (_threadinfo::remove): Add a "wait" argument to control how long we wait for a lock before removing. * exceptions.cc (init_exception_handler): Make global. Take argument to control exception handler being set. (ctrl_c_handler): Wait forever when removing self from signal chain. (_threadinfo::find_tls): Move to cygtls.cc. (sig_handle): Reorganize detection for thread-specific signals. * heap.cc (heap_init): Rework slightly. Make fatal error more verbose. Remove malloc initialization since it can't happen during dll attach. * init.cc (search_for): Move address to search for on stack here. (threadfunc_ix): Ditto for stack offset. Make shared so that stack walk potentially only has to be done once when cygwin processes are running. (threadfunc_fe): Use standard tls to store thread function (may change back later). (calibration_thread): New function. Potentially called to find threadfunc_ix. (munge_threadfunc): Search for "search_for" value on stack. Output warning when thread func not found on stack. Use standard tls to store thread function. (prime_threads): New function. Called to prime thread front end. (dll_entry): Call dll_crt0_0 here when DLL_PROCESS_ATTACH. Call prime_threads here. Try to remove thread from signal list here. * sigproc.cc (wait_sig): Initialize threadlist exception stuff here. * thread.cc (pthread::exit): Pass argument to signal list remove function. * thread.h: Remove obsolete *ResourceLock defines. * tlsoffsets.h: Regenerate. * winsup.h (spf): Define temporary debug macro to be deleted later. * dcrt0.cc (dll_crt0_0): New function, called during DLL initialization. Mainly consists of code pulled from dll_crt0_1. (dll_crt0_1): See above. (_dll_crt0): Wait for initial calibration thread to complete, if appropriate. Move some stuff to dll_crt0_0. (initialize_main_tls): Accommodate argument change to _thread_info::init_thread. * fork.cc (fork_child): Ditto. (sync_with_child): Fix debug message. * external.cc (cygwin_internal): Remove special considerations for uninitialized dll since initialization happens during dll attach now. * dlfcn.cc (dlopen): Remove obsolete *ResourceLock calls. (dlclose): Ditto. * cygheap.h (init_cygheap::close_ctty): Declare new function. * cygheap.cc (init_cygheap::close_ctty): Define new function. * syscalls.cc (close_all_files): Use close_ctty. (setsid): Ditto. * cygthread.cc (cygthread::stub): Remove exception initialization. * cygthread.cc (cygthread::stub): Remove exception initialization. (cygthread::simplestub): Ditto. * thread.cc (pthread::thread_init_wrapper): Ditto. * cygtls.cc (_last_thread): Make static. (_threadinfo::call2): Initialize exception handler here. (_threadinfo::find_tls): Move here. * exceptions.cc (_threadinfo::find_tls): Move. * dcrt0.cc (__api_fatal): Add prefix info to message here rather than including it in every call to function. * winsup.h (api_fatal): Accommodate above change. * debug.cc (add_handle): Don't do anything if cygheap not around. (mark_closed): Ditto. * dll_init.cc (dll_list::detach): Fix debug output. * fork.cc (sync_with_child): Ditto. (vfork): Improve debug output. * heap.cc (heap_init): Ditto. * exceptions.cc (try_to_debug): Clarify message when debugger attaches.
2004-01-14 16:45:37 +01:00
system_printf ("WARNING: trying to detach an already detached dll ...");
else if (--d->count == 0)
{
d->p.run_dtors ();
d->prev->next = d->next;
if (d->next)
d->next->prev = d->prev;
if (d->type == DLL_LOAD)
loaded_dlls--;
if (end == d)
end = d->prev;
VirtualFree (d, 0, MEM_RELEASE);
break;
}
2000-02-17 20:38:33 +01:00
}
2000-07-16 06:10:33 +02:00
/* Initialization for all linked DLLs, called by dll_crt0_1. */
2000-02-17 20:38:33 +01:00
void
dll_list::init ()
2000-02-17 20:38:33 +01:00
{
/* Make sure that destructors are called on exit. */
if (!dll_global_dtors_recorded)
2000-02-17 20:38:33 +01:00
{
atexit (dll_global_dtors);
dll_global_dtors_recorded = 1;
2000-02-17 20:38:33 +01:00
}
/* Walk the dll chain, initializing each dll */
dll *d = &start;
while ((d = d->next))
d->init ();
2000-02-17 20:38:33 +01:00
}
#define A64K (64 * 1024)
/* Mark every memory address up to "here" as reserved. This may force
Windows NT to load a DLL in the next available, lowest slot. */
static void
2000-02-17 20:38:33 +01:00
reserve_upto (const char *name, DWORD here)
{
DWORD size;
MEMORY_BASIC_INFORMATION mb;
for (DWORD start = 0x10000; start < here; start += size)
if (!VirtualQuery ((void *) start, &mb, sizeof (mb)))
size = A64K;
2000-02-17 20:38:33 +01:00
else
{
size = A64K * ((mb.RegionSize + A64K - 1) / A64K);
start = A64K * (((DWORD) mb.BaseAddress + A64K - 1) / A64K);
if (start + size > here)
size = here - start;
if (mb.State == MEM_FREE &&
!VirtualAlloc ((void *) start, size, MEM_RESERVE, PAGE_NOACCESS))
api_fatal ("couldn't allocate memory %p(%d) for '%s' alignment, %E\n",
start, size, name);
}
}
/* Release all of the memory previously allocated by "upto" above.
Note that this may also free otherwise reserved memory. If that becomes
a problem, we'll have to keep track of the memory that we reserve above. */
static void
2000-02-17 20:38:33 +01:00
release_upto (const char *name, DWORD here)
{
DWORD size;
MEMORY_BASIC_INFORMATION mb;
for (DWORD start = 0x10000; start < here; start += size)
if (!VirtualQuery ((void *) start, &mb, sizeof (mb)))
size = 64 * 1024;
else
{
size = mb.RegionSize;
if (!(mb.State == MEM_RESERVE && mb.AllocationProtect == PAGE_NOACCESS &&
(((void *) start < cygheap->user_heap.base
|| (void *) start > cygheap->user_heap.top) &&
2002-11-02 04:31:15 +01:00
((void *) start < (void *) cygheap
| (void *) start > (void *) ((char *) cygheap + CYGHEAPSIZE)))))
2000-02-17 20:38:33 +01:00
continue;
if (!VirtualFree ((void *) start, 0, MEM_RELEASE))
api_fatal ("couldn't release memory %p(%d) for '%s' alignment, %E\n",
start, size, name);
}
}
/* Reload DLLs after a fork. Iterates over the list of dynamically loaded DLLs
and attempts to load them in the same place as they were loaded in the parent. */
void
dll_list::load_after_fork (HANDLE parent, dll *first)
2000-02-17 20:38:33 +01:00
{
in_forkee = 1;
2000-02-17 20:38:33 +01:00
int try2 = 0;
dll d;
2000-02-17 20:38:33 +01:00
void *next = first;
while (next)
{
DWORD nb;
/* Read the dll structure from the parent. */
2000-07-16 06:10:33 +02:00
if (!ReadProcessMemory (parent, next, &d, sizeof (dll), &nb) ||
nb != sizeof (dll))
return;
2000-07-16 06:10:33 +02:00
/* We're only interested in dynamically loaded dlls.
Hopefully, this function wouldn't even have been called unless
the parent had some of those. */
if (d.type == DLL_LOAD)
{
bool unload = true;
HMODULE h = LoadLibraryEx (d.name, NULL, DONT_RESOLVE_DLL_REFERENCES);
if (!h)
system_printf ("can't reload %s", d.name);
/* See if DLL will load in proper place. If so, free it and reload
it the right way.
It sort of stinks that we can't invert the order of the FreeLibrary
and LoadLibrary since Microsoft documentation seems to imply that that
should do what we want. However, since the library was loaded above,
2000-07-16 06:10:33 +02:00
the second LoadLibrary does not execute it's startup code unless it
is first unloaded. */
else if (h == d.handle)
{
if (unload)
{
FreeLibrary (h);
LoadLibrary (d.name);
}
}
else if (try2)
api_fatal ("unable to remap %s to same address as parent(%p) != %p",
d.name, d.handle, h);
else
{
/* It loaded in the wrong place. Dunno why this happens but it always
seems to happen when there are multiple DLLs attempting to load into
the same address space. In the "forked" process, the second DLL always
loads into a different location. */
FreeLibrary (h);
/* Block all of the memory up to the new load address. */
reserve_upto (d.name, (DWORD) d.handle);
try2 = 1; /* And try */
continue; /* again. */
}
/* If we reached here, and try2 is set, then there is a lot of memory to
release. */
if (try2)
{
release_upto (d.name, (DWORD) d.handle);
try2 = 0;
}
}
next = d.next; /* Get the address of the next DLL. */
}
in_forkee = 0;
2000-02-17 20:38:33 +01:00
}
extern "C" int
2000-02-17 20:38:33 +01:00
dll_dllcrt0 (HMODULE h, per_process *p)
{
if (p == NULL)
p = &__cygwin_user_data;
else
*(p->impure_ptr_ptr) = __cygwin_user_data.impure_ptr;
bool initializing = in_forkee || cygwin_finished_initializing;
2000-02-17 20:38:33 +01:00
/* Partially initialize Cygwin guts for non-cygwin apps. */
if (dynamically_loaded && user_data->magic_biscuit == 0)
dll_crt0 (p);
else
check_sanity_and_sync (p);
dll_type type;
/* If this function is called before cygwin has finished
initializing, then the DLL must be a cygwin-aware DLL
that was explicitly linked into the program rather than
a dlopened DLL. */
if (!initializing)
type = DLL_LINK;
else
{
type = DLL_LOAD;
dlls.reload_on_fork = 1;
}
/* Allocate and initialize space for the DLL. */
dll *d = dlls.alloc (h, p, type);
/* If d == NULL, then something is broken.
Otherwise, if we've finished initializing, it's ok to
initialize the DLL. If we haven't finished initializing,
it may not be safe to call the dll's "main" since not
all of cygwin's internal structures may have been set up. */
if (!d || (initializing && !d->init ()))
return -1;
return (DWORD) d;
2000-02-17 20:38:33 +01:00
}
/* OBSOLETE: This function is obsolescent and will go away in the
future. Cygwin can now handle being loaded from a noncygwin app
using the same entry point. */
extern "C" int
2000-02-17 20:38:33 +01:00
dll_noncygwin_dllcrt0 (HMODULE h, per_process *p)
{
return dll_dllcrt0 (h, p);
}
extern "C" void
cygwin_detach_dll (dll *)
2000-02-17 20:38:33 +01:00
{
dlls.detach (__builtin_return_address (0));
2000-02-17 20:38:33 +01:00
}
extern "C" void
2000-02-17 20:38:33 +01:00
dlfork (int val)
{
dlls.reload_on_fork = val;
2000-02-17 20:38:33 +01:00
}
/* Called from various places to update all of the individual
ideas of the environ block. Explain to me again why we didn't
just import __cygwin_environ? */
void __stdcall
update_envptrs ()
{
extern char ***main_environ;
for (dll *d = dlls.istart (DLL_ANY); d; d = dlls.inext ())
{
*(d->p.envptr) = __cygwin_environ;
}
*main_environ = __cygwin_environ;
}