1 
2 /*--------------------------------------------------------------------*/
3 /*--- Create/destroy signal delivery frames.                       ---*/
4 /*---                                       sigframe-x86-freebsd.c ---*/
5 /*--------------------------------------------------------------------*/
6 
7 /*
8    This file is part of Valgrind, a dynamic binary instrumentation
9    framework.
10 
11    Copyright (C) 2000-2009 Nicholas Nethercote
12       njn@valgrind.org
13 
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License as
16    published by the Free Software Foundation; either version 2 of the
17    License, or (at your option) any later version.
18 
19    This program is distributed in the hope that it will be useful, but
20    WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22    General Public License for more details.
23 
24    You should have received a copy of the GNU General Public License
25    along with this program; if not, write to the Free Software
26    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
27    02111-1307, USA.
28 
29    The GNU General Public License is contained in the file COPYING.
30 */
31 
32 #if defined(VGP_x86_freebsd)
33 
34 #include "pub_core_basics.h"
35 #include "pub_core_vki.h"
36 #include "pub_core_libcsetjmp.h"    // to keep _threadstate.h happy
37 #include "pub_core_threadstate.h"
38 #include "pub_core_aspacemgr.h" /* find_segment */
39 #include "pub_core_libcbase.h"
40 #include "pub_core_libcassert.h"
41 #include "pub_core_libcprint.h"
42 #include "pub_core_machine.h"
43 #include "pub_core_options.h"
44 #include "pub_core_signals.h"
45 #include "pub_core_tooliface.h"
46 #include "pub_core_trampoline.h"
47 #include "pub_core_sigframe.h"   /* self */
48 
49 
50 /* This module creates and removes signal frames for signal deliveries
51    on x86-freebsd.
52 */
53 
54 
55 /*------------------------------------------------------------*/
56 /*--- Signal frame layouts                                 ---*/
57 /*------------------------------------------------------------*/
58 
59 // A structure in which to save the application's registers
60 // during the execution of signal handlers.
61 
62 // In theory, so long as we get the arguments to the handler function
63 // right, it doesn't matter what the exact layout of the rest of the
64 // frame is.  Unfortunately, things like gcc's exception unwinding
65 // make assumptions about the locations of various parts of the frame,
66 // so we need to duplicate it exactly.
67 
68 /* Valgrind-specific parts of the signal frame */
69 struct vg_sigframe
70 {
71    /* Sanity check word. */
72    UInt magicPI;
73 
74    UInt handlerflags;	/* flags for signal handler */
75 
76 
77    /* Safely-saved version of sigNo, as described above. */
78    Int  sigNo_private;
79 
80    /* XXX This is wrong.  Surely we should store the shadow values
81       into the shadow memory behind the actual values? */
82    VexGuestX86State vex_shadow1;
83    VexGuestX86State vex_shadow2;
84 
85    /* HACK ALERT */
86    VexGuestX86State vex;
87    /* end HACK ALERT */
88 
89    /* saved signal mask to be restored when handler returns */
90    vki_sigset_t	mask;
91 
92    /* Sanity check word.  Is the highest-addressed word; do not
93       move!*/
94    UInt magicE;
95 };
96 
97 struct sigframe
98 {
99    /* Sig handler's return address */
100    Addr retaddr;
101 
102    Int  sigNo;
103    Addr psigInfo;      /* code or pointer to sigContext */
104    Addr puContext;     /* points to uContext */
105    Addr addr;          /* "secret" 4th argument */
106    Addr phandler;      /* "action" or "handler" */
107 
108    /* pointed to by puContext */
109    struct vki_ucontext uContext;
110 
111    vki_siginfo_t sigInfo;
112 
113    struct _vki_fpstate fpstate;
114 
115    struct vg_sigframe vg;
116 };
117 
118 
119 /*------------------------------------------------------------*/
120 /*--- Creating signal frames                               ---*/
121 /*------------------------------------------------------------*/
122 
123 /* Create a plausible-looking sigcontext from the thread's
124    Vex guest state.
125 */
126 static
synth_ucontext(ThreadId tid,const vki_siginfo_t * si,UWord trapno,UWord err,const vki_sigset_t * set,struct vki_ucontext * uc,struct _vki_fpstate * fpstate)127 void synth_ucontext(ThreadId tid, const vki_siginfo_t *si,
128                     UWord trapno, UWord err, const vki_sigset_t *set,
129                     struct vki_ucontext *uc, struct _vki_fpstate *fpstate)
130 {
131    ThreadState *tst = VG_(get_ThreadState)(tid);
132    struct vki_mcontext *sc = &uc->uc_mcontext;
133 
134    VG_(memset)(uc, 0, sizeof(*uc));
135 
136    uc->uc_flags = 0;
137    uc->uc_link = 0;
138    uc->uc_sigmask = *set;
139    uc->uc_stack = tst->altstack;
140    VG_(memcpy)(&sc->fpstate, fpstate, sizeof(*fpstate));
141 
142 #  define SC2(reg,REG)  sc->reg = tst->arch.vex.guest_##REG
143    SC2(gs,GS);
144    SC2(fs,FS);
145    SC2(es,ES);
146    SC2(ds,DS);
147 
148    SC2(edi,EDI);
149    SC2(esi,ESI);
150    SC2(ebp,EBP);
151    SC2(esp,ESP);
152    SC2(ebx,EBX);
153    SC2(edx,EDX);
154    SC2(ecx,ECX);
155    SC2(eax,EAX);
156 
157    SC2(eip,EIP);
158    SC2(cs,CS);
159    sc->eflags = LibVEX_GuestX86_get_eflags(&tst->arch.vex);
160    SC2(ss,SS);
161    sc->trapno = trapno;
162    sc->err = err;
163 //   sc->addr = (UWord)si->si_addr;
164    sc->fpformat = VKI_FPFMT_NODEV;
165    sc->len = sizeof(*sc);
166    sc->ownedfp = VKI_FPOWNED_NONE;
167 #  undef SC2
168 
169 //   sc->cr2 = (UInt)si->_sifields._sigfault._addr;
170 }
171 
172 
173 /* Extend the stack segment downwards if needed so as to ensure the
174    new signal frames are mapped to something.  Return a Bool
175    indicating whether or not the operation was successful.
176 */
extend(ThreadState * tst,Addr addr,SizeT size)177 static Bool extend ( ThreadState *tst, Addr addr, SizeT size )
178 {
179    ThreadId        tid = tst->tid;
180    NSegment const* stackseg = NULL;
181 
182    if (VG_(extend_stack)(tid, addr)) {
183       stackseg = VG_(am_find_nsegment)(addr);
184       if (0 && stackseg)
185 	 VG_(printf)("frame=%#lx seg=%#lx-%#lx\n",
186 		     addr, stackseg->start, stackseg->end);
187    }
188 
189    if (stackseg == NULL || !stackseg->hasR || !stackseg->hasW) {
190       VG_(message)(
191          Vg_UserMsg,
192          "Can't extend stack to %#lx during signal delivery for thread %d:\n",
193          addr, tid);
194       if (stackseg == NULL)
195          VG_(message)(Vg_UserMsg, "  no stack segment\n");
196       else
197          VG_(message)(Vg_UserMsg, "  too small or bad protection modes\n");
198 
199       /* set SIGSEGV to default handler */
200       VG_(set_default_handler)(VKI_SIGSEGV);
201       VG_(synth_fault_mapping)(tid, addr);
202 
203       /* The whole process should be about to die, since the default
204 	 action of SIGSEGV to kill the whole process. */
205       return False;
206    }
207 
208    /* For tracking memory events, indicate the entire frame has been
209       allocated. */
210    VG_TRACK( new_mem_stack_signal, addr - VG_STACK_REDZONE_SZB,
211              size + VG_STACK_REDZONE_SZB, tid );
212 
213    return True;
214 }
215 
216 
217 /* Build the Valgrind-specific part of a signal frame. */
218 
build_vg_sigframe(struct vg_sigframe * frame,ThreadState * tst,const vki_sigset_t * mask,UInt flags,Int sigNo)219 static void build_vg_sigframe(struct vg_sigframe *frame,
220 			      ThreadState *tst,
221                               const vki_sigset_t *mask,
222 			      UInt flags,
223 			      Int sigNo)
224 {
225    frame->sigNo_private = sigNo;
226    frame->magicPI       = 0x31415927;
227    frame->vex_shadow1   = tst->arch.vex_shadow1;
228    frame->vex_shadow2   = tst->arch.vex_shadow2;
229    /* HACK ALERT */
230    frame->vex           = tst->arch.vex;
231    /* end HACK ALERT */
232    frame->mask          = tst->sig_mask;
233    frame->handlerflags  = flags;
234    frame->magicE        = 0x27182818;
235 }
236 
build_sigframe(ThreadState * tst,Addr esp_top_of_frame,const vki_siginfo_t * siginfo,const struct vki_ucontext * siguc,void * handler,UInt flags,const vki_sigset_t * mask,void * restorer)237 static Addr build_sigframe(ThreadState *tst,
238                               Addr esp_top_of_frame,
239                               const vki_siginfo_t *siginfo,
240                               const struct vki_ucontext *siguc,
241                               void *handler, UInt flags,
242                               const vki_sigset_t *mask,
243                               void *restorer)
244 {
245    struct sigframe *frame;
246    Addr esp = esp_top_of_frame;
247    Int  sigNo = siginfo->si_signo;
248    UWord trapno;
249    UWord err;
250 
251    esp -= sizeof(*frame);
252    esp = VG_ROUNDDN(esp, 16);
253    frame = (struct sigframe *)esp;
254 
255    if (!extend(tst, esp, sizeof(*frame)))
256       return esp_top_of_frame;
257 
258    /* retaddr, siginfo, uContext fields are to be written */
259    VG_TRACK( pre_mem_write, Vg_CoreSignal, tst->tid, "signal handler frame",
260              esp, offsetof(struct sigframe, vg) );
261 
262    frame->sigNo = sigNo;
263    frame->retaddr = (Addr)&VG_(x86_freebsd_SUBST_FOR_sigreturn);
264    if ((flags & VKI_SA_SIGINFO) == 0)
265       frame->psigInfo = (Addr)siginfo->si_code;
266    else
267       frame->psigInfo = (Addr)&frame->sigInfo;
268    VG_(memcpy)(&frame->sigInfo, siginfo, sizeof(vki_siginfo_t));
269 
270    if (siguc != NULL) {
271       trapno = siguc->uc_mcontext.trapno;
272       err = siguc->uc_mcontext.err;
273    } else {
274       trapno = 0;
275       err = 0;
276    }
277 
278    synth_ucontext(tst->tid, siginfo, trapno, err, mask,
279                   &frame->uContext, &frame->fpstate);
280 
281    if (sigNo == VKI_SIGILL && siginfo->si_code > 0)
282       frame->sigInfo.si_addr = (void*)tst->arch.vex.guest_EIP;
283 
284    VG_TRACK( post_mem_write,  Vg_CoreSignal, tst->tid,
285              esp, offsetof(struct sigframe, vg) );
286 
287    build_vg_sigframe(&frame->vg, tst, mask, flags, sigNo);
288 
289    return esp;
290 }
291 
292 /* EXPORTED */
VG_(sigframe_create)293 void VG_(sigframe_create)( ThreadId tid,
294                            Bool on_altstack,
295                            Addr esp_top_of_frame,
296                            const vki_siginfo_t *siginfo,
297                            const struct vki_ucontext *siguc,
298                            void *handler,
299                            UInt flags,
300                            const vki_sigset_t *mask,
301                            void *restorer )
302 {
303    Addr		esp;
304    ThreadState* tst = VG_(get_ThreadState)(tid);
305 
306    esp = build_sigframe(tst, esp_top_of_frame, siginfo, siguc, handler,
307                              flags, mask, restorer);
308 
309    /* Set the thread so it will next run the handler. */
310    /* tst->m_esp  = esp;  also notify the tool we've updated ESP */
311    VG_(set_SP)(tid, esp);
312    VG_TRACK( post_reg_write, Vg_CoreSignal, tid, VG_O_STACK_PTR, sizeof(Addr));
313 
314    tst->arch.vex.guest_EIP = (Addr) handler;
315 //   tst->arch.vex.guest_EDI = (ULong) siginfo->si_signo;
316    /* This thread needs to be marked runnable, but we leave that the
317       caller to do. */
318 
319    if (0)
320       VG_(printf)("pushed signal frame; %%ESP now = %#lx, "
321                   "next %%EIP = %#x, status=%d\n",
322 		  esp, tst->arch.vex.guest_EIP, tst->status);
323 }
324 
325 
326 /*------------------------------------------------------------*/
327 /*--- Destroying signal frames                             ---*/
328 /*------------------------------------------------------------*/
329 
330 /* Return False and don't do anything, just set the client to take a
331    segfault, if it looks like the frame is corrupted. */
332 static
restore_vg_sigframe(ThreadState * tst,struct vg_sigframe * frame,Int * sigNo)333 Bool restore_vg_sigframe ( ThreadState *tst,
334                            struct vg_sigframe *frame, Int *sigNo )
335 {
336    if (frame->magicPI != 0x31415927 ||
337        frame->magicE  != 0x27182818) {
338       VG_(message)(Vg_UserMsg, "Thread %d return signal frame "
339                                "corrupted.  Killing process.", tst->tid);
340       VG_(set_default_handler)(VKI_SIGSEGV);
341       VG_(synth_fault)(tst->tid);
342       *sigNo = VKI_SIGSEGV;
343       return False;
344    }
345    tst->sig_mask         = frame->mask;
346    tst->tmp_sig_mask     = frame->mask;
347    tst->arch.vex_shadow1 = frame->vex_shadow1;
348    tst->arch.vex_shadow2 = frame->vex_shadow2;
349    /* HACK ALERT */
350    tst->arch.vex         = frame->vex;
351    /* end HACK ALERT */
352    *sigNo                = frame->sigNo_private;
353    return True;
354 }
355 
356 static
restore_sigcontext(ThreadState * tst,struct vki_mcontext * sc,struct _vki_fpstate * fpstate)357 void restore_sigcontext( ThreadState *tst,
358                          struct vki_mcontext *sc,
359                          struct _vki_fpstate *fpstate )
360 {
361    tst->arch.vex.guest_EAX     = sc->eax;
362    tst->arch.vex.guest_ECX     = sc->ecx;
363    tst->arch.vex.guest_EDX     = sc->edx;
364    tst->arch.vex.guest_EBX     = sc->ebx;
365    tst->arch.vex.guest_EBP     = sc->ebp;
366    tst->arch.vex.guest_ESP     = sc->esp;
367    tst->arch.vex.guest_ESI     = sc->esi;
368    tst->arch.vex.guest_EDI     = sc->edi;
369 //::    tst->arch.vex.guest_eflags  = sc->eflags;
370    tst->arch.vex.guest_EIP     = sc->eip;
371    tst->arch.vex.guest_CS      = sc->cs;
372    tst->arch.vex.guest_SS      = sc->ss;
373    tst->arch.vex.guest_DS      = sc->ds;
374    tst->arch.vex.guest_ES      = sc->es;
375    tst->arch.vex.guest_FS      = sc->fs;
376    tst->arch.vex.guest_GS      = sc->gs;
377    VG_(memcpy)(fpstate, &sc->fpstate, sizeof(*fpstate));
378 }
379 
380 
381 static
restore_sigframe(ThreadState * tst,struct sigframe * frame,Int * sigNo)382 SizeT restore_sigframe ( ThreadState *tst,
383                          struct sigframe *frame, Int *sigNo )
384 {
385    if (restore_vg_sigframe(tst, &frame->vg, sigNo))
386       restore_sigcontext(tst, &frame->uContext.uc_mcontext, &frame->fpstate);
387 
388    return sizeof(*frame);
389 }
390 
391 /* EXPORTED */
VG_(sigframe_destroy)392 void VG_(sigframe_destroy)( ThreadId tid )
393 {
394    Addr          esp;
395    ThreadState*  tst;
396    SizeT	 size;
397    Int		 sigNo;
398 
399    tst = VG_(get_ThreadState)(tid);
400 
401    /* Correctly reestablish the frame base address. */
402    esp   = tst->arch.vex.guest_ESP;
403    esp  += 8; /* Clean up stack from argument/ret passed to sigreturn(2) */
404 
405    size = restore_sigframe(tst, (struct sigframe *)esp, &sigNo);
406 
407    VG_TRACK( die_mem_stack_signal, esp - VG_STACK_REDZONE_SZB,
408              size + VG_STACK_REDZONE_SZB );
409 
410    if (VG_(clo_trace_signals))
411       VG_(message)(
412          Vg_DebugMsg,
413          "VG_(signal_return) (thread %d): EIP=%#x\n",
414          tid, tst->arch.vex.guest_EIP);
415 
416    /* tell the tools */
417    VG_TRACK( post_deliver_signal, tid, sigNo );
418 }
419 
420 #endif // defined(VGP_x86_freebsd)
421 
422 /*--------------------------------------------------------------------*/
423 /*--- end                                                          ---*/
424 /*--------------------------------------------------------------------*/
425