It makes no sense to have a left pointing arrow as the desktop icon.
[wine/testsucceed.git] / documentation / winedev-kernel.sgml
blob7efd9d3ac73ec0f90b42cbd0dcdca595fb691f96
1 <chapter>
2 <title>Kernel modules</title>
3 <para>
4 This section covers the kernel modules. As already stated, Wine
5 implements the NT architecture, hence provides <filename>NTDLL</filename>
6 for the core kernel functions, and <filename>KERNEL32</filename>, which is
7 the implementation of the basis of the Win32 subsystem, on top of
8 <filename>NTDLL</filename>.
9 </para>
10 <para>
11 This chapter is made of two types of material (depending of their point of
12 view). Some items will be tackled from a global point of view and then,
13 when needed, explaining the split of work between
14 <filename>NTDLL</filename> and <filename>KERNEL32</filename>; some others
15 will be tackled from a DLL point of view (<filename>NTDLL</filename> or
16 <filename>KERNEL32</filename>). The choice is made so that the output is
17 more readable and understantable. At least, that's the intend (sigh).
18 </para>
20 <sect1 id="initialization">
22 <title>The Wine initialization process</title>
24 <para>
25 Wine has a rather complex startup procedure, so unlike many programs the
26 best place to begin exploring the code-base is
27 <emphasis>not</emphasis> in fact at the <function>main()</function>
28 function but instead at some of the more straightforward DLLs that
29 exist on the periphery such as MSI, the widget library (in
30 <filename>USER</filename> and <filename>COMCTL32</filename>) etc. The
31 purpose of this section is to document and explain how Wine starts up
32 from the moment the user runs "<command>wine myprogram.exe</command>" to
33 the point at which <filename>myprogram</filename> gets control.
34 </para>
36 <sect2>
37 <title>First Steps</title>
39 <para>
40 The actual wine binary that the user runs does not do very much, in
41 fact it is only responsible for checking the threading model in use
42 (NPTL vs LinuxThreads) and then invoking a new binary which performs
43 the next stage in the startup sequence. See the beginning of this
44 chapter for more information on this check and why it's necessary. You
45 can find this code in <filename>loader/glibc.c</filename>. The result
46 of this check is an exec of either <command>wine-pthread</command> or
47 <command>wine-kthread</command>, potentially (on Linux) via the
48 <emphasis>preloader</emphasis>. We need to use separate binaries here
49 because overriding the native pthreads library requires us to exploit
50 a property of ELF symbol fixup semantics: it's not possible to do this
51 without starting a new process.
52 </para>
54 <para>
55 The Wine preloader is found in
56 <filename>loader/preloader.c</filename>, and is required in order to
57 impose a Win32 style address space layout upon the newly created Win32
58 process. The details of what this does is covered in the address space
59 layout chapter. The preloader is a statically linked ELF binary which
60 is passed the name of the actual Wine binary to run (either
61 <command>wine-kthread</command> or <command>wine-pthread</command>)
62 along with the arguments the user passed in from the command line. The
63 preloader is an unusual program: it does not have a
64 <function>main()</function> function. In standard ELF applications,
65 the entry point is actually at a symbol named
66 <function>_start()</function>: this is provided by the
67 standard <command>gcc</command> infrastructure and normally jumps to
68 <function>__libc_start_main()</function> which initializes glibc before
69 passing control to the main function as defined by the programmer.
70 </para>
72 <para>
73 The preloader takes control direct from the entry point for a few
74 reasons. Firstly, it is required that glibc is not initialized twice:
75 the result of such behaviour is undefined and subject to change
76 without notice. Secondly, it's possible that as part of initializing
77 glibc, the address space layout could be changed - for instance, any
78 call to <function>malloc()</function> will initialize a heap arena
79 which modifies the VM mappings. Finally, glibc does not return to
80 <function>_start()</function> at any point, so by reusing it we avoid
81 the need to recreate the ELF bootstrap stack
82 (<varname>env</varname>, <varname>argv</varname>, auxiliary array etc).
83 </para>
85 <para>
86 The preloader is responsible for two things: protecting important
87 regions of the address space so the dynamic linker does not map shared
88 libraries into them, and once that is done loading the real Wine
89 binary off disk, linking it and starting it up. Normally all this is
90 automatically by glibc and the kernel but as we intercepted this
91 process by using a static binary it's up to us to restart the
92 process. The bulk of the code in the preloader is about loading
93 <command>wine-[pk]thread</command> and
94 <filename>ld-linux.so.2</filename> off disk, linking them together,
95 then starting the dynamic linking process.
96 </para>
98 <para>
99 One of the last things the preloader does before jumping into the
100 dynamic linker is scan the symbol table of the loaded Wine binary and
101 set the value of a global variable directly: this is a more efficient
102 way of passing information to the main Wine program than flattening
103 the data structures into an environment variable or command line
104 parameter then unpacking it on the other side, but it achieves pretty
105 much the same thing. The global variable set points to the preload
106 descriptor table, which contains the VMA regions protected by the
107 preloader. This allows Wine to unmap them once the dynamic linker has
108 been run, so leaving gaps we can initialize properly later on.
109 </para>
111 </sect2>
113 <sect2>
114 <title>Starting the emulator</title>
116 <para>
117 The process of starting up the emulator itself is mostly one of
118 chaining through various initializer functions defined in the core
119 libraries and DLLs: <filename>libwine</filename>, then
120 <filename>NTDLL</filename>, then <filename>KERNEL32</filename>.
121 </para>
123 <para>
124 Both the <command>wine-pthread</command> and
125 <command>wine-kthread</command> binaries share a common
126 <function>main()</function> function, defined in
127 <filename>loader/main.c</filename>, so no matter which binary is
128 selected after the preloader has run we start here. This passes the
129 information provided by the preloader into
130 <filename>libwine</filename> and then calls
131 <function>wine_init()</function>, defined in
132 <filename>libs/wine/loader.c</filename>. This is where the emulation
133 really starts:
134 <function>wine_init()</function> can, with the correct preparation,
135 be called from programs other than the wine loader itself.
136 </para>
138 <para>
139 <function>wine_init()</function> does some very basic setup tasks such
140 as initializing the debugging infrastructure, yet more address space
141 manipulation (see the information on the 4G/4G VM split in the address
142 space chapter), before loading <filename>NTDLL</filename> - the core
143 of both Wine and the Windows NT series - and jumping to the
144 <function>__wine_process_init()</function> function defined
145 in <filename>dlls/ntdll/loader.c</filename>
146 </para>
148 <para>
149 This function is responsible for initializing the primary Win32
150 environment. In <function>thread_init()</function>, it sets up the
151 TEB, the <command>wineserver</command> connection for the main thread
152 and the process heap. See the beginning of this chapter for more
153 information on this.
155 </para>
157 <para>
158 Finally, it loads and jumps to
159 <function>__wine_kernel_init()</function> in
160 <filename>KERNEL32.DLL</filename>: this is defined in
161 <filename>dlls/kernel32/process.c</filename>. This is where the bulk
162 of the work is done. The <filename>KERNEL32</filename> initialization
163 code retrieves the startup info for the process from the server,
164 initializes the registry, sets up the drive mapping system and locale
165 data, then begins loading the requested application itself. Each
166 process has a <structname>STARTUPINFO</structname> block that can be
167 passed into <function>CreateProcess</function> specifying various
168 things like how the first window should be displayed: this is sent to
169 the new process via the <command>wineserver</command>.
170 </para>
172 <para>
173 After determining the type of file given to Wine by the user (a Win32
174 EXE file, a Win16 EXE, a Winelib app etc), the program is loaded into
175 memory (which may involve loading and initializing other DLLs, the
176 bulk of Wines startup code), before control reaches the end of
177 <function>__wine_kernel_init()</function>. This function ends with the
178 new process stack being initialized, and start_process being called on
179 the new stack. Nearly there!
180 </para>
182 <para>
183 The final element of initializing Wine is starting the newly loaded
184 program itself. <function>start_process()</function> sets up the SEH
185 backstop handler, calls <function>LdrInitializeThunk()</function>
186 which performs the last part of the process initialization (such as
187 performing relocations and calling the <function>DllMain()</function>
188 with <constant>PROCESS_ATTACH</constant>), grabs the entry point of
189 the executable and then on this line:
190 </para>
192 <programlisting>
193 ExitProcess( entry( peb ) );
194 </programlisting>
196 <para>
197 ... jumps to the entry point of the program. At this point the users
198 program is running and the API provided by Wine is ready to be
199 used. When entry returns, the <function>ExitProcess()</function> API
200 will be used to initialize a graceful shutdown.
201 </para>
202 </sect2>
203 </sect1>
205 <sect1>
206 <title>Detailed memory management</title>
207 <para>
208 As already explained in previous chapter (see <xref linkend="arch-mem">
209 for the details), Wine creates every 32-bit Windows process in its own
210 32 address space. Wine also tries to map at the relevant addresses what
211 Windows would do. There are however a few nasty bits to look at.
212 </para>
214 <sect2>
215 <title>Implementation</title>
216 <para>
217 Wine (with a bit of black magic) is able to map the main module at
218 it's desired address (likely <constant>0x400000</constant>), to create
219 the process heap, its stack (as a Windows executable can ask for a
220 specific stack size), Wine simply use the initial stack of the ELF
221 executable for its initialisation, but creates a new stack (as a Win32
222 one) for the main thread of the executable. Wine also tries to map all
223 native DLLs at their desired address, so that no relocation has to be
224 performed.
225 </para>
226 <para>
227 Wine also implements the shared heap so native win9x DLLs can be
228 used. This heap is always created at the
229 <constant>SYSTEM_HEAP_BASE</constant> address or
230 <constant>0x80000000</constant> and defaults to 16 megabytes in size.
231 </para>
232 <para>
233 There are a few other magic locations. The bottom 64k of memory is
234 deliberately left unmapped to catch null pointer dereferences. The
235 region from 64k to 1mb+64k are reserved for DOS compatibility and
236 contain various DOS data structures. Finally, the address space also
237 contains mappings for the Wine binary itself, any native libaries
238 Wine is using, the glibc malloc arena and so on.
239 </para>
240 </sect2>
242 <sect2 id="address-space">
243 <title>Laying out the address space</title>
245 <para>
246 Up until about the start of 2004, the Linux address space very much
247 resembled the Windows 9x layout: the kernel sat in the top gigabyte,
248 the bottom pages were unmapped to catch null pointer dereferences, and
249 the rest was free. The kernels mmap algorithm was predictable: it
250 would start by mapping files at low addresses and work up from there.
251 </para>
253 <para>
254 The development of a series of new low level patches violated many of
255 these assumptions, and resulted in Wine needing to force the Win32
256 address space layout upon the system. This section looks at why and
257 how this is done.
258 </para>
260 <para>
261 The exec-shield patch increases security by randomizing the kernels
262 mmap algorithms. Rather than consistently choosing the same addresses
263 given the same sequence of requests, the kernel will now choose
264 randomized addresses. Because the Linux dynamic linker
265 (<filename>ld-linux.so.2</filename>) loads DSOs into memory by using
266 mmap, this means that DSOs are no longer loaded at predictable
267 addresses, so making it harder to attack software by using buffer
268 overflows. It also attempts to relocate certain binaries into a
269 special low area of memory known as the ASCII armor so making it
270 harder to jump into them when using string based attacks.
271 </para>
273 <para>
274 Prelink is a technology that enhances startup times by precalculating
275 ELF global offset tables then saving the results inside the native
276 binaries themselves. By grid fitting each DSO into the address space,
277 the dynamic linker does not have to perform as many relocations so
278 allowing applications that heavily rely on dynamic linkage to be
279 loaded into memory much quicker. Complex C++ applications such as
280 Mozilla, OpenOffice and KDE can especially benefit from this
281 technique.
282 </para>
284 <para>
285 The 4G VM split patch was developed by Ingo Molnar. It gives the Linux
286 kernel its own address space, thereby allowing processes to access the
287 maximum addressable amount of memory on a 32-bit machine: 4
288 gigabytes. It allows people with lots of RAM to fully utilise that in
289 any given process at the cost of performance: the reason behind giving
290 the kernel a part of each processes address space was to avoid the
291 overhead of switching on each syscall.
292 </para>
294 <para>
295 Each of these changes alter the address space in a way incompatible
296 with Windows. Prelink and exec-shield mean that the libraries Wine
297 uses can be placed at any point in the address space: typically this
298 meant that a library was sitting in the region that the EXE you wanted
299 to run had to be loaded (remember that unlike DLLs, EXE files cannot
300 be moved around in memory). The 4G VM split means that programs could
301 receive pointers to the top gigabyte of address space which some are
302 not prepared for (they may store extra information in the high bits of
303 a pointer, for instance). In particular, in combination with
304 exec-shield this one is especially deadly as it's possible the process
305 heap could be allocated beyond
306 <constant>ADDRESS_SPACE_LIMIT</constant> which causes Wine
307 initialization to fail.
308 </para>
310 <para>
311 The solution to these problems is for Wine to reserve particular parts
312 of the address space so that areas that we don't want the system to
313 use will be avoided. We later on (re/de)allocate those areas as
314 needed. One problem is that some of these mappings are put in place
315 automatically by the dynamic linker: for instance any libraries that
316 Wine is linked to (like <filename>libc</filename>,
317 <filename>libwine</filename>, <filename>libpthread</filename> etc)
318 will be mapped into memory before Wine even gets control. In order to
319 solve that, Wine overrides the default ELF initialization sequence at
320 a low level and reserves the needed areas by using direct syscalls
321 into the kernel (ie without linking against any other code to do it)
322 before restarting the standard initialization and letting the dynamic
323 linker continue. This is referred to as the preloader and is found in
324 <filename>loader/preloader.c</filename>.
325 </para>
327 <para>
328 Once the usual ELF boot sequence has been completed, some native
329 libraries may well have been mapped above the 3gig limit: however,
330 this doesn't matter as 3G is a Windows limit, not a Linux limit. We
331 still have to prevent the system from allocating anything else above
332 there (like the heap or other DLLs) though so Wine performs a binary
333 search over the upper gig of address space in order to iteratively
334 fill in the holes with <constant>MAP_NORESERVE</constant> mappings so
335 the address space is allocated but the memory to actually back it is
336 not. This code can be found in
337 <filename>libs/wine/mmap.c</filename>:<function>reserve_area</function>.
338 </para>
339 </sect2>
340 </sect1>
342 <sect1>
343 <title>Multi-processing in Wine</title>
344 <para>
345 Let's take a closer look at the way Wine loads and run processes in memory.
346 </para>
347 <sect2>
348 <title>Starting a process from command line</title>
349 <para>
350 When starting a Wine process from command line (we'll get later on to
351 the differences between NE, PE and Winelib executables), there are a
352 couple of things Wine need to do first. A first executable is run to
353 check the threading model of the underlying OS (see
354 <xref linkend="threading"> for the details) and will start the real
355 Wine loader corresponding to the choosen threading model.
356 </para>
357 <para>
358 Then Wine graps a few elements from the Unix world: the environment,
359 the program arguments. Then the <filename>ntdll.dll.so</filename> is
360 loaded into memory using the standard shared library dynamic
361 loader. When loaded, <filename>NTDLL</filename> will mainly first
362 create a decent Windows environment:
363 <itemizedlist>
364 <listitem>
365 <para>
366 create a PEB (Process Environment Block) and a TEB (Thread
367 Environment Block).
368 </para>
369 </listitem>
370 <listitem>
371 <para>
372 set up the connection to the Wine server - and eventually
373 launching the Wine server if none runs
374 </para>
375 </listitem>
376 <listitem>
377 <para>create the process heap</para>
378 </listitem>
379 </itemizedlist>
380 </para>
381 <para>
382 Then <filename>Kernel32</filename> is loaded (but now using the
383 Windows dynamic loading capabilities) and a Wine specific entry point
384 is called <function>__wine_kernel_init</function>. This function will
385 actually handle all the logic of the process loading and execution,
386 and will never return from it's call.
387 </para>
388 <para>
389 <function>__wine_kernel_init</function> will undergo the following
390 tasks:
391 <itemizedlist>
392 <listitem>
393 <para>
394 initialization of program arguments from Unix program arguments
395 </para>
396 </listitem>
397 <listitem>
398 <para>lookup of executable in the file system</para>
399 </listitem>
400 <listitem>
401 <para>
402 If the file is not found, then an error is printed and the Wine
403 loader stops.
404 </para>
405 </listitem>
406 <listitem>
407 <para>
408 We'll cover the non-PE file type later on, so assume for now
409 it's a PE file. The PE module is loaded in memory using the
410 same mechanisms as for a native DLLs (mainly mapping the file
411 data and code sections into memory, and handling relocation if
412 needed). Note that the dependencies on the module are not
413 resolved at this point.
414 </para>
415 </listitem>
416 <listitem>
417 <para>
418 A new stack is created, which size is given in the PE header,
419 and this stack is made the one of the running thread (which is
420 still the only one in the process). The stack used at startup
421 will no longer be used.
422 </para>
423 </listitem>
424 <listitem>
425 <para>
426 Which this new stack,
427 <function>ntdll.LdrInitializeThunk</function> is called which
428 performs the remaining initialization parts, including resolving
429 all the DLL imports on the PE module, and doing the init of the
430 TLS slots.
431 </para>
432 </listitem>
433 <listitem>
434 <para>
435 Control can now be passed to the <function>EntryPoint</function>
436 of the PE module, which will let the executable run.
437 </para>
438 </listitem>
439 </itemizedlist>
440 </para>
441 </sect2>
442 <sect2>
443 <title>Creating a child process from a running process</title>
444 <para>
445 The steps used are closely link to what is done in the previous case.
446 </para>
447 <para>
448 There are however a few points to look at a bit more closely. The
449 inner implementation creates the child process using the
450 <function>fork()</function> and <function>exec()</function>
451 calls. This means that we don't need to check again for the threading
452 model, we can use what the parent (or the grand-parent process...)
453 started from command line has found.
454 </para>
455 <para>
456 The Win32 process creation allows to pass a lot of information between
457 the parent and the child. This includes object handles, windows title,
458 console parameters, environment strings... Wine makes use of both the
459 standard Unix inheritance mechanisms (for environment for example) and
460 the Wine server (to pass from parent to child a chunk of data
461 containing the relevant information).
462 </para>
463 <para>
464 The previously described loading mechanism will check in the Wine
465 server if such a chunk exists, and, if so, will perform the relevant
466 initialization.
467 </para>
468 <para>
469 Some further synchronization is also put in place: a parent will wait
470 until the child has started, or has failed. The Wine server is also
471 used to perform those tasks.
472 </para>
473 </sect2>
474 <sect2>
475 <title>Starting a Winelib process</title>
476 <para>
477 Before going into the gory details, let's first go back to what a
478 Winelib application is. It can be either a regular Unix executable, or
479 a more specific Wine beast. This later form in fact creates two files
480 for a given executable (say <filename>foo.exe</filename>). The first
481 one, named <filename>foo</filename> will be a symbolic link to the
482 Wine loader (<filename>wine</filename>). The second one, named
483 <filename>foo.exe.so</filename>, is the equivalent of the
484 <filename>.dll.so</filename> files we've already described for
485 DLLs. As in Windows, an executable is, among other things, a module
486 with its import and export information, as any DLL, it makes sense
487 Wine uses the same mechanisms for loading native executables and
488 DLLs.
489 </para>
490 <para>
491 When starting a Winelib application from the command line (say with
492 <command>foo arg1 arg2</command>), the Unix shell will execute
493 <command>foo</command> as a Unix executable. Since this is in fact the
494 Wine loader, Wine will fire up. However, will notice that it hasn't
495 been started as <command>wine</command> but as <command>foo</command>,
496 and hence, will try to load (using Unix shared library mechanism) the
497 second file <filename>foo.exe.so</filename>. Wine will recognize a 32
498 bit module (with its descriptor) embedded in the shared library, and
499 once the shared library loaded, it will proceed the same path as when
500 loading a standard native PE executable.
501 </para>
502 <para>
503 Wine needs to implement this second form of executable in order to
504 maintain the order of initialization of some elements in the
505 executable. One particular issue is when dealing with global C++
506 objects. In standard Unix executable, the call of the constructor to
507 such objects is stored in the specific section of the executable
508 (<function>.init</function> not to name it). All constructors in this
509 section are called before the <function>main()</function> or
510 <function>WinMain</function> function is called. Creating a Wine
511 executable using the first form mentionned above will let those
512 constructors being called before Wine gets a chance to initialize
513 itself. So, any constructor using a Windows API will fail, because
514 Wine infrastructure isn't in place. The use of the second form for
515 Winelib executables ensures that we do the initialization using the
516 following steps:
517 <itemizedlist>
518 <listitem>
519 <para>
520 initialize the Wine infrastructure
521 </para>
522 </listitem>
523 <listitem>
524 <para>
525 load the executable into memory
526 </para>
527 </listitem>
528 <listitem>
529 <para>
530 handle the import sections for the executable
531 </para>
532 </listitem>
533 <listitem>
534 <para>
535 call the global object constructors (if any). They now can
536 properly call the Windows APIs
537 </para>
538 </listitem>
539 <listitem>
540 <para>
541 call the executable entry point
542 </para>
543 </listitem>
544 </itemizedlist>
545 </para>
546 <para>
547 The attentive reader would have noted that the resolution of imports
548 for the executable is done, as for a DLL, when the executable/DLL
549 descriptor is registered. However, this is done also by adding a
550 specific constructor in the <function>.init</function> section. For
551 the above describe scheme to function properly, this constructor must
552 be the first constructor to be called, before all the other
553 constructors, generated by the executable itself. The Wine build chain
554 takes care of that, and also generating the executable/DLL descriptor
555 for the Winelib executable.
556 </para>
557 </sect2>
558 </sect1>
560 <sect1 id="threading">
561 <title>Multi-threading in Wine</title>
563 <para>
564 This section will assume you understand the basics of multithreading. If
565 not there are plenty of good tutorials available on the net to get you
566 started.
567 </para>
569 <para>
570 Threading in Wine is somewhat complex due to several factors. The first
571 is the advanced level of multithreading support provided by Windows -
572 there are far more threading related constructs available in Win32 than
573 the Linux equivalent (pthreads). The second is the need to be able to
574 map Win32 threads to native Linux threads which provides us with
575 benefits like having the kernel schedule them without our
576 intervention. While it's possible to implement threading entirely
577 without kernel support, doing so is not desirable on most platforms that
578 Wine runs on.
579 </para>
581 <sect2>
582 <title>Threading support in Win32</title>
584 <para>
585 Win32 is an unusually thread friendly API. Not only is it entirely
586 thread safe, but it provides many different facilities for working
587 with threads. These range from the basics such as starting and
588 stopping threads, to the extremely complex such as injecting threads
589 into other processes and COM inter-thread marshalling.
590 </para>
592 <para>
593 One of the primary challenges of writing Wine code therefore is
594 ensuring that all our DLLs are thread safe, free of race conditions
595 and so on. This isn't simple - don't be afraid to ask if you aren't
596 sure whether a piece of code is thread safe or not!
597 </para>
599 <para>
600 Win32 provides many different ways you can make your code thread safe
601 however the most common are <emphasis>critical section</emphasis> and
602 the <emphasis>interlocked functions</emphasis>. Critical sections are
603 a type of mutex designed to protect a geographic area of code. If you
604 don't want multiple threads running in a piece of code at once, you
605 can protect them with calls to
606 <function>EnterCriticalSection()</function> and
607 <function>LeaveCriticalSection()</function>. The first call to
608 <function>EnterCriticalSection()</function> by a thread will lock the
609 section and continue without stopping. If another thread calls it then
610 it will block until the original thread calls
611 <function>LeaveCriticalSection()</function> again.
612 </para>
614 <para>
615 It is therefore vitally important that if you use critical sections to
616 make some code thread-safe, that you check every possible codepath out
617 of the code to ensure that any held sections are left. Code like this:
618 </para>
620 <programlisting>
621 if (res != ERROR_SUCCESS) return res;
622 </programlisting>
624 <para>
625 is extremely suspect in a function that also contains a call to
626 <function>EnterCriticalSection()</function>. Be careful.
627 </para>
629 <para>
630 If a thread blocks while waiting for another thread to leave a
631 critical section, you will see an error from the
632 <function>RtlpWaitForCriticalSection()</function> function, along with
633 a note of which thread is holding the lock. This only appears after a
634 certain timeout, normally a few seconds. It's possible the thread
635 holding the lock is just being really slow which is why Wine won't
636 terminate the app like a non-checked build of Windows would, but the
637 most common cause is that for some reason a thread forgot to call
638 <function>LeaveCriticalSection()</function>, or died while holding the
639 lock (perhaps because it was in turn waiting for another lock). This
640 doesn't just happen in Wine code: a deadlock while waiting for a
641 critical section could be due to a bug in the app triggered by a
642 slight difference in the emulation.
643 </para>
645 <para>
646 Another popular mechanism available is the use of functions like
647 <function>InterlockedIncrement()</function>
648 and <function>InterlockedExchange()</function>. These make use of native
649 CPU abilities to execute a single instruction while ensuring any other
650 processors on the system cannot access memory, and allow you to do
651 common operations like add/remove/check a variable in thread-safe code
652 without holding a mutex. These are useful for reference counting
653 especially in free-threaded (thread safe) COM objects.
654 </para>
656 <para>
657 Finally, the usage of TLS slots are also popular. TLS stands for
658 thread-local storage, and is a set of slots scoped local to a thread
659 which you can store pointers in. Look on MSDN for the
660 <function>TlsAlloc()</function> function to learn more about the Win32
661 implementation of this. Essentially, the contents of a given slot will
662 be different in each thread, so you can use this to store data that is
663 only meaningful in the context of a single thread. On recent versions
664 of Linux the __thread keyword provides a convenient interface to this
665 functionality - a more portable API is exposed in the pthread
666 library. However, these facilities are not used by Wine, rather, we
667 implement Win32 TLS entirely ourselves.
668 </para>
669 </sect2>
671 <sect2>
672 <title>POSIX threading vs. kernel threading</title>
674 <para>
675 Wine runs in one of two modes: either pthreads (posix threading) or
676 kthreads (kernel threading). This section explains the differences
677 between them. The one that is used is automatically selected on
678 startup by a small test program which then execs the correct binary,
679 either <command>wine-kthread</command> or
680 <command>wine-pthread</command>. On NPTL-enabled systems pthreads
681 will be used, and on older non-NPTL systems kthreads is selected.
682 </para>
684 <para>
685 Let's start with a bit of history. Back in the dark ages when Wine's
686 threading support was first implemented a problem was faced - Windows
687 had much more capable threading APIs than Linux did. This presented a
688 problem - Wine works either by reimplementing an API entirely or by
689 mapping it onto the underlying systems equivalent. How could Win32
690 threading be implemented using a library which did not have all the
691 needed features? The answer, of course, was that it couldn't be.
692 </para>
694 <para>
695 On Linux the pthreads interface is used to start, stop and control
696 threads. The pthreads library in turn is based on top of so-called
697 "kernel threads" which are created using the
698 <function>clone(2)</function> syscall. Pthreads provides a nicer (more
699 portable) interface to this functionality and also provides APIs for
700 controlling mutexes. There is a <ulink
701 url="http://www.llnl.gov/computing/tutorials/pthreads/"> good
702 tutorial on pthreads</ulink> available if you want to learn more.
703 </para>
705 <para>
706 As pthreads did not provide the necessary semantics to implement Win32
707 threading, the decision was made to implement Win32 threading on top
708 of the underlying kernel threads by using syscalls like
709 <function>clone()</function> directly. This provided maximum
710 flexibility and allowed a correct implementation but caused some bad
711 side effects. Most notably, all the userland Linux APIs assumed that
712 the user was utilising the pthreads library. Some only enabled thread
713 safety when they detected that pthreads was in use - this is true of
714 glibc, for instance. Worse, pthreads and pure kernel threads had
715 strange interactions when run in the same process yet some libraries
716 used by Wine used pthreads internally. Throw in source code porting
717 using Winelib - where you have both UNIX and Win32 code in the same
718 process - and chaos was the result.
719 </para>
721 <para>
722 The solution was simple yet ingenious: Wine would provide its own
723 implementation of the pthread library <emphasis>inside</emphasis> its
724 own binary. Due to the semantics of ELF symbol scoping, this would
725 cause Wine's own implementation to override any implementation loaded
726 later on (like the real libpthread.so). Therefore, any calls to the
727 pthread APIs in external libraries would be linked to Wine's instead
728 of the system's pthreads library, and Wine implemented pthreads by
729 using the standard Windows threading APIs it in turn implemented
730 itself.
731 </para>
733 <para>
734 As a result, libraries that only became thread-safe in the presence of
735 a loaded pthreads implementation would now do so, and any external
736 code that used pthreads would actually end up creating Win32 threads
737 that Wine was aware of and controlled. This worked quite nicely for a
738 long time, even though it required doing some extremely un-kosher
739 things like overriding internal libc structures and functions. That
740 is, it worked until NPTL was developed at which point the underlying
741 thread implementation on Linux changed dramatically.
742 </para>
744 <para>
745 The fake pthread implementation can be found in
746 <filename>loader/kthread.c</filename>, which is used to
747 produce the <command>wine-kthread</command> binary. In contrast,
748 <filename>loader/pthread.c</filename> produces the
749 <command>wine-pthread</command> binary which is used on newer NPTL
750 systems.
751 </para>
753 <para>
754 NPTL is a new threading subsystem for Linux that hugely improves its
755 performance and flexibility. By allowing threads to become much more
756 scalable and adding new pthread APIs, NPTL made Linux competitive with
757 Windows in the multi-threaded world. Unfortunately it also broke many
758 assumptions made by Wine (as well as other applications such as the
759 Sun JVM and RealPlayer) in the process.
760 </para>
762 <para>
763 There was, however, some good news. NPTL made Linux threading powerful
764 enough that Win32 threads could now be implemented on top of pthreads
765 like any other normal application. There would no longer be problems
766 with mixing win32-kthreads and pthreads created by external libraries,
767 and no need to override glibc internals. As you can see from the
768 relative sizes of the <filename>loader/kthread.c</filename> and
769 <filename>loader/pthread.c</filename> files, the difference in code
770 complexity is considerable. NPTL also made several other semantic
771 changes to things such as signal delivery so changes were required in
772 many different places in Wine.
773 </para>
775 <para>
776 On non-Linux systems the threading interface is typically not powerful
777 enough to replicate the semantics Win32 applications expect and so
778 kthreads with the pthread overrides are used.
779 </para>
780 </sect2>
782 <sect2>
783 <title>The Win32 thread environment</title>
785 <para>
786 All Win32 code, whether from a native EXE/DLL or in Wine itself,
787 expects certain constructs to be present in its environment. This
788 section explores what those constructs are and how Wine sets them
789 up. The lack of this environment is one thing that makes it hard to
790 use Wine code directly from standard Linux applications - in order to
791 interact with Win32 code a thread must first be
792 "adopted" by Wine.
793 </para>
795 <para>
796 The first thing Win32 code requires is the
797 <emphasis>TEB</emphasis> or "Thread Environment Block". This is an
798 internal (undocumented) Windows structure associated with every thread
799 which stores a variety of things such as TLS slots, a pointer to the
800 threads message queue, the last error code and so on. You can see the
801 definition of the TEB in <filename>include/thread.h</filename>, or at
802 least what we know of it so far. Being internal and subject to change,
803 the layout of the TEB has had to be reverse engineered from scratch.
804 </para>
806 <para>
807 A pointer to the TEB is stored in the %fs register and can be accessed
808 using <function>NtCurrentTeb()</function> from within Wine code. %fs
809 actually stores a selector, and setting it therefore requires
810 modifying the processes local descriptor table (LDT) - the code to do
811 this is in <filename>lib/wine/ldt.c</filename>.
812 </para>
814 <para>
815 The TEB is required by nearly all Win32 code run in the Wine
816 environment, as any <command>wineserver</command> RPC will use it,
817 which in turn implies that any code which could possibly block for
818 instance by using a critical section) needs it. The TEB also holds the
819 SEH exception handler chain as the first element, so if disassembling
820 you see code like this:
821 </para>
823 <programlisting>movl %esp, %fs:0</programlisting>
825 <para>
826 ... then you are seeing the program set up an SEH handler frame. All
827 threads must have at least one SEH entry, which normally points to the
828 backstop handler which is ultimately responsible for popping up the
829 all-too-familiar This program has performed an illegal operation and
830 will be terminated" message. On Wine we just drop straight into the
831 debugger. A full description of SEH is out of the scope of this
832 section, however there are some good articles in MSJ if you are
833 interested.
834 </para>
836 <para>
837 All Win32-aware threads must have a <command>wineserver</command>
838 connection. Many different APIs require the ability to communicate
839 with the <command>wineserver</command>. In turn, the
840 <command>wineserver</command> must be aware of Win32 threads in order
841 to be able to accurately report information to other parts of the
842 program and do things like route inter-thread messages, dispatch APCs
843 (asynchronous procedure calls) and so on. Therefore a part of thread
844 initialization is initializing the thread server-side. The result is
845 not only correct information in the server, but a set of file
846 descriptors the thread can use to communicate with the server - the
847 request fd, reply fd and wait fd (used for blocking).
848 </para>
849 </sect2>
850 </sect1>
852 <sect1 id="seh">
853 <title>Structured Exception Handling</title>
855 <para>
856 Structured Exception Handling (or SEH) is an implementation of
857 exceptions inside the Windows core. It allows code written in different
858 languages to throw exceptions across DLL boundaries, and Windows reports
859 various errors like access violations by throwing them. This section
860 looks at how it works, and how it's implemented in Wine.
861 </para>
863 <sect2>
864 <title>How SEH works</title>
866 <para>
867 SEH is based on embedding
868 <structname>EXCEPTION_REGISTRATION_RECORD</structname> structures in
869 the stack. Together they form a linked list rooted at offset zero in
870 the TEB (see the threading section if you don't know what this is). A
871 registration record points to a handler function, and when an
872 exception is thrown the handlers are executed in turn. Each handler
873 returns a code, and they can elect to either continue through the
874 handler chain or it can handle the exception and then restart the
875 program. This is referred to as unwinding the stack. After each
876 handler is called it's popped off the chain.
877 </para>
879 <para>
880 Before the system begins unwinding the stack, it runs vectored
881 handlers. This is an extension to SEH available in Windows XP, and
882 allows registered functions to get a first chance to watch or deal
883 with any exceptions thrown in the entire program, from any thread.
884 </para>
886 <para>
887 A thrown exception is represented by an
888 <structname>EXCEPTION_RECORD</structname> structure. It consists of a
889 code, flags, an address and an arbitrary number of <type>DWORD</type>
890 parameters. Language runtimes can use these parameters to associate
891 language-specific information with the exception.
892 </para>
894 <para>
895 Exceptions can be triggered by many things. They can be thrown
896 explicitly by using the RaiseException API, or they can be triggered
897 by a crash (ie, translated from a signal). They may be used internally
898 by a language runtime to implement language-specific exceptions. They
899 can also be thrown across DCOM connections.
900 </para>
902 <para>
903 Visual C++ has various extensions to SEH which it uses to implement,
904 eg, object destruction on stack unwind as well as the ability to throw
905 arbitrary types. The code for this is in
906 <filename>dlls/msvcrt/except.c</filename>
907 </para>
909 </sect2>
911 <sect2>
912 <title>Translating signals to exceptions</title>
914 <para>
915 In Windows, compilers are expected to use the system exception
916 interface, and the kernel itself uses the same interface to
917 dynamically insert exceptions into a running program. By contrast on
918 Linux the exception ABI is implemented at the compiler level
919 (inside GCC and the linker) and the kernel tells a thread of
920 exceptional events by sending <emphasis>signals</emphasis>. The
921 language runtime may or may not translate these signals into native
922 exceptions, but whatever happens the kernel does not care.
923 </para>
925 <para>
926 You may think that if an app crashes, it's game over and it really
927 shouldn't matter how Wine handles this. It's what you might
928 intuitively guess, but you'd be wrong. In fact some Windows programs
929 expect to be able to crash themselves and recover later without the
930 user noticing, some contain buggy binary-only components from third
931 parties and use SEH to swallow crashes, and still others execute
932 priviledged (kernel-level) instructions and expect it to work. In
933 fact, at least one set of APIs (the <function>IsBad*Ptr()</function>
934 series) can only be implemented by performing an operation that may
935 crash and returning <constant>TRUE</constant> if it does, and
936 <constant>FALSE</constant> if it doesn't! So, Wine needs to not only
937 implement the SEH infrastructure but also translate Unix signals into
938 SEH exceptions.
939 </para>
941 <para>
942 The code to translate signals into exceptions is a part of
943 <filename>NTDLL</filename>, and can be found in
944 <filename>dlls/ntdll/signal_i386.c</filename>. This file sets up
945 handlers for various signals during Wine startup, and for the ones
946 that indicate exceptional conditions translates them into
947 exceptions. Some signals are used by Wine internally and have nothing
948 to do with SEH.
949 </para>
951 <para>
952 Signal handlers in Wine run on their own stack. Each thread has its
953 own signal stack which resides 4k after the TEB. This is important for
954 a couple of reasons. Firstly, because there's no guarantee that the
955 app thread which triggered the signal has enough stack space for the
956 Wine signal handling code. In Windows, if a thread hits the limits of
957 its stack it triggers a fault on the stack guard page. The language
958 runtime can use this to grow the stack if it wants to.
960 <!-- fixme: is it really the language runtime that does this? i
961 can't find any code in Wine to reallocate the stack on
962 STATUS_GUARD_PAGE_VIOLATION -->
964 However, because a guard page violation is just a regular segfault to
965 the kernel, that would lead to a nested signal handler and that gets
966 messy really quick so we disallow that in Wine. Secondly, setting up
967 the exception to throw requires modifying the stack of the thread
968 which triggered it, which is quite hard to do when you're still
969 running on it.
970 </para>
972 <para>
973 Windows exceptions typically contain more information than the Unix
974 standard APIs provide. For instance, a
975 <constant>STATUS_ACCESS_VIOLATION</constant> exception
976 (<constant>0xC0000005</constant>) structure contains the faulting
977 address, whereas a standard Unix <constant>SIGSEGV</constant> just
978 tells the app that it crashed. Usually this information is passed as
979 an extra parameter to the signal handler, however its location and
980 contents vary between kernels (BSD, Solaris, etc). This data is
981 provided in a <structname>SIGCONTEXT</structname> structure, and on
982 entry to the signal handler it contains the register state of the CPU
983 before the signal was sent. Modifying it will cause the kernel to
984 adjust the context before restarting the thread.
985 </para>
986 </sect2>
987 </sect1>
989 <sect1>
990 <title>File management</title>
991 <para>
992 With time, Windows API comes closer to the old Unix paradigm "Everything
993 is a file". Therefore, this whole section dedicated to file management
994 will cover firstly the file management, but also some other objects like
995 directories, and even devices, which are manipulated in Windows in a
996 rather coherent way. We'll see later on some other objects fitting
997 (more or less) in this picture (pipes or consoles to name a few).
998 </para>
1000 <para>
1001 First of all, Wine, while implementing the file interface from Windows,
1002 needs to maps a file name (expressed in the Windows world) onto a file
1003 name in the Unix world. This encompasses several aspects: how to map
1004 the file names, how to map access rights (both on files and
1005 directories), how to map physical devices (hardisks, but also other
1006 devices - like serial or parallel interfaces - and even VxDs).
1007 </para>
1009 <sect2>
1010 <title>Various Windows formats for file names</title>
1011 <para>
1012 Let's first review a bit the various forms Windows uses when it comes
1013 to file names.
1014 </para>
1016 <sect3>
1017 <title>The DOS inheritance</title>
1019 <para>
1020 At the beginning was DOS, where each file has to sit on a drive,
1021 called from a single letter. For separating device names from
1022 directory or file names, a ':' was appended to this single letter,
1023 hence giving the (in)-famous <filename>C:</filename> drive
1024 designations. Another great invention was to use some fixed names
1025 for accessing devices: not only where these named fixed, in a way
1026 you couldn't change the name if you'd wish to, but also, they were
1027 insensible to the location where you were using them. For example,
1028 it's well known that <filename>COM1</filename> designates the first
1029 serial port, but it's also true that
1030 <filename>c:\foo\bar\com1</filename> also designates the first
1031 serial port. It's still true today: on XP, you still cannot name a
1032 file <filename>COM1</filename>, whatever the directory!!!
1033 </para>
1034 <para>
1035 Well later on (with Windows 95), Microsoft decided to overcome some
1036 little details in file names: this included being able to get out of
1037 the 8+3 format (8 letters for the name, 3 letters for the
1038 extension), and so being able to use "long names" (that's the
1039 "official" naming; as you can guess, the 8+3 format is a short
1040 name), and also to use very strange characters in a file name (like
1041 a space, or even a '.'). You could then name a file
1042 <filename>My File V0.1.txt</filename>, instead of
1043 <filename>myfile01.txt</filename>. Just to keep on the fun side of
1044 things, for many years the format used on the disk itself for
1045 storing the names has been the short name as the real one and to use
1046 some tricky aliasing techniques to store the long name. When some
1047 newer disk file systems have been introduced (NTFS with NT), in
1048 replacement of the old FAT system (which had little evolved since
1049 the first days of DOS), the long name became the real name while the
1050 short name took the alias role.
1051 </para>
1052 <para>
1053 Windows also started to support mounting network shares, and see
1054 them as they were a local disk (through a specific drive letter).
1055 The way it has been done changed along the years, so we won't go
1056 into all the details (especially on the DOS and Win9x side).
1057 </para>
1058 </sect3>
1060 <sect3>
1061 <title>The NT way</title>
1062 <para>
1063 The introduction of NT allowed a deep change in the ways DOS had
1064 been handling devices:
1065 <itemizedlist>
1066 <listitem>
1067 <para>
1068 There's no longer a forest of DOS drive letters (even if the
1069 <command>assign</command> was a way to create symbolic links
1070 in the forest), but a single hierarchical space.
1071 </para>
1072 </listitem>
1073 <listitem>
1074 <para>
1075 This hierarchy includes several distinct elements. For
1076 example, <filename>\Device\Hardisk0\Partition0</filename>
1077 refers to the first partition on the first physical hard disk
1078 of the system.
1079 </para>
1080 </listitem>
1081 <listitem>
1082 <para>
1083 This hierarchy covers way more than just the files and drives
1084 related objects, but most of the objects in the system. We'll
1085 only cover here the file related part.
1086 </para>
1087 </listitem>
1088 <listitem>
1089 <para>
1090 This hierarchy is not directly accessible for the Win32 API,
1091 but only the <filename>NTDLL</filename> API. The Win32 API
1092 only allows to manipulate part of this hierarchy (the rest
1093 being hidden from the Win32 API). Of course, the part you see
1094 from Win32 API looks very similar to the one that DOS
1095 provided.
1096 </para>
1097 </listitem>
1098 <listitem>
1099 <para>
1100 Mounting a disk is performed by creating a symbol link in this
1101 hierarchy from <filename>\Global??\C:</filename> (the name
1102 seen from the Win32 API) to
1103 <filename>\Device\Harddiskvolume1</filename> which determines
1104 the partition on a physical disk where C: is going to be seen.
1105 </para>
1106 </listitem>
1107 <listitem>
1108 <para>
1109 Network shares are also accessible through a symbol link.
1110 However in this case, a symbol link is created from
1111 <filename>\Global??\UNC\host\share\</filename> for the share
1112 <filename>share</filename> on the machine
1113 <filename>host</filename>) to what's called a network
1114 redirector, and which will take care of 1/ the connection to
1115 the remote share, 2/ handling with that remote share the rest
1116 of the path (after the name of the server, and the name of the
1117 share on that server).
1118 </para>
1119 <note>
1120 <para>
1121 In NT naming convention, <filename>\Global??</filename> can
1122 also be called <filename>\??</filename> to shorten the
1123 access.
1124 </para>
1125 </note>
1126 </listitem>
1127 </itemizedlist>
1128 </para>
1129 <para>
1130 All of these things, make the NT system pretty much more flexible
1131 (you can add new types of filesystems if you want), you provide a
1132 unique name space for all objects, and most operations boil down to
1133 creating relationship between different objects.
1134 </para>
1135 </sect3>
1137 <sect3>
1138 <title>Wrap up</title>
1139 <para>
1140 Let's end this chapter about files in Windows with a review of the
1141 different formats used for file names:
1142 <itemizedlist>
1143 <listitem>
1144 <para><filename>c:\foo\bar</filename> is a full path.</para>
1145 </listitem>
1146 <listitem>
1147 <para>
1148 <filename>\foo\bar</filename> is an absolute path; the full
1149 path is created by appending the default drive (ie. the drive
1150 of the current directory).
1151 </para>
1152 </listitem>
1153 <listitem>
1154 <para>
1155 <filename>bar</filename> is a relative path; the full path is
1156 created by adding the current directory.
1157 </para>
1158 </listitem>
1159 <listitem>
1160 <para>
1161 <filename>c:bar</filename> is a drive relative path. Note
1162 that the case where <filename>c:</filename> is the drive of
1163 the current directory is rather easy; it's implemented the
1164 same way as the case just below (relative path). In the rest
1165 of this chapter, drive relative path will only cover the case
1166 where the drive in the path isn't the drive of the default
1167 directory. The resolution of this to a full pathname defers
1168 according to the version of Windows, and some parameters.
1169 Let's take some time browsing through these issues. On
1170 Windows 9x (as well as on DOS), the system maintains a process
1171 wide set of default directories per drive. Hence, in this
1172 case, it will resolve <filename>c:bar</filename> to the
1173 default directory on drive <filename>c:</filename> plus file
1174 <filename>bar</filename>. Of course, the default per drive
1175 directory is updated each time a new current directory is set
1176 (only the current directory of the drive specified is
1177 modified). On Windows NT, things differ a bit. Since NT
1178 implements a namespace for file closer to a single tree
1179 (instead of 26 drives), having a current directory per drive
1180 is a bit ackward. Hence, Windows NT default behavior is to
1181 have only one current directory across all drives (in fact, a
1182 current directory expressed in the global tree) - this
1183 directory is of course related to a given process -,
1184 <filename>c:bar</filename> is resolved this way:
1185 <itemizedlist>
1186 <listitem>
1187 <para>
1188 If <filename>c:</filename> is the drive of the default
1189 directory, the final path is the current directory plus
1190 <filename>bar</filename>.
1191 </para>
1192 </listitem>
1193 <listitem>
1194 <para>
1195 Otherwise it's resolved into
1196 <filename>c:\bar</filename>.
1197 </para>
1198 </listitem>
1199 <listitem>
1200 <para>
1201 In order to bridge the gap between the two
1202 implementations (Windows 9x and NT), NT adds a bit of
1203 complexity on the second case. If the
1204 <envar>=C:</envar> environment variable is defined, then
1205 it's value is used as a default directory for drive
1206 <filename>C:</filename>. This is handy, for example,
1207 when writing a DOS shell, where having a current drive
1208 per drive is still implemented, even on NT. This
1209 mechanism (through environment variables) is implemented
1210 on <command>CMD.EXE</command>, where those variables are
1211 set when you change directories with the
1212 <command>cd</command>. Since environment variables are
1213 inherited at process creation, the current directories
1214 settings are inherited by child processes, hence
1215 mimicing the behavior of the old DOS shell. There's no
1216 mechanism (in <filename>NTDLL</filename> or
1217 <filename>KERNEL32</filename>) to set up, when current
1218 directory changes, the relevant environment variables.
1219 This behavior is clearly band-aid, not a full featured
1220 extension of current directory behavior.
1221 </para>
1222 </listitem>
1223 </itemizedlist>
1224 Wine fully implements all those behaviors (the Windows 9x vs
1225 NT ones are triggered by the version flag in Wine).
1226 </para>
1227 </listitem>
1228 <listitem>
1229 <para>
1230 <filename>\\host\share</filename> is <firstterm>UNC</firstterm>
1231 (Universal Naming Convention) path, ie. represents a file on a
1232 remote share.
1233 </para>
1234 </listitem>
1235 <listitem>
1236 <para>
1237 <filename>\\.\device</filename> denotes a physical device
1238 installed in the system (as seen from the Win32 subsystem). A
1239 standard NT system will map it to the
1240 <filename>\??\device</filename> NT path. Then, as a standard
1241 configuration, <filename>\??\device</filename> is likely to be
1242 a link to in a physical device described and hooked into the
1243 <filename>\Device\</filename> tree. For example,
1244 <filename>COM1</filename> is a link to
1245 <filename>\Device\Serial0</filename>.
1246 </para>
1247 </listitem>
1248 <listitem>
1249 <para>
1250 On some versions of Windows, paths were limited to
1251 <constant>MAX_PATH</constant> characters. To circumvent this,
1252 Microsoft allowed paths to be <constant>32,767</constant>
1253 characters long, under the conditions that the path is
1254 expressed in Unicode (no Ansi version), and that the path is
1255 prefixed with <filename>\\?\</filename>. This convention is
1256 applicable to any of the cases described above.
1257 </para>
1258 </listitem>
1259 </itemizedlist>
1260 </para>
1261 <para>
1262 To summarize, what we've discussed so, let's put everything into a
1263 single table...
1264 <table>
1265 <title>DOS, Win32 and NT paths equivalences</title>
1266 <tgroup cols="3" align="left">
1267 <thead>
1268 <row>
1269 <entry>Type of path</entry>
1270 <entry>Win32 example</entry>
1271 <entry>NT equivalent</entry>
1272 <entry>Rule to construct</entry>
1273 </row>
1274 </thead>
1275 <tbody>
1276 <row>
1277 <entry>Full path</entry>
1278 <entry><filename>c:\foo\bar.txt</filename></entry>
1279 <entry><filename>\Global??\C:\foo\bar.txt</filename></entry>
1280 <entry>Simple concatenation</entry>
1281 </row>
1282 <row>
1283 <entry>Absolute path</entry>
1284 <entry><filename>\foo\bar.txt</filename></entry>
1285 <entry><filename>\Global??\J:\foo\bar.txt</filename></entry>
1286 <entry>
1287 Simple concatenation using the drive of the default
1288 directory (here J:)
1289 </entry>
1290 </row>
1291 <row>
1292 <entry>Relative path</entry>
1293 <entry><filename>gee\bar.txt</filename></entry>
1294 <entry>
1295 <filename>
1296 \Global??\J:\mydir\mysubdir\gee\bar.txt
1297 </filename>
1298 </entry>
1299 <entry>
1300 Simple concatenation using the default directory
1301 (here <filename>J:\mydir\mysubdir</filename>)
1302 </entry>
1303 </row>
1304 <row>
1305 <entry>Drive relative path</entry>
1306 <entry><filename>j:gee\bar.txt</filename></entry>
1307 <entry>
1308 <msgtext>
1309 <para>
1310 <itemizedlist>
1311 <listitem>
1312 <para>
1313 On Windows 9x (and DOS),
1314 <filename>J:\toto\gee\bar.txt</filename>.
1315 </para>
1316 </listitem>
1317 <listitem>
1318 <para>
1319 On Windows NT,
1320 <filename>J:\gee\bar.txt</filename>.
1321 </para>
1322 </listitem>
1323 <listitem>
1324 <para>
1325 On Windows NT,
1326 <filename>J:\tata\titi\bar.txt</filename>.
1327 </para>
1328 </listitem>
1329 </itemizedlist>
1330 </para>
1331 </msgtext>
1332 </entry>
1333 <entry>
1334 <msgtext>
1335 <para>
1336 <itemizedlist>
1337 <listitem>
1338 <para>
1339 On Windows NT (and DOS),
1340 <filename>\toto</filename> is the default
1341 directory on drive <filename>J:</filename>.
1342 </para>
1343 </listitem>
1344 <listitem>
1345 <para>
1346 On Windows NT, if <envar>=J:</envar> isn't set.
1347 </para>
1348 </listitem>
1349 <listitem>
1350 <para>
1351 On Windows NT, if <envar>=J:</envar> is set to
1352 <filename>J:\tata\titi</filename>.
1353 </para>
1354 </listitem>
1355 </itemizedlist>
1356 </para>
1357 </msgtext>
1358 </entry>
1359 </row>
1360 <row>
1361 <entry>UNC (Uniform Naming Convention) path</entry>
1362 <entry><filename>\\host\share\foo\bar.txt</filename></entry>
1363 <entry>
1364 <filename>\Global??\UNC\host\share\foo\bar.txt</filename>
1365 </entry>
1366 <entry>
1367 Simple concatenation.
1368 </entry>
1369 </row>
1370 <row>
1371 <entry>Device path</entry>
1372 <entry><filename>\\.\device</filename></entry>
1373 <entry><filename>\Global??\device</filename></entry>
1374 <entry>Simple concatenation</entry>
1375 </row>
1376 <row>
1377 <entry>Long paths</entry>
1378 <entry><filename>\\?\...</filename></entry>
1379 <entry></entry>
1380 <entry>
1381 With this prefix, paths can take up to
1382 <constant>32,767</constant> characters, instead of
1383 <constant>MAX_PATH</constant> for all the others). Once
1384 the prefix stripped, to be handled like one of the
1385 previous ones, just providing internal buffers large
1386 enough).
1387 </entry>
1388 </row>
1389 </tbody>
1390 </tgroup>
1391 </table>
1392 </para>
1393 </sect3>
1394 </sect2>
1396 <sect2>
1397 <title>Wine implementation</title>
1398 <para>
1399 We'll mainly cover in this section the way Wine opens a file (in the
1400 Unix sense) when given a Windows file name. This will include mapping
1401 the Windows path onto a Unix path (including the devices case),
1402 handling the access rights, the sharing attribute if any...
1403 </para>
1404 <sect3>
1405 <title>Mapping a Windows path into an absolute Windows path</title>
1406 <para>
1407 First of all, we described in previous section the way to convert
1408 any path in an absolute path. Wine implements all the previous algorithms
1409 in order to achieve this. Note also, that this transformation is
1410 done with information local to the process (default directory,
1411 environment variables...). We'll assume in the rest of this section
1412 that all paths have now been transformed into absolute from.
1413 </para>
1414 </sect3>
1415 <sect3>
1416 <title>Mapping a Windows (absolute) path onto a Unix path</title>
1417 <para>
1418 When Wine is requested to map a path name (in DOS form, with a drive
1419 letter, e.g. <filename>c:\foo\bar\myfile.txt</filename>), Wine
1420 converts this into the following Unix path
1421 <filename>$(WINEPREFIX)/dosdevices/c:/foo/bar/myfile.txt</filename>.
1422 The Wine configuration process is responsible for setting
1423 <filename>$(WINEPREFIX)/dosdevices/c:</filename> to be a symbolic
1424 link pointing to the directory in Unix hierarchy the user wants to
1425 expose as the <filename>C:</filename> drive in the DOS forest of
1426 drives.
1427 </para>
1428 <para>
1429 This scheme allows:
1430 <itemizedlist>
1431 <listitem>
1432 <para>
1433 a very simple algorithm to map a DOS path name into a Unix one
1434 (no need of Wine server calls)
1435 </para>
1436 </listitem>
1437 <listitem>
1438 <para>
1439 a very configurable implementation: it's very easy to change a
1440 drive mapping
1441 </para>
1442 </listitem>
1443 <listitem>
1444 <para>
1445 a rather readable configuration: no need of sophisticated
1446 tools to read a drive mapping, a <command>ls -l
1447 $(WINEPREFIX)/dosdevices</command>
1448 says it all.
1449 </para>
1450 </listitem>
1451 </itemizedlist>
1452 </para>
1453 <para>
1454 This scheme is also used to implement UNC path names. For example,
1455 Wine maps <filename>\\host\share\foo\bar\MyRemoteFile.txt</filename>
1456 into
1457 <filename>$(WINEPREFIX)/dosdevices/unc/host/share/foo/bar/MyRemoteFile.txt</filename>.
1458 It's then up to the user to decide where
1459 <filename>$(WINEPREFIX)/dosdevices/unc/host/share</filename> shall
1460 point to (or be). For example, it can either be a symbolic link to a
1461 directory inside the local machine (just for emulation purpose), or
1462 a symbolic link to the mount point of a remote disk (done through
1463 Samba or NFS), or even the real mount point. Wine will not do any
1464 checking here, nor will help in actually mounting the remote drive.
1465 </para>
1466 <para>
1467 We've seen how Wine maps a drive letter or a UNC path onto the Unix
1468 hierarchy, we now have to look on a the filename is searched within
1469 this hierarchy. The main issue is about case sensivity. Here's a
1470 reminder of the various properties for the file systems in the
1471 field.
1472 <table>
1473 <title>File systems' properties</title>
1474 <tgroup cols="4" align="left">
1475 <thead>
1476 <row>
1477 <entry>FS Name</entry>
1478 <entry>Length of elements</entry>
1479 <entry>Case sensitivity (on disk)</entry>
1480 <entry>Case sensitivity for lookup</entry>
1481 </row>
1482 </thead>
1483 <tbody>
1484 <row>
1485 <entry>FAT, FAT16 or FAT32</entry>
1486 <entry>Short name (8+3)</entry>
1487 <entry>Names are always stored in upper-case</entry>
1488 <entry>Case insensitive</entry>
1489 </row>
1490 <row>
1491 <entry>VFAT</entry>
1492 <entry>Short name (8+3) + alias on long name</entry>
1493 <entry>
1494 Short names are always stored in upper-case. Long names
1495 are stored with case preservation.
1496 </entry>
1497 <entry>Case insensitive</entry>
1498 </row>
1499 <row>
1500 <entry>NTFS</entry>
1501 <entry>Long name + alias on short name (8+3).</entry>
1502 <entry>
1503 Long names are stored with case preservation. Short names
1504 are always stored in upper-case.
1505 </entry>
1506 <entry>Case insentivite</entry>
1507 </row>
1508 <row>
1509 <entry>Linux FS (ext2fs, ext3fs, reiserfs...)</entry>
1510 <entry>Long name</entry>
1511 <entry>Case preserving</entry>
1512 <entry>Case sensitive</entry>
1513 </row>
1514 </tbody>
1515 </tgroup>
1516 </table>
1517 </para>
1518 <para>
1519 <note>
1520 <title>Case sensitivity vs. preservation</title>
1521 <para>
1522 When we say that most systems in NT are case insensitive, this
1523 has to be understood for looking up for a file, where the
1524 matches are made in a case insensitive mode. This is different
1525 from VFAT or NTFS "case preservation" mechanism, which stores
1526 the file names as they are given when creating the file, while
1527 doing case insensitive matches.
1528 </para>
1529 </note>
1530 Since most file systems used in NT are case insensitive and since
1531 most Unix file systems are case sensitive, Wine undergo a case
1532 insensitive search when it has found the Unix path is has to look
1533 for. This means, for example, that for opening the
1534 <filename>$(WINEPREFIX)/dosdevices/c:/foo/bar/myfile.txt</filename>,
1535 Wine will recursively open all directories in the path, and check,
1536 in this order, for the existence of the directory entry in the form
1537 given in the file name (ie. case sensitive), and if it's not found,
1538 in a case insensitive form. This allows to also pass, in most Win32
1539 file API also a Unix path (instead of a DOS or NT path), but we'll
1540 come back to this later. This also means that the algorithm
1541 described doesn't correctly handle the case of two files in the same
1542 directory, which names only differ on the case of the letters. This
1543 means, that if, in the same directory, two files (which names match
1544 in a case sensitive comparison), Wine will pick-up the right one if
1545 the filename given matches on of the name (in a case sensitive way),
1546 but will pickup one of the two (without defining the one it's going
1547 to pickup) if the filename given matches none of the two names in a
1548 case sensitive way (but in a case insensitive way). For example, if
1549 the two filenames are <filename>my_neat_file.txt</filename> and
1550 <filename>My_Neat_File.txt</filename>, Wine's behavior when opening
1551 <filename>MY_neat_FILE.txt</filename> is undefined.
1552 </para>
1553 <para>
1554 As Windows, at the early days, didn't support the notion of symbolic
1555 links on directories, lots of applications (and some old native
1556 DLLs) are not ready for this feature. Mainly, they imply that the
1557 directory structure is a tree, which has lots of consequences on
1558 navigating in the forest of directories (ie: there cannot be two
1559 ways for going from directory to another, there cannot be
1560 cycles...). In order to prevent some bad behavior for such
1561 applications, Wine sets up an option. By default, symbolic links on
1562 directories are not followed by Wine. There's an options to follow
1563 them (see the Wine User Guide), but this could be harmful.
1564 </para>
1565 <para>
1566 Wine considers that Unix file names <emphasis>are</emphasis> long
1567 filename. This seems a reasonable approach; this is also the
1568 approach followed by most of the Unix OSes while mounting Windows
1569 partitions (with filesystems like FAT, FAT32 or NTFS). Therefore,
1570 Wine tries to support short names the best it can. Basically, they
1571 are two options:
1572 <itemizedlist>
1573 <listitem>
1574 <para>
1575 The filesystem on which the inspected directory lies in a real
1576 Windows FS (like FAT, or FAT32, or NTFS) and the OS has
1577 support to access the short filename (for example, Linux does
1578 this on FAT, FAT32 or VFAT). In this case, Wine makes full use
1579 of this information and really mimics the Windows behavior:
1580 the short filename used for any file is the same than on
1581 Windows.
1582 </para>
1583 </listitem>
1584 <listitem>
1585 <para>
1586 If conditions listed above are not met (either, FS has no
1587 physical short name support, or OS doesn't provide the access
1588 access to the short name), Wine decides and computes on its
1589 own the short filename for a given long filename. We cannot
1590 ensure that the generated short name is the same than on
1591 Windows (because the algorithm on Windows takes into account
1592 the order of creation of files, which cannot be implemented in
1593 Wine: Wine would have to cache the short names of every
1594 directory it uses!). The short name is made up of part of the
1595 long name (first characters) and the rest with a hashed
1596 value. This has several advantages:
1597 <itemizedlist>
1598 <listitem>
1599 <para>
1600 The algorithm is rather simple and low cost.
1601 </para>
1602 </listitem>
1603 <listitem>
1604 <para>
1605 The algorithm is stateless (doesn't depend of the other
1606 files in the directory).
1607 </para>
1608 </listitem>
1609 </itemizedlist>
1610 But, it also has the drawbacks (of the advantages):
1611 <itemizedlist>
1612 <listitem>
1613 <para>
1614 The algorithm isn't the same as on Windows, which means
1615 a program cannot use short names generated on
1616 Windows. This could happen when copying an existing
1617 installed program from Windows (for example, on a dual
1618 boot machine).
1619 </para>
1620 </listitem>
1621 <listitem>
1622 <para>
1623 Two long file names can end up with the same short name
1624 (Windows handles the collision in this case, while Wine
1625 doesn't). We rely on our hash algorithm to lower at most
1626 this possibility (even if it exists).
1627 </para>
1628 </listitem>
1629 </itemizedlist>
1630 </para>
1631 </listitem>
1632 </itemizedlist>
1633 </para>
1634 <para>
1635 Wine also allows in most file API to give as a parameter a full Unix
1636 path name. This is handy when running a Wine (or Winelib) program
1637 from the command line, and one doesn't need to convert the path into
1638 the Windows form. However, Wine checks that the Unix path given can
1639 be accessed from one of the defined drives, insuring that only part
1640 of the Unix <filename>/</filename> hierarchy can be accessed.
1641 </para>
1642 <para>
1643 As a side note, as Unix doesn't widely provide a Unicode interface
1644 to the filenames, and that Windows implements filenames as Unicode
1645 strings (even on the physical layer with NTFS, the FATs variant are
1646 ANSI), we need to properly map between the two. At startup, Wine
1647 defines what's called the Unix Code Page, that's is the code page
1648 the Unix kernel uses as a reference for the strings. Then Wine uses
1649 this code page for all the mappings it has to do between a Unicode
1650 path (on the Windows side) and a Ansi path to be used in a Unix path
1651 API. Note, that this will work as long as a disk isn't mounted with
1652 a different code page than the one the kernel uses as a default.
1653 </para>
1654 <para>
1655 We describe below how Windows devices are mapped to Unix devices.
1656 Before that, let's finish the pure file round-up with some basic
1657 operations.
1658 </para>
1659 </sect3>
1660 <sect3>
1661 <title>Access rights and file attributes</title>
1662 <para>
1663 Now that we have looked how Wine converts a Windows pathname into a
1664 Unix one, we need to cover the various meta-data attached to a file
1665 or a directory.
1666 </para>
1667 <para>
1668 In Windows, access rights are simplistic: a file can be read-only or
1669 read-write. Wine sets the read-only flag if the file doesn't have
1670 the Unix user-write flag set. As a matter of fact, there's no way
1671 Wine can return that a file cannot be read (that doesn't exist under
1672 Windows). The file will be seen, but trying to open it will return
1673 an error. The Unix exec-flag is never reported. Wine doesn't use
1674 this information to allow/forbid running a new process (as Unix does
1675 with the exec-flag). Last but not least: hidden files. This exists
1676 on Windows but not really on Unix! To be exact, in Windows, the
1677 hidden flag is a metadata associated to any file or directoy; in
1678 Unix, it's a convention based on the syntax of the file name
1679 (whether it starts with a '.' or not). Wine implements two behaviors
1680 (chosen by configuration). This impacts file names and directory
1681 names starting by a '.'. In first mode
1682 (<option>ShowDotFile</option> is <constant>FALSE</constant>), every
1683 file or directory starting by '.' is returned with the hidden flag
1684 turned on. This is the natural behavior on Unix (for
1685 <command>ls</command> or even file explorer). In the second mode
1686 (<option>ShowDotFile</option> is <constant>TRUE</constant>), Wine
1687 never sets the hidden flag, hence every file will be seen.
1688 </para>
1689 <para>
1690 Last but not least, before opening a file, Windows makes use of
1691 sharing attributes in order to check whether the file can be opened;
1692 for example, a process, being the first in the system to open a
1693 given file, could forbid, while it maintains the file opened, that
1694 another process opens it for write access, whereas open for read
1695 access would be granted. This is fully supported in Wine by moving
1696 all those checks in the Wine server for a global view on the system.
1697 Note also that what's moved in the Wine server is the check, when
1698 the file is opened, to implement the Windows sharing semantics.
1699 Further operation on the file (like reading and writing) will not
1700 require heavy support from the server.
1701 </para>
1702 <para>
1703 The other good reason for putting the code for actually opening a
1704 file in the server is that an opened files in Windows is managed
1705 through a handle, and handles can only be created in Wine server!
1706 </para>
1707 <para>
1708 Just a note about attributes on directories: while we can easily map
1709 the meaning of Windows' <constant>FILE_ATTRIBUTE_READONLY</constant>
1710 on a file, we cannot do it for a directory. Windows' semantic (when
1711 this flag is set) means do not delete the directory, while the
1712 <constant>w</constant> attribute in Unix means don't write nor
1713 delete it. Therefore, Wine uses an asymetric mapping here: if the
1714 directory (in Unix) isn't writable, then Wine reports the
1715 <constant>FILE_ATTRIBUTE_READONLY</constant> attribute; on the other
1716 way around, when asked to set a directory with
1717 <constant>FILE_ATTRIBUTE_READONLY</constant> attribute, Wine simply
1718 does nothing.
1719 </para>
1720 </sect3>
1721 <sect3>
1722 <title>Operations on file</title>
1723 <sect4>
1724 <title>Reading and writing</title>
1725 <para>
1726 Reading and writing are the basic operations on files. Wine of
1727 course implements this, and bases the implementation on client
1728 side calls to Unix equivalents (like <function>read()</function>
1729 or <function>write()</function>). Note, that the Wine server is
1730 involved in any read or write operation, as Wine needs to
1731 transform the Windows-handle to the file into a Unix file
1732 descriptor it can pass to any Unix file function.
1733 </para>
1734 </sect4>
1735 <sect4>
1736 <title>Getting a Unix fd</title>
1737 <para>
1738 This is major operation in any file related operation. Basically,
1739 each file opened (at the Windows level), is first opened in the
1740 Wine server, where the fd is stored. Then, Wine (on client side)
1741 uses <function>recvmsg()</function> to pass the fd from the wine
1742 server process to the client process. Since this operation could
1743 be lengthy, Wine implement some kind of cache mechanism to send it
1744 only once, but getting a fd from a handle on a file (or any other
1745 Unix object which can be manipulated through a file descriptor)
1746 still requires a round trip to the Wine server.
1747 </para>
1748 </sect4>
1749 <sect4>
1750 <title>Locking</title>
1751 <para>
1752 Windows provides file locking capabilities. When a lock is set
1753 (and a lock can be set on any contiguous range in a file), it
1754 controls how other processes in the system will have access to the
1755 range in the file. Since locking range on a file are defined on a
1756 system wide manner, its implementation resides in
1757 <command>wineserver</command>. It tries to make use Unix file
1758 locking (if the underlying OS and the mounted disk where the file
1759 sits support this feature) with <function>fcntl()</function> and
1760 the <constant>F_SETLK</constant> command. If this isn't
1761 supported, then <command>wineserver</command> just pretends it
1762 works.
1763 </para>
1764 </sect4>
1765 <sect4>
1766 <title>I/O control</title>
1767 <para>
1768 There's no need (so far) to implement support (for files and
1769 directories) for <function>DeviceIoControl()</function>, even if
1770 this is supported by Windows, but for very specific needs
1771 (like compression management, or file system related information).
1772 This isn't the case for devices (including disks), but we'll cover
1773 this in the hereafter section related to devices.
1774 </para>
1775 </sect4>
1776 <sect4>
1777 <title>Buffering</title>
1778 <para>
1779 Wine doesn't do any buffering on file accesses but rely on the
1780 underlying Unix kernel for that (when possible). This scheme is
1781 needed because it's easier to implement multiple accesses on the
1782 same file at the kernel level, rather than at Wine levels. Doing
1783 lots of small reads on the same file can turn into a performance
1784 hog, because each read operation needs a round trip to the server
1785 in order to get a file descriptor (see above).
1786 </para>
1787 </sect4>
1788 <sect4>
1789 <title>Overlapped I/O</title>
1790 <para>
1791 Windows introduced the notion of overlapped I/O. Basically, it
1792 just means that an I/O operation (think read / write to start
1793 with) will not wait until it's completed, but rather return to the
1794 caller as soon as possible, and let the caller handle the wait
1795 operation and determine when the data is ready (for a read
1796 operation) or has been sent (for a write operation). Note that the
1797 overlapped operation is linked to a specific thread.
1798 </para>
1799 <para>
1800 There are several interests to this: a server can handle several
1801 clients without requiring multi-threading techniques; you can
1802 handle an event driven model more easily (ie how to kill properly
1803 a server while waiting in the lengthy <function>read()</function>
1804 operation).
1805 </para>
1806 <para>
1807 Note that Microsoft's support for this feature evolved along the
1808 various versions of Windows. For example, Windows 95 or 98 only
1809 supports overlapped I/O for serial and parallel ports, while NT
1810 supports also files, disks, sockets, pipes, or mailslots.
1811 </para>
1812 <para>
1813 Wine implements overlapped I/O operations. This is mainly done by
1814 queueing in the server a request that will be triggered when
1815 something the current state changes (like data available for a
1816 read operation). This readiness is signaled to the calling
1817 processing by queueing a specific APC, which will be called within
1818 the next waiting operation the thread will have. This specific
1819 APC will then do the hard work of the I/O operation. This scheme
1820 allows to put in place a wait mechanism, to attach a routine to be
1821 called (on the thread context) when the state changes, and to be
1822 done is a rather transparent manner (embedded any the generic wait
1823 operation). However, it isn't 100% perfect. As the heavy
1824 operations are done in the context of the calling threads, if
1825 those operations are lengthy, there will be an impact on the
1826 calling thread, especially its latency. In order to provide an
1827 effective support for this overlapped I/O operations, we would
1828 need to rely on Unix kernel features (AIO is a good example).
1829 </para>
1830 </sect4>
1831 </sect3>
1832 <sect3>
1833 <title>Devices & volume management</title>
1834 <para>
1835 We've covered so far the ways file names are mapped into Unix
1836 paths. There's still need to cover it for devices. As a regular
1837 file, devices are manipulated in Windows with both read / write
1838 operations, but also control mechanisms (speed or parity of a serial
1839 line; volume name of a hard disk...). Since, this is also supported
1840 in Linux, there's also a need to open (in a Unix sense) a device
1841 when given a Windows device name. This section applies to DOS device
1842 names, which are seen in NT as nicknames to other devices.
1843 </para>
1844 <para>
1845 Firstly, Wine implements the Win32 to NT mapping as described above,
1846 hence every device path (in NT sense) is of the following form:
1847 <filename>/??/devicename</filename> (or
1848 <filename>/DosDevices/devicename</filename>). As Windows device
1849 names are case insensitive, Wine also converts them to lower case
1850 before any operation. Then, the first operation Wine tries is to
1851 check whether
1852 <filename>$(WINEPREFIX)/dosdevices/devicename</filename> exists. If
1853 so, it's used as the final Unix path for the device. The
1854 configuration process is in charge of creating for example, a
1855 symbolic link between
1856 <filename>$(WINEPREFIX)/dosdevices/PhysicalDrive0</filename> and
1857 <filename>/dev/hda0</filename>. If such a link cannot be found, and
1858 the device name looks like a DOS disk name (like
1859 <filename>C:</filename>), Wine first tries to get the Unix device
1860 from the path <filename>$(WINEPREFIX)/dosdevices/c:</filename>
1861 (i.e. the device which is mounted on the target of the symbol link);
1862 if this doesn't give a Unix device, Wine tries whether
1863 <filename>$(WINEPREFIX)/dosdevices/c::</filename> exists. If so,
1864 it's assumed to be a link to the actual Unix device. For example,
1865 for a CD Rom, <filename>$(WINEPREFIX)/dosdevices/e::</filename>
1866 would be a symbolic link to <filename>/dev/cdrom</filename>. If
1867 this doesn't exist (we're still handling the a device name of the
1868 <filename>C:</filename> form), Wine tries to get the Unix device
1869 from the system information (<filename>/etc/mtab</filename> and
1870 <filename>/etc/fstab</filename> on Linux). We cannot apply this
1871 method in all the cases, because we have no insurance that the
1872 directory can actually be found. One could have, for example, a CD
1873 Rom which he/she want only to use as audio CD player (ie never
1874 mounted), thus not having any information of the device itself. If
1875 all of this doesn't work either, some basic operations are checked:
1876 if the devicename is <filename>NUL</filename>, then
1877 <filename>/dev/null</filename> is returned. If the device name is a
1878 default serial name (<filename>COM1</filename> up to
1879 <filename>COM9</filename>) (resp. printer name
1880 <filename>LPT1</filename> up to <filename>LPT9</filename>), then
1881 Wine tries to open the Nth serial (resp. printer) in the system.
1882 Otherwise, some basic old DOS name support is done
1883 <filename>AUX</filename> is transformed into
1884 <filename>COM1</filename> and <filename>PRN</filename> into
1885 <filename>LPT1</filename>), and the whole process is retried with
1886 those new names.
1887 </para>
1888 <para>
1889 To sum up:
1890 <table>
1891 <title>
1892 Mapping of Windows device names into Unix device names
1893 </title>
1894 <tgroup cols="3" align="left">
1895 <thead>
1896 <row>
1897 <entry>Windows device name</entry>
1898 <entry>NT device name</entry>
1899 <entry>Mapping to Unix device name</entry>
1900 </row>
1901 </thead>
1902 <tbody>
1903 <row>
1904 <entry><filename>&lt;any_path&gt;AUX</filename></entry>
1905 <entry<filename>>\Global??\AUX</filename></entry>
1906 <entry>
1907 Treated as an alias to <filename>COM1</filename>
1908 </entry>
1909 </row>
1910 <row>
1911 <entry><filename>&lt;any_path&gt;PRN</filename></entry>
1912 <entry><filename>\Global??\PRN</filename></entry>
1913 <entry>Treated as an alias to <filename>LPT1</filename></entry>
1914 </row>
1915 <row>
1916 <entry><filename>&lt;any_path&gt;COM1</filename></entry>
1917 <entry><filename>\Global??\COM1</filename></entry>
1918 <entry>
1919 <filename>$(WINEPREFIX)/dosdevices/com1</filename>
1920 (if the symbol link exists) or the Nth serial
1921 line in the system (on Linux,
1922 <filename>/dev/ttyS0</filename>).
1923 </entry>
1924 </row>
1925 <row>
1926 <entry><filename>&lt;any_path&gt;LPT1</filename></entry>
1927 <entry><filename>\Global??\LPT1</filename></entry>
1928 <entry>
1929 <filename>$(WINEPREFIX)/dosdevices/lpt1</filename>
1930 (if the symbol link exists) or the Nth printer
1931 in the system (on Linux,
1932 <filename>/dev/lp0</filename>).
1933 </entry>
1934 </row>
1935 <row>
1936 <entry><filename>&lt;any_path&gt;NUL</filename></entry>
1937 <entry><filename>\Global??\NUL</filename></entry>
1938 <entry><filename>/dev/null</filename></entry>
1939 </row>
1940 <row>
1941 <entry><filename>\\.\E:</filename></entry>
1942 <entry><filename>\Global??\E:</filename></entry>
1943 <entry>
1944 <filename>$(WINEPREFIX)/dosdevices/e::</filename> (if the
1945 symbolic link exists) or guessing the device from
1946 <filename>/etc/mtab</filename> or
1947 <filename>/etc/fstab</filename>.
1948 </entry>
1949 </row>
1950 <row>
1951 <entry><filename>\\.\&lt;device_name&gt;</filename></entry>
1952 <entry>
1953 <filename>\Global??\&lt;device_name&gt;</filename>
1954 </entry>
1955 <entry>
1956 <filename>$(WINEPREFIX)/dosdevices/&lt;device_name&gt;</filename>
1957 (if the symbol link exists).
1958 </entry>
1959 </row>
1960 </tbody>
1961 </tgroup>
1962 </table>
1963 </para>
1964 <para>
1965 Now that we know which Unix device to open for a given Windows
1966 device, let's cover the operation on it. Those operations can either
1967 be read / write, io control (and even others).
1968 </para>
1969 <para>
1970 Read and write operations are supported on Real disks & CDROM
1971 devices, under several conditions:
1972 <itemizedlist>
1973 <listitem>
1974 <para>
1975 Foremost, as the <function>ReadFile()</function> and
1976 <function>WriteFile()</function> calls are mapped onto the
1977 Unix <function>read()</function> and
1978 <function>write()</function> calls, the user (from the Unix
1979 perspective of the one running the Wine executable) must have
1980 read (resp. write) access to the device. It wouldn't be wise
1981 to let a user write directly to a hard disk!!!
1982 </para>
1983 </listitem>
1984 <listitem>
1985 <para>
1986 Blocks' size for read and write but be of the size of a
1987 physical block (generally 512 for a hard disk, depends on the
1988 type of CD used), and offsets must also be a multiple of the
1989 block size.
1990 </para>
1991 </listitem>
1992 </itemizedlist>
1993 </para>
1994 <para>
1995 Wine also reads (if the first condition above about access rights is
1996 met) the volume information from a hard disk or a CD ROM to be
1997 displayed to a user.
1998 </para>
1999 <!--
2000 <para>
2001 Handling of old DOS devices (<filename>COMx</filename>,
2002 <filename>LPTx</filename>, <filename>NUL</filename>...)
2003 </para>
2005 <para>
2006 Wine also recognizes VxD as devices. But those VxD must be the
2007 Wine builtin ones (Wine will never allow to load native VxD). Those
2008 are configured with symbolic links in the
2009 <filename>$(WINEPREFIX)/dosdevices/</filename> directory, and point
2010 to the actual builtin DLL. This DLL exports a single entry point,
2011 that Wine will use when a call to
2012 <function>DeviceIoControl</function> is made, with a handle opened
2013 to this VxD. This allows to provide some kind of compatibility for
2014 old Win9x apps, still talking directly to VxD. This is no longer
2015 supported on Windows NT, newest programs are less likely to make use
2016 of this feature, so we don't expect lots of development in this
2017 area, even though the framework is there and working. Note also that
2018 Wine doesn't provide support for native VxDs (as a game, report how
2019 many times this information is written in the documentation; as an
2020 advanced exercise, find how many more occurrences we need in order to
2021 stop questions whether it's possible or not).
2022 </para>
2023 </sect3>
2024 </sect2>
2025 </sect1>
2026 <sect1 id="ntdll">
2027 <title><filename>NTDLL</filename> module</title>
2028 <para>
2029 <filename>NTDLL</filename> provides most of the services you'd expect
2030 from a kernel. In lots of cases, <filename>KERNEL32</filename> APIs are
2031 just wrappers to <filename>NTDLL</filename> APIs. There are however,
2032 some difference in the APIs (the <filename>NTDLL</filename> ones have
2033 quite often a bit wider semantics than their
2034 <filename>KERNEL32</filename> counterparts). All the detailed functions
2035 we've described since the beginning of this chapter are in fact
2036 implemented in <filename>NTDLL</filename>, plus a great numbers of
2037 others we haven's written about yet.
2038 </para>
2039 </sect1>
2041 <sect1>
2042 <title><filename>KERNEL32</filename> Module</title>
2044 <para>
2045 As already explained, <filename>KERNEL32</filename> maps quite a few of
2046 its APIs to <filename>NTDLL</filename>. There are however a couple of
2047 things which are handled directly in
2048 <filename>KERNEL32</filename>. Let's cover a few of them...
2049 </para>
2050 <sect2 id="consoles">
2051 <title>Console</title>
2052 <sect3>
2053 <title>NT implementation</title>
2054 <para>
2055 Windows implements console solely in the Win32 subsystem. Under NT,
2056 the real implementation uses a dedicated subsystem
2057 <filename>csrss.exe</filename> Client/Server Run-time SubSystem)
2058 which is in charge, amont other things, of animating the consoles.
2059 Animating includes for example handling several processes on the
2060 same console (write operations must be atomic, but also a character
2061 keyed on the console must be read by a single process), or sending
2062 some information back to the processes (changing the size or
2063 attributes of the console, closing the console). Windows NT uses a
2064 dedicated (RPC based) protocol between each process being attached
2065 to a console and the <command>csrss.exe</command> subsystem, which
2066 is in charge of the UI of every console in the system.
2067 </para>
2068 </sect3>
2069 <sect3>
2070 <title>Wine implementation</title>
2071 <para>
2072 Wine tries to integrate as much as possible into the Unix consoles,
2073 but the overall situation isn't perfect yet. Basically, Wine
2074 implements three kinds of consoles:
2075 <itemizedlist>
2076 <listitem>
2077 <para>
2078 the first one is a direct mapping of the Unix console into the
2079 Windows environment. From the windows program point of view,
2080 it won't run in a Windows console, but it will see its
2081 standard input and output streams redirected to files; thoses
2082 files are hooked into the Unix console's output and input
2083 streams respectively. This is handy for running programs from
2084 a Unix command line (and use the result of the program as it
2085 was a Unix programs), but it lacks all the semantics of the
2086 Windows consoles.
2087 </para>
2088 </listitem>
2089 <listitem>
2090 <para>
2091 the second and third ones are closer to the NT scheme, albeit
2092 different from what NT does. The <command>wineserver</command>
2093 plays the role of the <filename>csrss.exe</filename> subsystem
2094 (all requests are sent to it), and are then dispatched to a
2095 dedicated wine process, called (surprise!)
2096 <command>wineconsole</command> which manages the UI of the
2097 console. There is a running instance of
2098 <command>wineconsole</command> for every console in the
2099 system. Two flavors of this scheme are actually implemented:
2100 they vary on the backend for the
2101 <command>wineconsole</command>. The first one, dubbed
2102 <constant>user</constant>, creates a real GUI window
2103 (hence the USER name) and renders the console in this window.
2104 The second one uses the <filename>(n)curses</filename> library
2105 to take full control of an existing Unix console; of course,
2106 interaction with other Unix programs will not be as smooth as
2107 the first solution.
2108 </para>
2109 </listitem>
2110 </itemizedlist>
2111 </para>
2112 <para>
2113 The following table describes the main implementation differences
2114 between the three approaches.
2115 <table>
2116 <title>Function consoles implementation comparison</title>
2117 <tgroup cols="4" align="left">
2118 <thead>
2119 <row>
2120 <entry>Function</entry>
2121 <entry>Bare streams</entry>
2122 <entry>
2123 <command>Wineconsole</command> &amp; user backend
2124 </entry>
2125 <entry>
2126 <command>Wineconsole</command> &amp; curses backend
2127 </entry>
2128 </row>
2129 </thead>
2130 <tbody>
2131 <row>
2132 <entry>
2133 Console as a Win32 Object (and associated handles)
2134 </entry>
2135 <entry>
2136 No specific Win32 object is used in this case. The
2137 handles manipulated for the standard Win32 streams are in
2138 fact "bare handles" to their corresponding Unix streams.
2139 The mode manipulation functions
2140 (<function>GetConsoleMode()</function> /
2141 <function>SetConsoleMode()</function>) are not supported.
2142 </entry>
2143 <entry>
2144 Implemented in server, and a specific Winelib program
2145 (<command>wineconsole</command>) is in charge of the
2146 rendering and user input. The mode manipulation functions
2147 behave as expected.
2148 </entry>
2149 <entry>
2150 Implemented in server, and a specific Winelib program
2151 (<command>wineconsole</command>) is in charge of the
2152 rendering and user input. The mode manipulation functions
2153 behave as expected.
2154 </entry>
2155 </row>
2156 <row>
2157 <entry>
2158 Inheritance (including handling in
2159 <function>CreateProcess()</function> of
2160 <constant>CREATE_DETACHED</constant>,
2161 <constant>CREATE_NEW_CONSOLE</constant> flags).
2162 </entry>
2163 <entry>
2164 Not supported. Every process child of a process will
2165 inherit the Unix streams, so will also inherit the Win32
2166 standard streams.
2167 </entry>
2168 <entry>
2169 Fully supported (each new console creation will be handled
2170 by the creation of a new <filename>USER32</filename> window)
2171 </entry>
2172 <entry>
2173 Fully supported, except for the creation of a new console,
2174 which will be rendered on the same Unix terminal as the
2175 previous one, leading to unpredictable results.
2176 </entry>
2177 </row>
2178 <row>
2179 <entry>
2180 <function>ReadFile()</function> /
2181 <function>WriteFile()</function> operations
2182 </entry>
2183 <entry>Fully supported</entry>
2184 <entry>Fully supported</entry>
2185 <entry>Fully supported</entry>
2186 </row>
2187 <row>
2188 <entry>
2189 Screen-buffer manipulation (creation, deletion, resizing...)
2190 </entry>
2191 <entry>Not supported</entry>
2192 <entry>Fully supported</entry>
2193 <entry>
2194 Partly supported (this won't work too well as we don't
2195 control (so far) the size of underlying Unix terminal
2196 </entry>
2197 </row>
2198 <row>
2199 <entry>
2200 APIs for reading/writing screen-buffer content, cursor position
2201 </entry>
2202 <entry>Not supported</entry>
2203 <entry>Fully supported</entry>
2204 <entry>Fully supported</entry>
2205 </row>
2206 <row>
2207 <entry>APIs for manipulating the rendering window size</entry>
2208 <entry>Not supported</entry>
2209 <entry>Fully supported</entry>
2210 <entry>
2211 Partly supported (this won't work too well as we don't
2212 control (so far) the size of underlying Unix terminal
2213 </entry>
2214 </row>
2215 <row>
2216 <entry>
2217 Signaling (in particular, Ctrl-C handling)
2218 </entry>
2219 <entry>
2220 Nothing is done, which means that Ctrl-C will generate (as
2221 usual) a <constant>SIGINT</constant> which will terminate
2222 the program.
2223 </entry>
2224 <entry>
2225 Partly supported (Ctrl-C behaves as expected, however the
2226 other Win32 CUI signaling isn't properly implemented).
2227 </entry>
2228 <entry>
2229 Partly supported (Ctrl-C behaves as expected, however the
2230 other Win32 CUI signaling isn't properly implemented).
2231 </entry>
2232 </row>
2233 </tbody>
2234 </tgroup>
2235 </table>
2236 </para>
2237 <para>
2238 The Win32 objects behind a console can be created in several
2239 occasions:
2240 <itemizedlist>
2241 <listitem>
2242 <para>
2243 When the program is started from
2244 <command>wineconsole</command>, a new console object is
2245 created and will be used (inherited) by the process launched
2246 from <command>wineconsole</command>.
2247 </para>
2248 </listitem>
2249 <listitem>
2250 <para>
2251 When a program, which isn't attached to a console, calls
2252 <function>AllocConsole()</function>, Wine then launches
2253 <command>wineconsole</command>, and attaches the current
2254 program to this console. In this mode, the
2255 <filename>USER32</filename> mode is always selected as Wine
2256 cannot tell the current state of the Unix console.
2257 </para>
2258 </listitem>
2259 </itemizedlist>
2260 </para>
2261 <para>
2262 Please also note, that starting a child process with the
2263 <constant>CREATE_NEW_CONSOLE</constant> flag, will end-up calling
2264 <function>AllocConsole()</function> in the child process, hence
2265 creating a <command>wineconsole</command> with the
2266 <filename>USER32</filename> backend.
2267 </para>
2268 <para>
2269 Another interesting point to note is that Windows implements handles
2270 to console objects (input and screen buffers) only in the
2271 <filename>KERNEL32</filename> DLL, and those are not sent nor seen
2272 from the <filename>NTDLL</filename> level, albeit, for example,
2273 console are waitable on input. How is this possible? Well, Windows
2274 NT is a bit tricky here. Regular handles have an interesting
2275 property: their integral value is always a multiple of four (they
2276 are likely to be offsets from the beginning of a table). Console
2277 handles, on the other hand, are not multiple of four, but have the
2278 two lower bit set (being a multiple of four means having the two
2279 lower bits reset). When <filename>KERNEL32</filename> sees a handle
2280 with the two lower bits set, it then knows it's a console handle and
2281 takes appropriate decisions. For example, in the various
2282 <function>kernel32!WaitFor*()</function> functions, it transforms
2283 any console handle (input and <emphasis>output</emphasis> -
2284 strangely enough handles to console's screen buffers are waitable)
2285 into a dedicated wait event for the targetted console. There's an
2286 (undocumented) <filename>KERNEL32</filename> function
2287 <function>GetConsoleInputWaitHandle()</function> which returns the
2288 handle to this event in case you need it. Another interesting
2289 handling of those console's handles is in
2290 <function>ReadFile()</function>
2291 (resp. <function>WriteFile()</function>), which behavior, for
2292 console's handles, is transferred to
2293 <function>ReadConsole()</function> (resp.
2294 <function>WriteConsole()</function>). Note that's always the ANSI
2295 version of
2296 <function>ReadConsole()</function> /
2297 <function>WriteConsole()</function>
2298 which is called, hence using the default console's code page. There
2299 are some other spots affected, but you can look in
2300 <filename>dlls/kernel</filename> to find them all. All of this is
2301 implemented in Wine.
2302 </para>
2303 <para>
2304 Wine also implements the same layout of the registry for storing the
2305 preferences of the console as Windows does. Those settings can
2306 either be defined globally, or on a per process name basis.
2307 <command>wineconsole</command> provides the choice to the user to
2308 pick you which registry part (global, current running program) it
2309 wishes to modify the settings for.
2310 <table>
2311 <title>Console registry settings</title>
2312 <tgroup cols="3" align="left">
2313 <thead>
2314 <row>
2315 <entry>Name</entry>
2316 <entry>Default value</entry>
2317 <entry>Purpose</entry>
2318 </row>
2319 </thead>
2320 <tbody>
2321 <row>
2322 <entry>CursorSize</entry>
2323 <entry>25</entry>
2324 <entry>
2325 Percentage of cell height to which the cursor extents
2326 </entry>
2327 </row>
2328 <row>
2329 <entry>CursorVisible</entry>
2330 <entry>1</entry>
2331 <entry>Whether the cursor is visible or not</entry>
2332 </row>
2333 <row>
2334 <entry>EditionMode</entry>
2335 <entry>0</entry>
2336 <entry>
2337 The way the edition takes place in the console: 0 is
2338 insertion mode, 1 is overwrite mode.
2339 </entry>
2340 </row>
2341 <row>
2342 <entry>ExitOnDie</entry>
2343 <entry>1</entry>
2344 <entry>
2345 Whether the console should close itself when last running
2346 program attached to it dies
2347 </entry>
2348 </row>
2349 <row>
2350 <entry>FaceName</entry>
2351 <entry>No default</entry>
2352 <entry>
2353 Name of the font to be used for display. When none is
2354 given, <command>wineconsole</command> tries its best to
2355 pick up a decent font
2356 </entry>
2357 </row>
2358 <row>
2359 <entry>FontSize</entry>
2360 <entry>0x0C08</entry>
2361 <entry>
2362 The high word in the font's cell height, and the low word
2363 is the font cell's width. The default value is 12 pixels
2364 in height and 8 pixels in width.
2365 </entry>
2366 </row>
2367 <row>
2368 <entry>FontWeight</entry>
2369 <entry>0</entry>
2370 <entry>
2371 Weigth of the font. If none is given (or 0)
2372 <command>wineconsole</command> picks up a decent font size
2373 </entry>
2374 </row>
2375 <row>
2376 <entry>HistoryBufferSize</entry>
2377 <entry>50</entry>
2378 <entry>
2379 Number of entries in history buffer (not actually used)
2380 </entry>
2381 </row>
2382 <row>
2383 <entry>HistoryNoDup</entry>
2384 <entry>0</entry>
2385 <entry>
2386 Whether the history should store twice the same entry
2387 </entry>
2388 </row>
2389 <row>
2390 <entry>MenuMask</entry>
2391 <entry>0</entry>
2392 <entry>
2393 This mask only exists for Wine console handling. It
2394 allows to know which combination of extra keys are need to
2395 open the configuration window on right click. The mask
2396 can include <constant>MK_CONTROL</constant> or
2397 <constant>MK_SHIFT</constant> bits. This can be needed
2398 when programs actually need the right click to be passed
2399 to them instead of being intercepted by
2400 <command>wineconsole</command>.
2401 </entry>
2402 </row>
2403 <row>
2404 <entry>QuickEdit</entry>
2405 <entry>0</entry>
2406 <entry>
2407 If null, mouse events are sent to the application. If non
2408 null, mouse events are used to select text on the window.
2409 This setting must really be set on a application per
2410 application basis, because it deals with the fact the CUI
2411 application will use or not the mouse events.
2412 </entry>
2413 </row>
2414 <row>
2415 <entry>ScreenBufferSize</entry>
2416 <entry>0x1950</entry>
2417 <entry>
2418 The high word is the number of font cells in the height of
2419 the screen buffer, while the low word is the number of
2420 font cells in the width of the screen buffer.
2421 </entry>
2422 </row>
2423 <row>
2424 <entry>ScreenColors</entry>
2425 <entry>0x000F</entry>
2426 <entry>
2427 Default color attribute for the screen buffer (low char is
2428 the foreground color, and high char is the background
2429 color)
2430 </entry>
2431 </row>
2432 <row>
2433 <entry>WindowSize</entry>
2434 <entry>0x1950</entry>
2435 <entry>
2436 The high word is the number of font cells in the height of
2437 the window, while the low word is the number of font cells
2438 in the width of the window. This window is the visible
2439 part of the screen buffer: this implies that a screen
2440 buffer must always be bigger than its window, and that the
2441 screen buffer can be scrolled so that every cell of the
2442 screen buffer can be seen in the window.
2443 </entry>
2444 </row>
2445 </tbody>
2446 </tgroup>
2447 </table>
2448 </para>
2449 </sect3>
2450 </sect2>
2451 <sect2>
2452 <title>Win16 processes support</title>
2453 <sect3>
2454 <title>Starting a NE (Win16) process</title>
2455 <para>
2456 Wine is also able to run 16 bit processes, but this feature is only
2457 supported on Intel IA-32 architectures.
2458 </para>
2459 <para>
2460 When Wine is requested to run a NE (Win 16 process), it will in fact
2461 hand over the execution of it to a specific executable
2462 <command>winevdm</command>. VDM stands for Virtual DOS
2463 Machine. This <command>winevdm</command> is a Winelib application,
2464 but will in fact set up the correct 16 bit environment to run the
2465 executable. We will get back later on in details to what this means.
2466 </para>
2467 <para>
2468 Any new 16 bit process created by this executable (or its children)
2469 will run into the same <command>winevdm</command> instance. Among
2470 one instance, several functionalities will be provided to those 16
2471 bit processes, including the cooperative multitasking, sharing the
2472 same address space, managing the selectors for the 16 bit segments
2473 needed for code, data and stack.
2474 </para>
2475 <para>
2476 Note that several <command>winevdm</command> instances can run in
2477 the same Wine session, but the functionalities described above are
2478 only shared among a given instance, not among all the
2479 instances. <command>winevdm</command> is built as Winelib
2480 application, and hence has access to any facility a 32 bit
2481 application has.
2482 </para>
2483 <para>
2484 Each Win16 application is implemented in
2485 <command>winevdm</command> as a Win32
2486 thread. <command>winevdm</command> then implements its own
2487 scheduling facilities (in fact, the code for this feature is in the
2488 <filename>krnl386.exe</filename> DLL). Since the required Win16
2489 scheduling is non pre-emptive, this doesn't require any underlying
2490 OS kernel support.
2491 </para>
2492 </sect3>
2493 <sect3>
2494 <title>SysLevels</title>
2495 <para>
2496 SysLevels are an undocumented Windows-internal thread-safety system
2497 dedicated to 16 bit applications (or 32 bit applications that call -
2498 directly or indirectly - 16 bit code). They are basically critical
2499 sections which must be taken in a particular order. The mechanism is
2500 generic but there are always three syslevels:
2501 <itemizedlist>
2502 <listitem>
2503 <para>level 1 is the Win16 mutex,</para>
2504 </listitem>
2505 <listitem>
2506 <para>level 2 is the <filename>USER</filename> mutex,</para>
2507 </listitem>
2508 <listitem>
2509 <para>level 3 is the <filename>GDI</filename> mutex.</para>
2510 </listitem>
2511 </itemizedlist>
2512 </para>
2514 <para>
2515 When entering a syslevel, the code (in
2516 <filename>dlls/kernel/syslevel.c</filename>) will check that a
2517 higher syslevel is not already held and produce an error if so. This
2518 is because it's not legal to enter level 2 while holding level 3 -
2519 first, you must leave level 3.
2520 </para>
2522 <para>
2523 Throughout the code you may see calls to
2524 <function>_ConfirmSysLevel()</function> and
2525 <function>_CheckNotSysLevel()</function>. These functions are
2526 essentially assertions about the syslevel states and can be used to
2527 check that the rules have not been accidentally violated. In
2528 particular, <function>_CheckNotSysLevel()</function> will break
2529 probably into the debugger) if the check fails. If this happens the
2530 solution is to get a backtrace and find out, by reading the source
2531 of the wine functions called along the way, how Wine got into the
2532 invalid state.
2533 </para>
2534 </sect3>
2535 <sect3>
2536 <title>Memory management</title>
2537 <para>
2538 Every Win16 address is expressed in the form of selector:offset. The
2539 selector is an entry in the LDT, but a 16 bit entry, limiting each
2540 offset to 64 KB. Hence, the maximum available memory to a Win16
2541 process is 512 MB. Note, that the processor runs in protected mode,
2542 but using 16 bit selectors.
2543 </para>
2544 <para>
2545 Windows, for a 16 bit process, defines a few selectors to access the
2546 "real" memory (the one provided) by DOS. Basically, Wine also
2547 provides this area of memory.
2548 </para>
2549 </sect3>
2550 </sect2>
2551 <sect2>
2552 <title>DOS processes support</title>
2553 <para>
2554 The behaviour we just described also applies to DOS executables, which
2555 are handled the same way by <command>winevdm</command>. This is only
2556 supported on Intel IA-32 architectures.
2557 </para>
2558 <para>
2559 Wine implements also most of the DOS support in a Wine specific DLL
2560 (<filename>winedos</filename>). This DLL is called under certain
2561 conditions, like:
2562 <itemizedlist>
2563 <listitem>
2564 <para>
2565 In <command>winevdm</command>, when trying to launch a DOS
2566 application (<filename>.EXE</filename> or
2567 <filename>.COM</filename>, <filename>.PIF</filename>).
2568 </para>
2569 </listitem>
2570 <listitem>
2571 <para>
2572 In <filename>kernel32</filename>, when an attempt is made in the
2573 binary code to call some DOS or BIOS interrupts (like Int 21h
2574 for example).
2575 </para>
2576 </listitem>
2577 </itemizedlist>
2578 </para>
2579 <para>
2580 When <command>winevdm</command> runs a DOS program, this one runs in
2581 real mode (in fact in V86 mode from the IA-32 point of view).
2582 </para>
2583 <para>
2584 Wine also supports part of the DPMI (DOS Protected Mode Interface).
2585 </para>
2586 <para>
2587 Wine, when running a DOS programs, needs to map the 1 MB of virtual
2588 memory to the real memory (as seen by the DOS program). When this is
2589 not possible (like when someone else is already using this area), the
2590 DOS support is not possible. Not also that by doing so, access to
2591 linear address 0 is enabled (as it's also real mode address 0 which is
2592 valid). Hence, NULL pointer derefence faults are no longer catched.
2593 </para>
2594 </sect2>
2595 </sect1>
2597 </chapter>
2599 <!-- Keep this comment at the end of the file
2600 Local variables:
2601 mode: sgml
2602 sgml-parent-document:("wine-devel.sgml" "set" "book" "part" "chapter" "")
2603 End: