Port WITH-TLS-EA and other remaining FS prefix uses to Windows.
[sbcl.git] / src / runtime / x86-assem.S
1 /*
2  * very-low-level utilities for runtime support
3  */
4
5 /*
6  * This software is part of the SBCL system. See the README file for
7  * more information.
8  *
9  * This software is derived from the CMU CL system, which was
10  * written at Carnegie Mellon University and released into the
11  * public domain. The software is in the public domain and is
12  * provided with absolutely no warranty. See the COPYING and CREDITS
13  * files for more information.
14  */
15 \f
16 #define LANGUAGE_ASSEMBLY
17 #include "sbcl.h"
18 #include "validate.h"
19 #include "genesis/closure.h"
20 #include "genesis/funcallable-instance.h"
21 #include "genesis/fdefn.h"
22 #include "genesis/static-symbols.h"
23 #include "genesis/symbol.h"
24 #include "genesis/thread.h"
25         
26 /* Minimize conditionalization for different OS naming schemes. 
27  *
28  * (As of sbcl-0.8.10, this seems no longer to be much of an issue, 
29  * since everyone has converged on ELF. If this generality really 
30  * turns out not to matter, perhaps it's just clutter we could get
31  * rid of? -- WHN 2004-04-18)
32  *
33  * (Except Win32, which is unlikely ever to be ELF, sorry. -- AB 2005-12-08)
34  */
35 #if defined __linux__  || defined __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__ || defined __sun
36 #define GNAME(var) var
37 #else
38 #define GNAME(var) _##var
39 #endif
40
41 /* Get the right type of alignment. Linux, FreeBSD and NetBSD (but not OpenBSD)
42  * want alignment in bytes. 
43  *
44  * (As in the GNAME() definitions above, as of sbcl-0.8.10, this seems 
45  * no longer to be much of an issue, since everyone has converged on
46  * the same value. If this generality really turns out not to 
47  * matter any more, perhaps it's just clutter we could get
48  * rid of? -- WHN 2004-04-18)
49  */
50 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__sun) || defined(LISP_FEATURE_WIN32)
51 #define align_4byte     4
52 #define align_8byte     8
53 #define align_16byte    16
54 #define align_page      4096
55 #else
56 #define align_4byte     2
57 #define align_8byte     3
58 #define align_16byte    4       
59 #define align_page      12
60 #endif                  
61
62 /*
63  * The assembler used for win32 doesn't like .type or .size directives,
64  * so we want to conditionally kill them out. So let's wrap them in macros
65  * that are defined to be no-ops on win32. Hopefully this still works on
66  * other platforms.
67  */
68 #if !defined(LISP_FEATURE_WIN32) && !defined(LISP_FEATURE_DARWIN)
69 #define TYPE(name) .type name,@function
70 #define SIZE(name) .size name,.-name
71 #else
72 #define TYPE(name)
73 #define SIZE(name)
74 #endif
75
76 /* Helper macros for access to thread-locals slots for both OS types:
77  * ------------------------------------------------------------------------
78  *
79  *                          Windows TEB block
80  * ==================        __________
81  * | Win32 %FS base | ---->  |        | 0
82  * ==================        |        | 1
83  *                           z        z
84  *     TLS slots start here> |XXXXXXXX| e10 = TEB_STATIC_TLS_SLOTS_OFFSET
85  *                           |XXXXXXXX| e11
86  *                           z   ...  z
87  *                           |XXXXXXXX| e4e
88  *     TLS ends here>     ,- |XXXXXXXX| e4f = TEB_STATIC_TLS_SLOTS_OFFSET+63
89  *                       /   z        z
90  *                       |   ----------
91  *                       |
92  *                       |   big blob of SBCL-specific thread-local data
93  *                       |     |----------------------------------------|
94  *                       |     |   CONTROL, BINDING, ALIEN STACK        |
95  *                       |     z                                        z
96  * ==================    |     |----------------------------------------|
97  * | Linux %FS base | -->|     |   FFI stack pointer                    |
98  * ==================    |     |    (extra page for mprotect)           |
99  *                        \    |----------------------------------------|
100  *   (union p_t_d) ----->  \-> | struct thread {   | dynamic_values[0]  |
101  *   .                         |   ...             |               [1]  |
102  *   .                         z   ...             z               ...  z
103  *   [tls data begins]         | }                 |               ...  | <-
104  *   [declared end of p_t_d]   |----------------------------------------| . |
105  *   .                         |                                   ...  | . |
106  *   .                         |                           [TLS_SIZE-1] | <-|
107  *   [tls data actually ends]  |----------------------------------------|   |
108  *   .                         | ALTSTACK                               |   |
109  *   .                         |----------------------------------------|   |
110  *   .                         | struct nonpointer_thread_data { }      |   |
111  *   .                         ------------------------------------------   |
112  *   [blob actually ends]                                                   |
113  *                                                                         /
114  *                                                                        /
115  *                                                                       /
116  *          ______________________                                      /
117  *          | struct symbol {    |                                     /
118  *          z   ...              z                                    /
119  *          |   fixnum tls_index;  // fixnum value relative to union /
120  *          | }                  |           (< TLS_SIZE = 4096)
121  *          ---------------------|
122  */
123 #ifdef LISP_FEATURE_WIN32
124 # define TEB_STATIC_TLS_SLOTS_OFFSET 0xE10
125 # define TEB_SBCL_THREAD_BASE_OFFSET (TEB_STATIC_TLS_SLOTS_OFFSET+(63*4))
126 # define SBCL_THREAD_BASE_EA %fs:TEB_SBCL_THREAD_BASE_OFFSET
127 # define MAYBE_FS(addr) addr
128 # define LoadTlSymbolValueAddress(symbol,reg) ;         \
129         movl    SBCL_THREAD_BASE_EA, reg ;              \
130         addl    (symbol+SYMBOL_TLS_INDEX_OFFSET), reg ;
131 # define LoadCurrentThreadSlot(offset,reg);     \
132         movl    SBCL_THREAD_BASE_EA, reg ;      \
133         movl    offset(reg), reg ;
134 #elif defined(LISP_FEATURE_LINUX) || defined(LISP_FEATURE_SUNOS) || defined(LISP_FEATURE_FREEBSD)
135   /* see comment in arch_os_thread_init */
136 # define SBCL_THREAD_BASE_EA %fs:THREAD_SELFPTR_OFFSET
137 # define MAYBE_FS(addr) addr
138 #else
139   /* perhaps there's an OS out there that actually supports %fs without
140    * jumping through hoops, so just in case, here a default definition: */
141 # define SBCL_THREAD_BASE_EA $0
142 # define MAYBE_FS(addr) %fs:addr
143 #endif
144
145 /* gas can't parse 4096LU; redefine */
146 #if BACKEND_PAGE_BYTES == 4096
147 # undef BACKEND_PAGE_BYTES
148 # define BACKEND_PAGE_BYTES 4096
149 #elif BACKEND_PAGE_BYTES == 32768
150 # undef BACKEND_PAGE_BYTES
151 # define BACKEND_PAGE_BYTES 32768
152 #else
153 # error BACKEND_PAGE_BYTES mismatch
154 #endif
155
156 /* OAOOM because we don't have the C headers here */
157 #define THREAD_CSP_PAGE_SIZE BACKEND_PAGE_BYTES
158
159 /* the CSP page sits right before the thread */
160 #define THREAD_SAVED_CSP_OFFSET (-THREAD_CSP_PAGE_SIZE)
161
162 /*
163  * x86/darwin (as of MacOS X 10.4.5) doesn't reliably file signal
164  * handlers (SIGTRAP or Mach exception handlers) for 0xCC, wo we have
165  * to use ud2 instead. ud2 is an undefined opcode, #x0b0f, or
166  * 0F 0B in low-endian notation, that causes SIGILL to fire. We check
167  * for this instruction in the SIGILL handler and if we see it, we
168  * advance the EIP by two bytes to skip over ud2 instruction and
169  * call sigtrap_handler. */
170 #if defined(LISP_FEATURE_UD2_BREAKPOINTS)
171 #define END()
172 #define TRAP ud2
173 #else
174 #define END() .end
175 #define TRAP int3
176 #endif
177
178         .text
179         .globl  GNAME(all_threads)
180 \f
181 /*
182  * A call to call_into_c preserves esi, edi, and ebp.   
183  * (The C function will preserve ebx, esi, edi, and ebp across its
184  * function call, but we trash ebx ourselves by using it to save the
185  * return Lisp address.)
186  *
187  * Return values are in eax and maybe edx for quads, or st(0) for
188  * floats.
189  *
190  * This should work for Lisp calls C calls Lisp calls C..
191  *
192  * FIXME & OAOOM: This duplicates call-out in src/compiler/x86/c-call.lisp,
193  * so if you tweak this, change that too!
194  */
195 /*
196  * Note on sections specific to LISP_FEATURE_SB_SAFEPOINT:
197  *
198  * The code below is essential to safepoint-based garbage collection,
199  * and several details need to be considered for correct implementation.
200  *
201  * The stack spilling approach:
202  *   On SB-SAFEPOINT platforms, the CALL-OUT vop is defined to spill all
203  *   live Lisp TNs to the stack to provide information for conservative
204  *   GC cooperatively (avoiding the need to retrieve register values
205  *   from POSIX signal contexts or Windows GetThreadContext()).
206  *
207  * Finding the SP at all:
208  *   The main remaining value needed by GC is the stack pointer (SP) at
209  *   the moment of entering the foreign function.  For this purpose, a
210  *   thread-local field for the SP is used.  Two stores to that field
211  *   are done for each C call, one to save the SP before calling out and
212  *   and one to undo that store afterwards.
213  *
214  * Stores as synchronization points:
215  *   These two stores delimit the C call: While the SP is set, our
216  *   thread is known not to run Lisp code: During GC, memory protection
217  *   ensures that no thread proceeds across stores.
218  *
219  * The return PC issue:
220  *   (Note that CALL-OUT has, in principle, two versions: Inline
221  *   assembly in the VOP -or- alternatively the out-of-line version you
222  *   are currently reading.  In reality, safepoint builds currently
223  *   lack the inline code entirely.)
224  *
225  *   Both versions need to take special care with the return PC:
226  *   - In the inline version of the code (if it existed), the two stores
227  *     would be done directly in the CALL-OUT vop.  In that theoretical
228  *     implementation, there is a time interval between return of the
229  *     actual C call and a second SP store during which the return
230  *     address might not be on the stack anymore.
231  *   - In this out-of-line version, the stores are done during
232  *     call_into_c's frame, but an equivalent problem arises: In order
233  *     to present the stack of arguments as our foreign function expects
234  *     them, call_into_c has to pop the Lisp return address into a
235  *     register first; this register has to be preserved by GENCGC
236  *     separately: our return address is not in the stack anymore.
237  *   In both case, stack scanning alone is not sufficient to pin
238  *   the return address, and we communicate it to GC explicitly
239  *   in addition to the SP.
240  *
241  * Note on look-alike accessor macros with vastly different behaviour:
242  *   THREAD_PC_AROUND_FOREIGN_CALL_OFFSET is an "ordinary" field of the
243  *   struct thread, whereas THREAD_SAVED_CSP_OFFSET is a synchronization
244  *   point on a potentially write-protected page.
245 */
246
247         .text
248         .align  align_16byte,0x90
249         .globl GNAME(call_into_c)
250         TYPE(GNAME(call_into_c))
251 GNAME(call_into_c):
252 /* Save the return Lisp address in ebx. */
253         popl    %ebx
254
255 /* Setup the NPX for C */
256         /* The VOP says regarding CLD: "Clear out DF: Darwin, Windows,
257          * and Solaris at least require this, and it should not hurt
258          * others either." call_into_c didn't have it, but better safe than
259          * sorry. */
260         cld
261         fstp    %st(0)
262         fstp    %st(0)
263         fstp    %st(0)
264         fstp    %st(0)
265         fstp    %st(0)
266         fstp    %st(0)
267         fstp    %st(0)
268         fstp    %st(0)
269
270 #ifdef LISP_FEATURE_SB_SAFEPOINT
271         /* enter safe region: store SP and return PC */
272         movl    SBCL_THREAD_BASE_EA,%edi
273         movl    %esp,MAYBE_FS(THREAD_SAVED_CSP_OFFSET(%edi))
274         movl    %ebx,MAYBE_FS(THREAD_PC_AROUND_FOREIGN_CALL_OFFSET(%edi))
275 #endif
276
277         /* foreign call, preserving ESI, EDI, and EBX */
278         call    *%eax             # normal callout using Lisp stack
279         /* return values now in eax/edx OR st(0) */
280
281 #ifdef LISP_FEATURE_SB_SAFEPOINT
282         /* leave region: clear the SP!  (Also unpin the return PC.) */
283         xorl    %ecx,%ecx
284         movl    %ecx,MAYBE_FS(THREAD_SAVED_CSP_OFFSET(%edi))
285         movl    %ecx,MAYBE_FS(THREAD_PC_AROUND_FOREIGN_CALL_OFFSET(%edi))
286 #endif
287
288         movl    %eax,%ecx         # remember integer return value
289
290 /* Check for a return FP value. */
291         fxam
292         fnstsw  %ax
293         andl    $0x4500,%eax
294         cmpl    $0x4100,%eax
295         jne     Lfp_rtn_value
296
297 /* The return value is in eax, or eax,edx? */
298 /* Set up the NPX stack for Lisp. */
299         fldz                    # Ensure no regs are empty.
300         fldz
301         fldz
302         fldz
303         fldz
304         fldz
305         fldz
306         fldz
307
308 /* Restore the return value. */
309         movl    %ecx,%eax       # maybe return value
310
311 /* Return. */
312         jmp     *%ebx
313
314 Lfp_rtn_value:
315 /* The return result is in st(0). */
316 /* Set up the NPX stack for Lisp, placing the result in st(0). */
317         fldz                    # Ensure no regs are empty.
318         fldz
319         fldz
320         fldz
321         fldz
322         fldz
323         fldz
324         fxch    %st(7)          # Move the result back to st(0).
325
326 /* We don't need to restore eax, because the result is in st(0). */
327
328 /* Return. FIXME: It would be nice to restructure this to use RET. */
329         jmp     *%ebx
330
331         SIZE(GNAME(call_into_c))
332
333 \f
334         .text   
335         .globl GNAME(call_into_lisp_first_time)
336         TYPE(GNAME(call_into_lisp_first_time))
337                 
338 /* We don't worry too much about saving registers 
339  * here, because we never expect to return from the initial call to lisp 
340  * anyway */
341         
342         .align  align_16byte,0x90
343 GNAME(call_into_lisp_first_time):
344         pushl   %ebp            # Save old frame pointer.
345         movl    %esp,%ebp       # Establish new frame.
346 #ifndef LISP_FEATURE_WIN32
347         movl    GNAME(all_threads),%eax
348         /* pthread machinery takes care of this for other threads */
349         movl    THREAD_CONTROL_STACK_END_OFFSET(%eax) ,%esp
350 #else
351 /* Win32 -really- doesn't like you switching stacks out from under it. */
352         movl    GNAME(all_threads),%eax
353 #endif
354         jmp     Lstack
355 \f
356         .text   
357         .globl GNAME(call_into_lisp)
358         TYPE(GNAME(call_into_lisp))
359                 
360 /* The C conventions require that ebx, esi, edi, and ebp be preserved
361  * across function calls. */
362         
363         .align  align_16byte,0x90
364 GNAME(call_into_lisp):
365         pushl   %ebp            # Save old frame pointer.
366         movl    %esp,%ebp       # Establish new frame.
367
368 Lstack:
369 /* Save the NPX state */
370         fwait                   # Catch any pending NPX exceptions.
371         subl    $108,%esp       # Make room for the NPX state.
372         fnsave  (%esp)          # save and reset NPX
373
374         movl    (%esp),%eax     # Load NPX control word.
375         andl    $0xfffff2ff,%eax        # Set rounding mode to nearest.
376         orl     $0x00000200,%eax        # Set precision to 64 bits.  (53-bit mantissa)
377         pushl   %eax
378         fldcw   (%esp)          # Recover modes.
379         popl    %eax
380
381         fldz                    # Ensure no FP regs are empty.
382         fldz
383         fldz
384         fldz
385         fldz
386         fldz
387         fldz
388         fldz
389         
390 /* Save C regs: ebx esi edi. */
391         pushl   %ebx
392         pushl   %esi
393         pushl   %edi
394         
395 /* Clear descriptor regs. */
396         xorl    %eax,%eax       # lexenv
397         xorl    %ebx,%ebx       # available
398         xorl    %ecx,%ecx       # arg count
399         xorl    %edx,%edx       # first arg
400         xorl    %edi,%edi       # second arg
401         xorl    %esi,%esi       # third arg
402
403 /* no longer in function call */
404         movl    %esp,%ebx       # remember current stack
405         pushl   %ebx            # Save entry stack on (maybe) new stack.
406
407         /* Establish Lisp args. */
408         movl     8(%ebp),%eax   # lexenv?
409         movl    12(%ebp),%ebx   # address of arg vec
410         movl    16(%ebp),%ecx   # num args
411         shll    $2,%ecx         # Make num args into fixnum.
412         cmpl    $0,%ecx
413         je      Ldone
414         movl    (%ebx),%edx     # arg0
415         cmpl    $4,%ecx
416         je      Ldone
417         movl    4(%ebx),%edi    # arg1
418         cmpl    $8,%ecx
419         je      Ldone
420         movl    8(%ebx),%esi    # arg2
421 Ldone:  
422         /* Registers eax, ecx, edx, edi, and esi are now live. */
423
424 #ifdef LISP_FEATURE_WIN32
425         /* Establish an SEH frame. */
426 #ifdef LISP_FEATURE_SB_THREAD
427         /* FIXME: need to save BSP here. */
428 #error "need to save BSP here, but don't know how yet."
429 #else
430         pushl   BINDING_STACK_POINTER + SYMBOL_VALUE_OFFSET
431 #endif
432         pushl   $GNAME(exception_handler_wrapper)
433         pushl   %fs:0
434         movl    %esp, %fs:0
435 #endif
436
437         /* Alloc new frame. */
438         push    %ebp            # Dummy for return address
439         push    %ebp            # fp in save location S1
440         mov     %esp,%ebp       # The current sp marks start of new frame.
441         sub     $4,%esp         # Ensure 3 slots are allocated, two above.
442
443         call    *CLOSURE_FUN_OFFSET(%eax)
444         
445         /* If the function returned multiple values, it will return to
446            this point.  Lose them */
447         jnc     LsingleValue
448         mov     %ebx, %esp
449 LsingleValue:
450         /* A singled value function returns here */
451
452 #ifdef LISP_FEATURE_WIN32
453         /* Remove our SEH frame. */
454         popl    %fs:0
455         add     $8, %esp
456 #endif
457
458 /* Restore the stack, in case there was a stack change. */
459         popl    %esp            # c-sp
460
461 /* Restore C regs: ebx esi edi. */
462         popl    %edi
463         popl    %esi
464         popl    %ebx
465
466 /* Restore the NPX state. */
467         frstor  (%esp)
468         addl    $108, %esp
469         
470         popl    %ebp            # c-sp
471         movl    %edx,%eax       # c-val
472         ret
473         SIZE(GNAME(call_into_lisp))
474 \f
475 /* support for saving and restoring the NPX state from C */
476         .text
477         .globl  GNAME(fpu_save)
478         TYPE(GNAME(fpu_save))
479         .align  2,0x90
480 GNAME(fpu_save):
481         movl    4(%esp),%eax
482         fnsave  (%eax)          # Save the NPX state. (resets NPX)
483         ret
484         SIZE(GNAME(fpu_save))
485
486         .globl  GNAME(fpu_restore)
487         TYPE(GNAME(fpu_restore))
488         .align  2,0x90
489 GNAME(fpu_restore):
490         movl    4(%esp),%eax
491         frstor  (%eax)          # Restore the NPX state.
492         ret
493         SIZE(GNAME(fpu_restore))
494 \f
495 /*
496  * the undefined-function trampoline
497  */
498         .text
499         .align  align_16byte,0x90
500         .globl GNAME(undefined_tramp)
501         TYPE(GNAME(undefined_tramp))
502         .byte   0, 0, 0, SIMPLE_FUN_HEADER_WIDETAG
503 GNAME(undefined_tramp):
504         pop     4(%ebp)         # Save return PC for backtrace.
505         TRAP
506         .byte   trap_Error
507         .byte   2
508         .byte   UNDEFINED_FUN_ERROR
509         .byte   sc_DescriptorReg # eax in the Descriptor-reg SC
510         ret
511         SIZE(GNAME(undefined_tramp))
512
513 /* KLUDGE: FIND-ESCAPED-FRAME (SYS:SRC;CODE;DEBUG-INT.LISP) needs
514  * to know the name of the function immediately following the
515  * undefined-function trampoline. */
516
517 /*
518  * the closure trampoline
519  */
520         .text
521         .align  align_16byte,0x90
522         .globl GNAME(closure_tramp)
523         TYPE(GNAME(closure_tramp))
524         .byte   0, 0, 0, SIMPLE_FUN_HEADER_WIDETAG
525 GNAME(closure_tramp):
526         movl    FDEFN_FUN_OFFSET(%eax),%eax
527         /* FIXME: The '*' after "jmp" in the next line is from PVE's
528          * patch posted to the CMU CL mailing list Oct 6, 1999. It looks
529          * reasonable, and it certainly seems as though if CMU CL needs it,
530          * SBCL needs it too, but I haven't actually verified that it's
531          * right. It would be good to find a way to force the flow of
532          * control through here to test it. */
533         jmp     *CLOSURE_FUN_OFFSET(%eax)
534         SIZE(GNAME(closure_tramp))
535
536         .text
537         .align  align_16byte,0x90
538         .globl GNAME(funcallable_instance_tramp)
539         TYPE(GNAME(funcallable_instance_tramp))
540 GNAME(funcallable_instance_tramp):
541         movl    FUNCALLABLE_INSTANCE_FUNCTION_OFFSET(%eax),%eax 
542         /* KLUDGE: on this platform, whatever kind of function is in %rax
543          * now, the first word of it contains the address to jump to. */
544         jmp     *CLOSURE_FUN_OFFSET(%eax)
545         SIZE(GNAME(funcallable_instance_tramp))
546         
547 /*
548  * fun-end breakpoint magic
549  */
550
551 /*
552  * For an explanation of the magic involved in function-end
553  * breakpoints, see the implementation in ppc-assem.S.
554  */
555
556         .text
557         .globl  GNAME(fun_end_breakpoint_guts)
558         .align  align_16byte
559 GNAME(fun_end_breakpoint_guts):
560         /* Multiple Value return */
561         jc      multiple_value_return
562         /* Single value return: The eventual return will now use the
563            multiple values return convention but with a return values
564            count of one. */
565         movl    %esp,%ebx       # Setup ebx - the ofp.
566         subl    $4,%esp         # Allocate one stack slot for the return value
567         movl    $4,%ecx         # Setup ecx for one return value.
568         movl    $(NIL),%edi     # default second value
569         movl    $(NIL),%esi     # default third value
570                 
571 multiple_value_return:
572         
573         .globl GNAME(fun_end_breakpoint_trap)
574 GNAME(fun_end_breakpoint_trap):
575         TRAP
576         .byte   trap_FunEndBreakpoint
577         hlt                     # We should never return here.
578
579         .globl GNAME(fun_end_breakpoint_end)
580 GNAME(fun_end_breakpoint_end):
581
582 \f
583         .globl  GNAME(do_pending_interrupt)
584         TYPE(GNAME(do_pending_interrupt))
585         .align  align_16byte,0x90
586 GNAME(do_pending_interrupt):
587         TRAP
588         .byte   trap_PendingInterrupt
589         ret
590         SIZE(GNAME(do_pending_interrupt))
591 \f
592 /* Allocate bytes and return the start of the allocated space
593  * in the specified destination register.
594  *
595  * In the general case the size will be in the destination register.
596  *
597  * All registers must be preserved except the destination.
598  * The C conventions will preserve ebx, esi, edi, and ebp.
599  * So only eax, ecx, and edx need special care here.
600  *
601  * ALLOC factors out the logic of calling alloc(): stack alignment, etc.
602  *
603  * DEFINE_ALLOC_TO_FOO defines an alloction routine.
604  */
605
606 #ifdef LISP_FEATURE_DARWIN
607 #define ALLOC(size)                                             \
608         pushl   %ebp;              /* Save EBP               */ \
609         movl    %esp,%ebp;         /* Save ESP to EBP        */ \
610         pushl   $0;                /* Reserve space for arg  */ \
611         andl    $0xfffffff0,%esp;  /* Align stack to 16bytes */ \
612         movl    size, (%esp);      /* Argument to alloc      */ \
613         call    GNAME(alloc);                                   \
614         movl    %ebp,%esp;         /* Restore ESP from EBP   */ \
615         popl    %ebp;              /* Restore EBP            */
616 #else
617 #define ALLOC(size)                                             \
618         pushl   size;              /* Argument to alloc      */ \
619         call    GNAME(alloc);                                   \
620         addl    $4,%esp;           /* Pop argument           */
621 #endif
622
623 #define DEFINE_ALLOC_TO_EAX(name,size)                          \
624         .globl  GNAME(name);                                    \
625         TYPE(GNAME(name));                                      \
626         .align  align_16byte,0x90;                              \
627 GNAME(name):                                                    \
628         pushl   %ecx;              /* Save ECX and EDX       */ \
629         pushl   %edx;                                           \
630         ALLOC(size)                                             \
631         popl    %edx;              /* Restore ECX and EDX    */ \
632         popl    %ecx;                                           \
633         ret;                                                    \
634         SIZE(GNAME(name))
635
636 #define DEFINE_ALLOC_TO_ECX(name,size)                          \
637         .globl  GNAME(name);                                    \
638         TYPE(GNAME(name));                                      \
639         .align  align_16byte,0x90;                              \
640 GNAME(name):                                                    \
641         pushl   %eax;              /* Save EAX and EDX       */ \
642         pushl   %edx;                                           \
643         ALLOC(size)                                             \
644         movl    %eax,%ecx;         /* Result to destination  */ \
645         popl    %edx;                                           \
646         popl    %eax;                                           \
647         ret;                                                    \
648         SIZE(GNAME(name))
649         
650 #define DEFINE_ALLOC_TO_EDX(name,size)                          \
651         .globl  GNAME(name);                                    \
652         TYPE(GNAME(name));                                      \
653         .align  align_16byte,0x90;                              \
654 GNAME(name):                                                    \
655         pushl   %eax;               /* Save EAX and ECX      */ \
656         pushl   %ecx;                                           \
657         ALLOC(size)                                             \
658         movl    %eax,%edx;          /* Restore EAX and ECX   */ \
659         popl    %ecx;                                           \
660         popl    %eax;                                           \
661         ret;                                                    \
662         SIZE(GNAME(name))
663
664 #define DEFINE_ALLOC_TO_REG(name,reg,size)                      \
665         .globl  GNAME(name);                                    \
666         TYPE(GNAME(name));                                      \
667         .align  align_16byte,0x90;                              \
668 GNAME(name):                                                    \
669         pushl   %eax;              /* Save EAX, ECX, and EDX */ \
670         pushl   %ecx;                                           \
671         pushl   %edx;                                           \
672         ALLOC(size)                                             \
673         movl    %eax,reg;          /* Restore them           */ \
674         popl    %edx;                                           \
675         popl    %ecx;                                           \
676         popl    %eax;                                           \
677         ret;                                                    \
678         SIZE(GNAME(name))
679
680 DEFINE_ALLOC_TO_EAX(alloc_to_eax,%eax)
681 DEFINE_ALLOC_TO_EAX(alloc_8_to_eax,$8)
682 DEFINE_ALLOC_TO_EAX(alloc_16_to_eax,$16)
683
684 DEFINE_ALLOC_TO_ECX(alloc_to_ecx,%ecx)
685 DEFINE_ALLOC_TO_ECX(alloc_8_to_ecx,$8)
686 DEFINE_ALLOC_TO_ECX(alloc_16_to_ecx,$16)
687
688 DEFINE_ALLOC_TO_EDX(alloc_to_edx,%edx)
689 DEFINE_ALLOC_TO_EDX(alloc_8_to_edx,$8)
690 DEFINE_ALLOC_TO_EDX(alloc_16_to_edx,$16)
691
692 DEFINE_ALLOC_TO_REG(alloc_to_ebx,%ebx,%ebx)
693 DEFINE_ALLOC_TO_REG(alloc_8_to_ebx,%ebx,$8)
694 DEFINE_ALLOC_TO_REG(alloc_16_to_ebx,%ebx,$16)
695
696 DEFINE_ALLOC_TO_REG(alloc_to_esi,%esi,%esi)
697 DEFINE_ALLOC_TO_REG(alloc_8_to_esi,%esi,$8)
698 DEFINE_ALLOC_TO_REG(alloc_16_to_esi,%esi,$16)
699
700 DEFINE_ALLOC_TO_REG(alloc_to_edi,%edi,%edi)
701 DEFINE_ALLOC_TO_REG(alloc_8_to_edi,%edi,$8)
702 DEFINE_ALLOC_TO_REG(alloc_16_to_edi,%edi,$16)
703
704 /* Called from lisp when an inline allocation overflows.
705  * Every register except the result needs to be preserved.
706  * We depend on C to preserve ebx, esi, edi, and ebp.
707  * But where necessary must save eax, ecx, edx. */
708
709 #ifdef LISP_FEATURE_SB_THREAD
710 #define START_REGION %fs:THREAD_ALLOC_REGION_OFFSET
711 #else
712 #define START_REGION GNAME(boxed_region)
713 #endif
714
715 #if defined(LISP_FEATURE_SB_THREAD) && defined(LISP_FEATURE_WIN32)
716 #define ALLOC_OVERFLOW(size,scratch)                            \
717         movl SBCL_THREAD_BASE_EA, scratch;                      \
718         /* Calculate the size for the allocation. */            \
719         subl THREAD_ALLOC_REGION_OFFSET(scratch),size;          \
720         ALLOC(size)
721 #else
722 #define ALLOC_OVERFLOW(size,scratch)                    \
723           /* Calculate the size for the allocation. */  \
724           subl    START_REGION,size;                    \
725           ALLOC(size)
726 #endif
727
728 /* This routine handles an overflow with eax=crfp+size. So the
729    size=eax-crfp. */
730         .align  align_16byte
731         .globl  GNAME(alloc_overflow_eax)
732         TYPE(GNAME(alloc_overflow_eax))
733 GNAME(alloc_overflow_eax):
734         pushl   %ecx            # Save ecx
735         pushl   %edx            # Save edx
736         ALLOC_OVERFLOW(%eax,%edx)
737         popl    %edx    # Restore edx.
738         popl    %ecx    # Restore ecx.
739         ret
740         SIZE(GNAME(alloc_overflow_eax))
741
742         .align  align_16byte
743         .globl  GNAME(alloc_overflow_ecx)
744         TYPE(GNAME(alloc_overflow_ecx))
745 GNAME(alloc_overflow_ecx):
746         pushl   %eax            # Save eax
747         pushl   %edx            # Save edx
748         ALLOC_OVERFLOW(%ecx,%edx)
749         movl    %eax,%ecx       # setup the destination.
750         popl    %edx    # Restore edx.
751         popl    %eax    # Restore eax.
752         ret
753         SIZE(GNAME(alloc_overflow_ecx))
754
755         .align  align_16byte
756         .globl  GNAME(alloc_overflow_edx)
757         TYPE(GNAME(alloc_overflow_edx))
758 GNAME(alloc_overflow_edx):
759         pushl   %eax            # Save eax
760         pushl   %ecx            # Save ecx
761         ALLOC_OVERFLOW(%edx,%ecx)
762         movl    %eax,%edx       # setup the destination.
763         popl    %ecx    # Restore ecx.
764         popl    %eax    # Restore eax.
765         ret
766         SIZE(GNAME(alloc_overflow_edx))
767
768 /* This routine handles an overflow with ebx=crfp+size. So the
769    size=ebx-crfp. */
770         .align  align_16byte
771         .globl  GNAME(alloc_overflow_ebx)
772         TYPE(GNAME(alloc_overflow_ebx))
773 GNAME(alloc_overflow_ebx):
774         pushl   %eax            # Save eax
775         pushl   %ecx            # Save ecx
776         pushl   %edx            # Save edx
777         ALLOC_OVERFLOW(%ebx,%edx)
778         movl    %eax,%ebx       # setup the destination.
779         popl    %edx    # Restore edx.
780         popl    %ecx    # Restore ecx.
781         popl    %eax    # Restore eax.
782         ret
783         SIZE(GNAME(alloc_overflow_ebx))
784
785 /* This routine handles an overflow with esi=crfp+size. So the
786    size=esi-crfp. */
787         .align  align_16byte
788         .globl  GNAME(alloc_overflow_esi)
789         TYPE(GNAME(alloc_overflow_esi))
790 GNAME(alloc_overflow_esi):
791         pushl   %eax            # Save eax
792         pushl   %ecx            # Save ecx
793         pushl   %edx            # Save edx
794         ALLOC_OVERFLOW(%esi,%edx)
795         movl    %eax,%esi       # setup the destination.
796         popl    %edx    # Restore edx.
797         popl    %ecx    # Restore ecx.
798         popl    %eax    # Restore eax.
799         ret
800         SIZE(GNAME(alloc_overflow_esi))
801
802         .align  align_16byte
803         .globl  GNAME(alloc_overflow_edi)
804         TYPE(GNAME(alloc_overflow_edi))
805 GNAME(alloc_overflow_edi):
806         pushl   %eax            # Save eax
807         pushl   %ecx            # Save ecx
808         pushl   %edx            # Save edx
809         ALLOC_OVERFLOW(%edi,%edx)
810         movl    %eax,%edi       # setup the destination.
811         popl    %edx    # Restore edx.
812         popl    %ecx    # Restore ecx.
813         popl    %eax    # Restore eax.
814         ret
815         SIZE(GNAME(alloc_overflow_edi))
816
817
818 #ifdef LISP_FEATURE_WIN32
819         /* The guts of the exception-handling system doesn't use
820          * frame pointers, which manages to throw off backtraces
821          * rather badly.  So here we grab the (known-good) EBP
822          * and EIP from the exception context and use it to fake
823          * up a stack frame which will skip over the system SEH
824          * code. */
825         .align  align_16byte
826         .globl  GNAME(exception_handler_wrapper)
827         TYPE(GNAME(exception_handler_wrapper))
828 GNAME(exception_handler_wrapper):
829         /* Context layout is: */
830         /* 7 dwords before FSA. (0x1c) */
831         /* 8 dwords and 0x50 bytes in the FSA. (0x70/0x8c) */
832         /* 4 dwords segregs. (0x10/0x9c) */
833         /* 6 dwords non-stack GPRs. (0x18/0xb4) */
834         /* EBP (at 0xb4) */
835         /* EIP (at 0xb8) */
836 #define CONTEXT_EBP_OFFSET 0xb4
837 #define CONTEXT_EIP_OFFSET 0xb8
838         /* some other stuff we don't care about. */
839         pushl   %ebp
840         movl    0x10(%esp), %ebp        /* context */
841         pushl   CONTEXT_EIP_OFFSET(%ebp)
842         pushl   CONTEXT_EBP_OFFSET(%ebp)
843         movl    %esp, %ebp
844         pushl   0x1c(%esp)
845         pushl   0x1c(%esp)
846         pushl   0x1c(%esp)
847         pushl   0x1c(%esp)
848         call    GNAME(handle_exception)
849         lea     8(%ebp), %esp
850         popl    %ebp
851         ret
852         SIZE(GNAME(exception_handler_wrapper))
853 #endif
854
855 #ifdef LISP_FEATURE_DARWIN
856         .align align_16byte
857         .globl GNAME(call_into_lisp_tramp)
858         TYPE(GNAME(call_into_lisp_tramp))
859 GNAME(call_into_lisp_tramp):
860         /* 1. build the stack frame from the block that's pointed to by ECX
861            2. free the block
862            3. set ECX to 0
863            4. call the function via call_into_lisp
864         */
865         pushl   0(%ecx)          /* return address */
866
867         pushl   %ebp
868         movl    %esp, %ebp
869
870         pushl   32(%ecx)         /* eflags */
871         pushl   28(%ecx)         /* EAX */
872         pushl   20(%ecx)         /* ECX */
873         pushl   16(%ecx)         /* EDX */
874         pushl   24(%ecx)         /* EBX */
875         pushl   $0                /* popal is going to ignore esp */
876         pushl   %ebp              /* is this right?? */
877         pushl   12(%ecx)         /* ESI */
878         pushl   8(%ecx)          /* EDI */
879         pushl   $0                /* args for call_into_lisp */
880         pushl   $0
881         pushl   4(%ecx)          /* function to call */
882
883         /* free our save block */
884         pushl   %ecx              /* reserve sufficient space on stack for args */
885         pushl   %ecx
886         andl    $0xfffffff0, %esp  /* align stack */
887         movl    $0x40, 4(%esp)
888         movl    %ecx, (%esp)
889         call    GNAME(os_invalidate)
890
891         /* call call_into_lisp */
892         leal    -48(%ebp), %esp
893         call    GNAME(call_into_lisp)
894
895         /* Clean up our mess */
896         leal    -36(%ebp), %esp
897         popal
898         popfl
899         leave
900         ret
901         
902         SIZE(call_into_lisp_tramp)
903 #endif
904         
905         .align  align_16byte,0x90
906         .globl  GNAME(post_signal_tramp)
907         TYPE(GNAME(post_signal_tramp))
908 GNAME(post_signal_tramp):
909         /* this is notionally the second half of a function whose first half
910          * doesn't exist.  This is where call_into_lisp returns when called 
911          * using return_to_lisp_function */
912         addl $12,%esp   /* clear call_into_lisp args from stack */
913         popal           /* restore registers */
914         popfl
915 #ifdef LISP_FEATURE_DARWIN
916         /* skip two padding words */
917         addl $8,%esp
918 #endif
919         leave
920         ret
921         SIZE(GNAME(post_signal_tramp))
922
923
924         /* fast_bzero implementations and code to detect which implementation
925          * to use.
926          */
927 \f
928         .globl GNAME(fast_bzero_pointer)
929         .data
930         .align  align_16byte
931 GNAME(fast_bzero_pointer):
932         /* Variable containing a pointer to the bzero function to use.
933          * Initially points to a basic function.  Change this variable
934          * to fast_bzero_detect if OS supports SSE.  */
935         .long GNAME(fast_bzero_base)
936 \f
937         .globl GNAME(gc_safepoint_page)
938         .data
939         .align  align_page
940 GNAME(gc_safepoint_page):
941         .fill BACKEND_PAGE_BYTES,1,0
942 \f
943         .text
944         .align  align_16byte,0x90
945         .globl GNAME(fast_bzero)
946         TYPE(GNAME(fast_bzero))
947 GNAME(fast_bzero):        
948         /* Indirect function call */
949         jmp *GNAME(fast_bzero_pointer)
950         SIZE(GNAME(fast_bzero))
951         
952 \f      
953         .text
954         .align  align_16byte,0x90
955         .globl GNAME(fast_bzero_detect)
956         TYPE(GNAME(fast_bzero_detect))
957 GNAME(fast_bzero_detect):
958         /* Decide whether to use SSE, MMX or REP version */
959         push %eax /* CPUID uses EAX-EDX */
960         push %ebx
961         push %ecx
962         push %edx
963         mov $1, %eax
964         cpuid
965         test $0x04000000, %edx    /* SSE2 needed for MOVNTDQ */
966         jnz Lsse2
967         /* Originally there was another case here for using the
968          * MOVNTQ instruction for processors that supported MMX but
969          * not SSE2. This turned out to be a loss especially on
970          * Athlons (where this instruction is apparently microcoded
971          * somewhat slowly). So for simplicity revert to REP STOSL
972          * for all non-SSE2 processors.
973          */
974 Lbase:
975         movl $(GNAME(fast_bzero_base)), GNAME(fast_bzero_pointer)
976         jmp Lrestore
977 Lsse2:
978         movl $(GNAME(fast_bzero_sse)), GNAME(fast_bzero_pointer)
979         jmp Lrestore
980         
981 Lrestore:
982         pop %edx
983         pop %ecx
984         pop %ebx
985         pop %eax
986         jmp *GNAME(fast_bzero_pointer)
987         
988         SIZE(GNAME(fast_bzero_detect))
989         
990 \f
991         .text
992         .align  align_16byte,0x90
993         .globl GNAME(fast_bzero_sse)
994         TYPE(GNAME(fast_bzero_sse))
995         
996 GNAME(fast_bzero_sse):
997         /* A fast routine for zero-filling blocks of memory that are
998          * guaranteed to start and end at a 4096-byte aligned address.
999          */        
1000         push %esi                 /* Save temporary registers */
1001         push %edi
1002         mov 16(%esp), %esi        /* Parameter: amount of bytes to fill */
1003         mov 12(%esp), %edi        /* Parameter: start address */
1004         shr $6, %esi              /* Amount of 64-byte blocks to copy */
1005         jz Lend_sse               /* If none, stop */
1006         movups %xmm7, -16(%esp)   /* Save XMM register */
1007         xorps  %xmm7, %xmm7       /* Zero the XMM register */
1008         jmp Lloop_sse
1009         .align align_16byte
1010 Lloop_sse:
1011
1012         /* Copy the 16 zeroes from xmm7 to memory, 4 times. MOVNTDQ is the
1013          * non-caching double-quadword moving variant, i.e. the memory areas
1014          * we're touching are not fetched into the L1 cache, since we're just
1015          * going to overwrite the memory soon anyway.
1016          */
1017         movntdq %xmm7, 0(%edi)
1018         movntdq %xmm7, 16(%edi)
1019         movntdq %xmm7, 32(%edi)
1020         movntdq %xmm7, 48(%edi)
1021  
1022         add $64, %edi /* Advance pointer */
1023         dec %esi      /* Decrement 64-byte block count */
1024         jnz Lloop_sse
1025         movups -16(%esp), %xmm7 /* Restore the XMM register */
1026         sfence        /* Ensure that weakly ordered writes are flushed. */
1027 Lend_sse:
1028         mov 12(%esp), %esi      /* Parameter: start address */
1029         prefetcht0 0(%esi)      /* Prefetch the start of the block into cache,
1030                                  * since it's likely to be used immediately. */
1031         pop %edi      /* Restore temp registers */
1032         pop %esi
1033         ret
1034         SIZE(GNAME(fast_bzero_sse))
1035                 
1036 \f
1037         .text
1038         .align  align_16byte,0x90
1039         .globl GNAME(fast_bzero_base)
1040         TYPE(GNAME(fast_bzero_base))
1041         
1042 GNAME(fast_bzero_base):
1043         /* A fast routine for zero-filling blocks of memory that are
1044          * guaranteed to start and end at a 4096-byte aligned address.
1045          */        
1046         push %eax                 /* Save temporary registers */
1047         push %ecx
1048         push %edi
1049         mov 20(%esp), %ecx        /* Parameter: amount of bytes to fill */
1050         mov 16(%esp), %edi        /* Parameter: start address */
1051         xor %eax, %eax            /* Zero EAX */
1052         shr $2, %ecx              /* Amount of 4-byte blocks to copy */
1053         jz  Lend_base
1054
1055         rep
1056         stosl                     /* Store EAX to *EDI, ECX times, incrementing
1057                                    * EDI by 4 after each store */
1058         
1059 Lend_base:        
1060         pop %edi                  /* Restore temp registers */
1061         pop %ecx
1062         pop %eax
1063         ret
1064         SIZE(GNAME(fast_bzero_base))
1065
1066 \f
1067 /* When LISP_FEATURE_C_STACK_IS_CONTROL_STACK, we cannot safely scrub
1068  * the control stack from C, largely due to not knowing where the
1069  * active stack frame ends.  On such platforms, we reimplement the
1070  * core scrubbing logic in assembly, in this case here:
1071  */
1072         .text
1073         .align  align_16byte,0x90
1074         .globl GNAME(arch_scrub_control_stack)
1075         TYPE(GNAME(arch_scrub_control_stack))
1076 GNAME(arch_scrub_control_stack):
1077         /* We are passed three parameters:
1078          * A (struct thread *) at [ESP+4],
1079          * the address of the guard page at [ESP+8], and
1080          * the address of the hard guard page at [ESP+12].
1081          * We may trash EAX, ECX, and EDX with impunity.
1082          * [ESP] is our return address, [ESP-4] is the first
1083          * stack slot to scrub. */
1084
1085         /* We start by setting up our scrub pointer in EAX, our
1086          * guard page upper bound in ECX, and our hard guard
1087          * page upper bound in EDX. */
1088         lea     -4(%esp), %eax
1089         mov     GNAME(os_vm_page_size),%edx
1090         mov     %edx, %ecx
1091         add     8(%esp), %ecx
1092         add     12(%esp), %edx
1093
1094         /* We need to do a memory operation relative to the
1095          * thread pointer, so put it in %ecx and our guard
1096          * page upper bound in 4(%esp). */
1097         xchg    4(%esp), %ecx
1098
1099         /* Now we begin our main scrub loop. */
1100 ascs_outer_loop:
1101
1102         /* If we're about to scrub the hard guard page, exit. */
1103         cmp     %edx, %eax
1104         jae     ascs_check_guard_page
1105         cmp     12(%esp), %eax
1106         ja      ascs_finished
1107
1108 ascs_check_guard_page:
1109         /* If we're about to scrub the guard page, and the guard
1110          * page is protected, exit. */
1111         cmp     4(%esp), %eax
1112         jae     ascs_clear_loop
1113         cmp     8(%esp), %eax
1114         jbe     ascs_clear_loop
1115         cmpl    $(NIL), THREAD_CONTROL_STACK_GUARD_PAGE_PROTECTED_OFFSET(%ecx)
1116         jne     ascs_finished
1117
1118         /* Clear memory backwards to the start of the (4KiB) page */
1119 ascs_clear_loop:
1120         movl    $0, (%eax)
1121         test    $0xfff, %eax
1122         lea     -4(%eax), %eax
1123         jnz     ascs_clear_loop
1124
1125         /* If we're about to hit the hard guard page, exit. */
1126         cmp     %edx, %eax
1127         jae     ascs_finished
1128
1129         /* If the next (previous?) 4KiB page contains a non-zero
1130          * word, continue scrubbing. */
1131 ascs_check_loop:
1132         testl   $-1, (%eax)
1133         jnz     ascs_outer_loop
1134         test    $0xfff, %eax
1135         lea     -4(%eax), %eax
1136         jnz     ascs_check_loop
1137
1138 ascs_finished:
1139         ret
1140         SIZE(GNAME(arch_scrub_control_stack))
1141 \f
1142         END()