1 /* Copyright (c) 2010-2012, 2014-2015. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
8 * win32-ucontext: Unix ucontext_t operations on Windows platforms
9 * Copyright(C) 2007 Panagiotis E. Hadjidoukas
11 * Contact Email: phadjido@cs.uoi.gr, xdoukas@ceid.upatras.gr
13 * win32-ucontext is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2 of the License, or (at your option) any later version.
18 * win32-ucontext is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with SimGrid in the file LICENSE-LGPL-2.1;
25 * if not, write to the Free Software Foundation, Inc.,
26 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
29 #include "xbt/win32_ucontext.h"
31 int getcontext(ucontext_t * ucp)
35 /* Retrieve the full machine context */
36 ucp->uc_mcontext.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
37 ret = GetThreadContext(GetCurrentThread(), &ucp->uc_mcontext);
38 return (ret == 0) ? -1 : 0;
41 int setcontext(const ucontext_t * ucp)
45 /* Restore the full machine context (already set) */
46 ret = SetThreadContext(GetCurrentThread(), &ucp->uc_mcontext);
47 return (ret == 0) ? -1 : 0;
50 int makecontext(ucontext_t * ucp, void (*func) (), int argc, ...)
56 /* Stack grows down */
57 sp = (char *) (size_t) ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size;
59 /* Reserve stack space for the arguments (maximum possible: argc*(8 bytes per argument)) */
60 sp -= argc * sizeof(void*);
61 if (sp < (char *) ucp->uc_stack.ss_sp) {
67 /* Set the instruction and the stack pointer */
68 #if defined(_I_X86_) || defined(__i386) || defined(__i386__) || defined(_M_IX86)
69 ucp->uc_mcontext.Eip = (DWORD) func;
70 ucp->uc_mcontext.Esp = (DWORD) sp - sizeof(void*);
71 #elif defined(_IA64_) || defined(__ia64) || defined(__ia64__)
73 #elif defined _AMD64_ || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)
74 ucp->uc_mcontext.Rip = (DWORD64) func;
75 ucp->uc_mcontext.Rsp = (DWORD64) sp - sizeof(void*);
77 #error "No architecture defined for Windows build."
80 /* Save/Restore the full machine context */
81 ucp->uc_mcontext.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
83 /* Copy the arguments */
85 for (i = 0; i < argc; i++) {
86 memcpy(sp, ap, sizeof(void*));
94 int swapcontext(ucontext_t * oucp, const ucontext_t * ucp)
97 if ((oucp == NULL) || (ucp == NULL)) {
102 ret = getcontext(oucp);
104 ret = setcontext(ucp);