process.cc revision 9026:971f35a65a00
16019Shines@cs.fsu.edu/*
26019Shines@cs.fsu.edu * Copyright (c) 2007 The Hewlett-Packard Development Company
37100Sgblack@eecs.umich.edu * All rights reserved.
47100Sgblack@eecs.umich.edu *
57100Sgblack@eecs.umich.edu * The license below extends only to copyright in the software and shall
67100Sgblack@eecs.umich.edu * not be construed as granting a license to any other intellectual
77100Sgblack@eecs.umich.edu * property including but not limited to intellectual property relating
87100Sgblack@eecs.umich.edu * to a hardware implementation of the functionality of the software
97100Sgblack@eecs.umich.edu * licensed hereunder.  You may use the software subject to the license
107100Sgblack@eecs.umich.edu * terms below provided that you ensure that this notice is replicated
117100Sgblack@eecs.umich.edu * unmodified and in its entirety in all distributions of the software,
127100Sgblack@eecs.umich.edu * modified or unmodified, in source code or in binary form.
137100Sgblack@eecs.umich.edu *
147100Sgblack@eecs.umich.edu * Copyright (c) 2003-2006 The Regents of The University of Michigan
156019Shines@cs.fsu.edu * All rights reserved.
166019Shines@cs.fsu.edu *
176019Shines@cs.fsu.edu * Redistribution and use in source and binary forms, with or without
186019Shines@cs.fsu.edu * modification, are permitted provided that the following conditions are
196019Shines@cs.fsu.edu * met: redistributions of source code must retain the above copyright
206019Shines@cs.fsu.edu * notice, this list of conditions and the following disclaimer;
216019Shines@cs.fsu.edu * redistributions in binary form must reproduce the above copyright
226019Shines@cs.fsu.edu * notice, this list of conditions and the following disclaimer in the
236019Shines@cs.fsu.edu * documentation and/or other materials provided with the distribution;
246019Shines@cs.fsu.edu * neither the name of the copyright holders nor the names of its
256019Shines@cs.fsu.edu * contributors may be used to endorse or promote products derived from
266019Shines@cs.fsu.edu * this software without specific prior written permission.
276019Shines@cs.fsu.edu *
286019Shines@cs.fsu.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
296019Shines@cs.fsu.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
306019Shines@cs.fsu.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
316019Shines@cs.fsu.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
326019Shines@cs.fsu.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
336019Shines@cs.fsu.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
346019Shines@cs.fsu.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
356019Shines@cs.fsu.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
366019Shines@cs.fsu.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
376019Shines@cs.fsu.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
386019Shines@cs.fsu.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
396019Shines@cs.fsu.edu *
406019Shines@cs.fsu.edu * Authors: Gabe Black
416019Shines@cs.fsu.edu *          Ali Saidi
426757SAli.Saidi@ARM.com */
436019Shines@cs.fsu.edu
446019Shines@cs.fsu.edu#include "arch/x86/regs/misc.hh"
456019Shines@cs.fsu.edu#include "arch/x86/regs/segment.hh"
466019Shines@cs.fsu.edu#include "arch/x86/isa_traits.hh"
476019Shines@cs.fsu.edu#include "arch/x86/process.hh"
486019Shines@cs.fsu.edu#include "arch/x86/types.hh"
496019Shines@cs.fsu.edu#include "base/loader/elf_object.hh"
509022Sgblack@eecs.umich.edu#include "base/loader/object_file.hh"
516019Shines@cs.fsu.edu#include "base/misc.hh"
527170Sgblack@eecs.umich.edu#include "base/trace.hh"
536253Sgblack@eecs.umich.edu#include "cpu/thread_context.hh"
547202Sgblack@eecs.umich.edu#include "debug/Stack.hh"
556253Sgblack@eecs.umich.edu#include "mem/page_table.hh"
566253Sgblack@eecs.umich.edu#include "sim/process_impl.hh"
577396Sgblack@eecs.umich.edu#include "sim/syscall_emul.hh"
588745Sgblack@eecs.umich.edu#include "sim/system.hh"
597405SAli.Saidi@ARM.com
608782Sgblack@eecs.umich.eduusing namespace std;
618782Sgblack@eecs.umich.eduusing namespace X86ISA;
628782Sgblack@eecs.umich.edu
637259Sgblack@eecs.umich.edustatic const int ArgumentReg[] = {
648757Sgblack@eecs.umich.edu    INTREG_RDI,
658782Sgblack@eecs.umich.edu    INTREG_RSI,
668757Sgblack@eecs.umich.edu    INTREG_RDX,
678777Sgblack@eecs.umich.edu    //This argument register is r10 for syscalls and rcx for C.
688782Sgblack@eecs.umich.edu    INTREG_R10W,
698756Sgblack@eecs.umich.edu    //INTREG_RCX,
706019Shines@cs.fsu.edu    INTREG_R8W,
716757SAli.Saidi@ARM.com    INTREG_R9W
728757Sgblack@eecs.umich.edu};
736019Shines@cs.fsu.edustatic const int NumArgumentRegs = sizeof(ArgumentReg) / sizeof(const int);
748745Sgblack@eecs.umich.edustatic const int ArgumentReg32[] = {
759384SAndreas.Sandberg@arm.com    INTREG_EBX,
766397Sgblack@eecs.umich.edu    INTREG_ECX,
778782Sgblack@eecs.umich.edu    INTREG_EDX,
786019Shines@cs.fsu.edu    INTREG_ESI,
796397Sgblack@eecs.umich.edu    INTREG_EDI,
808335Snate@binkert.org};
819023Sgblack@eecs.umich.edustatic const int NumArgumentRegs32 = sizeof(ArgumentReg) / sizeof(const int);
829023Sgblack@eecs.umich.edu
838335Snate@binkert.orgX86LiveProcess::X86LiveProcess(LiveProcessParams * params, ObjectFile *objFile,
846019Shines@cs.fsu.edu        SyscallDesc *_syscallDescs, int _numSyscallDescs) :
856019Shines@cs.fsu.edu    LiveProcess(params, objFile), syscallDescs(_syscallDescs),
866019Shines@cs.fsu.edu    numSyscallDescs(_numSyscallDescs)
876019Shines@cs.fsu.edu{
886019Shines@cs.fsu.edu    brk_point = objFile->dataBase() + objFile->dataSize() + objFile->bssSize();
896019Shines@cs.fsu.edu    brk_point = roundUp(brk_point, VMPageSize);
906019Shines@cs.fsu.edu}
916019Shines@cs.fsu.edu
92X86_64LiveProcess::X86_64LiveProcess(LiveProcessParams *params,
93        ObjectFile *objFile, SyscallDesc *_syscallDescs,
94        int _numSyscallDescs) :
95    X86LiveProcess(params, objFile, _syscallDescs, _numSyscallDescs)
96{
97
98    vsyscallPage.base = 0xffffffffff600000ULL;
99    vsyscallPage.size = VMPageSize;
100    vsyscallPage.vtimeOffset = 0x400;
101    vsyscallPage.vgettimeofdayOffset = 0x410;
102
103    // Set up stack. On X86_64 Linux, stack goes from the top of memory
104    // downward, less the hole for the kernel address space plus one page
105    // for undertermined purposes.
106    stack_base = (Addr)0x7FFFFFFFF000ULL;
107
108    // Set pointer for next thread stack.  Reserve 8M for main stack.
109    next_thread_stack_base = stack_base - (8 * 1024 * 1024);
110
111    // Set up region for mmaps. This was determined empirically and may not
112    // always be correct.
113    mmap_start = mmap_end = (Addr)0x2aaaaaaab000ULL;
114}
115
116void
117I386LiveProcess::syscall(int64_t callnum, ThreadContext *tc)
118{
119    TheISA::PCState pc = tc->pcState();
120    Addr eip = pc.pc();
121    if (eip >= vsyscallPage.base &&
122            eip < vsyscallPage.base + vsyscallPage.size) {
123        pc.npc(vsyscallPage.base + vsyscallPage.vsysexitOffset);
124        tc->pcState(pc);
125    }
126    X86LiveProcess::syscall(callnum, tc);
127}
128
129
130I386LiveProcess::I386LiveProcess(LiveProcessParams *params,
131        ObjectFile *objFile, SyscallDesc *_syscallDescs,
132        int _numSyscallDescs) :
133    X86LiveProcess(params, objFile, _syscallDescs, _numSyscallDescs)
134{
135    _gdtStart = ULL(0xffffd000);
136    _gdtSize = VMPageSize;
137
138    vsyscallPage.base = 0xffffe000ULL;
139    vsyscallPage.size = VMPageSize;
140    vsyscallPage.vsyscallOffset = 0x400;
141    vsyscallPage.vsysexitOffset = 0x410;
142
143    stack_base = _gdtStart;
144
145    // Set pointer for next thread stack.  Reserve 8M for main stack.
146    next_thread_stack_base = stack_base - (8 * 1024 * 1024);
147
148    // Set up region for mmaps. This was determined empirically and may not
149    // always be correct.
150    mmap_start = mmap_end = (Addr)0xf7ffe000ULL;
151}
152
153SyscallDesc*
154X86LiveProcess::getDesc(int callnum)
155{
156    if (callnum < 0 || callnum >= numSyscallDescs)
157        return NULL;
158    return &syscallDescs[callnum];
159}
160
161void
162X86_64LiveProcess::initState()
163{
164    X86LiveProcess::initState();
165
166    argsInit(sizeof(uint64_t), VMPageSize);
167
168       // Set up the vsyscall page for this process.
169    allocateMem(vsyscallPage.base, vsyscallPage.size);
170    uint8_t vtimeBlob[] = {
171        0x48,0xc7,0xc0,0xc9,0x00,0x00,0x00,    // mov    $0xc9,%rax
172        0x0f,0x05,                             // syscall
173        0xc3                                   // retq
174    };
175    initVirtMem.writeBlob(vsyscallPage.base + vsyscallPage.vtimeOffset,
176            vtimeBlob, sizeof(vtimeBlob));
177
178    uint8_t vgettimeofdayBlob[] = {
179        0x48,0xc7,0xc0,0x60,0x00,0x00,0x00,    // mov    $0x60,%rax
180        0x0f,0x05,                             // syscall
181        0xc3                                   // retq
182    };
183    initVirtMem.writeBlob(vsyscallPage.base + vsyscallPage.vgettimeofdayOffset,
184            vgettimeofdayBlob, sizeof(vgettimeofdayBlob));
185
186    for (int i = 0; i < contextIds.size(); i++) {
187        ThreadContext * tc = system->getThreadContext(contextIds[i]);
188
189        SegAttr dataAttr = 0;
190        dataAttr.dpl = 3;
191        dataAttr.unusable = 0;
192        dataAttr.defaultSize = 1;
193        dataAttr.longMode = 1;
194        dataAttr.avl = 0;
195        dataAttr.granularity = 1;
196        dataAttr.present = 1;
197        dataAttr.type = 3;
198        dataAttr.writable = 1;
199        dataAttr.readable = 1;
200        dataAttr.expandDown = 0;
201        dataAttr.system = 1;
202
203        //Initialize the segment registers.
204        for(int seg = 0; seg < NUM_SEGMENTREGS; seg++) {
205            tc->setMiscRegNoEffect(MISCREG_SEG_BASE(seg), 0);
206            tc->setMiscRegNoEffect(MISCREG_SEG_EFF_BASE(seg), 0);
207            tc->setMiscRegNoEffect(MISCREG_SEG_ATTR(seg), dataAttr);
208        }
209
210        SegAttr csAttr = 0;
211        csAttr.dpl = 3;
212        csAttr.unusable = 0;
213        csAttr.defaultSize = 0;
214        csAttr.longMode = 1;
215        csAttr.avl = 0;
216        csAttr.granularity = 1;
217        csAttr.present = 1;
218        csAttr.type = 10;
219        csAttr.writable = 0;
220        csAttr.readable = 1;
221        csAttr.expandDown = 0;
222        csAttr.system = 1;
223
224        tc->setMiscRegNoEffect(MISCREG_CS_ATTR, csAttr);
225
226        Efer efer = 0;
227        efer.sce = 1; // Enable system call extensions.
228        efer.lme = 1; // Enable long mode.
229        efer.lma = 1; // Activate long mode.
230        efer.nxe = 1; // Enable nx support.
231        efer.svme = 0; // Disable svm support for now. It isn't implemented.
232        efer.ffxsr = 1; // Turn on fast fxsave and fxrstor.
233        tc->setMiscReg(MISCREG_EFER, efer);
234
235        //Set up the registers that describe the operating mode.
236        CR0 cr0 = 0;
237        cr0.pg = 1; // Turn on paging.
238        cr0.cd = 0; // Don't disable caching.
239        cr0.nw = 0; // This is bit is defined to be ignored.
240        cr0.am = 0; // No alignment checking
241        cr0.wp = 0; // Supervisor mode can write read only pages
242        cr0.ne = 1;
243        cr0.et = 1; // This should always be 1
244        cr0.ts = 0; // We don't do task switching, so causing fp exceptions
245                    // would be pointless.
246        cr0.em = 0; // Allow x87 instructions to execute natively.
247        cr0.mp = 1; // This doesn't really matter, but the manual suggests
248                    // setting it to one.
249        cr0.pe = 1; // We're definitely in protected mode.
250        tc->setMiscReg(MISCREG_CR0, cr0);
251
252        tc->setMiscReg(MISCREG_MXCSR, 0x1f80);
253    }
254}
255
256void
257I386LiveProcess::initState()
258{
259    X86LiveProcess::initState();
260
261    argsInit(sizeof(uint32_t), VMPageSize);
262
263    /*
264     * Set up a GDT for this process. The whole GDT wouldn't really be for
265     * this process, but the only parts we care about are.
266     */
267    allocateMem(_gdtStart, _gdtSize);
268    uint64_t zero = 0;
269    assert(_gdtSize % sizeof(zero) == 0);
270    for (Addr gdtCurrent = _gdtStart;
271            gdtCurrent < _gdtStart + _gdtSize; gdtCurrent += sizeof(zero)) {
272        initVirtMem.write(gdtCurrent, zero);
273    }
274
275    // Set up the vsyscall page for this process.
276    allocateMem(vsyscallPage.base, vsyscallPage.size);
277    uint8_t vsyscallBlob[] = {
278        0x51,       // push %ecx
279        0x52,       // push %edp
280        0x55,       // push %ebp
281        0x89, 0xe5, // mov %esp, %ebp
282        0x0f, 0x34  // sysenter
283    };
284    initVirtMem.writeBlob(vsyscallPage.base + vsyscallPage.vsyscallOffset,
285            vsyscallBlob, sizeof(vsyscallBlob));
286
287    uint8_t vsysexitBlob[] = {
288        0x5d,       // pop %ebp
289        0x5a,       // pop %edx
290        0x59,       // pop %ecx
291        0xc3        // ret
292    };
293    initVirtMem.writeBlob(vsyscallPage.base + vsyscallPage.vsysexitOffset,
294            vsysexitBlob, sizeof(vsysexitBlob));
295
296    for (int i = 0; i < contextIds.size(); i++) {
297        ThreadContext * tc = system->getThreadContext(contextIds[i]);
298
299        SegAttr dataAttr = 0;
300        dataAttr.dpl = 3;
301        dataAttr.unusable = 0;
302        dataAttr.defaultSize = 1;
303        dataAttr.longMode = 0;
304        dataAttr.avl = 0;
305        dataAttr.granularity = 1;
306        dataAttr.present = 1;
307        dataAttr.type = 3;
308        dataAttr.writable = 1;
309        dataAttr.readable = 1;
310        dataAttr.expandDown = 0;
311        dataAttr.system = 1;
312
313        //Initialize the segment registers.
314        for(int seg = 0; seg < NUM_SEGMENTREGS; seg++) {
315            tc->setMiscRegNoEffect(MISCREG_SEG_BASE(seg), 0);
316            tc->setMiscRegNoEffect(MISCREG_SEG_EFF_BASE(seg), 0);
317            tc->setMiscRegNoEffect(MISCREG_SEG_ATTR(seg), dataAttr);
318            tc->setMiscRegNoEffect(MISCREG_SEG_SEL(seg), 0xB);
319            tc->setMiscRegNoEffect(MISCREG_SEG_LIMIT(seg), (uint32_t)(-1));
320        }
321
322        SegAttr csAttr = 0;
323        csAttr.dpl = 3;
324        csAttr.unusable = 0;
325        csAttr.defaultSize = 1;
326        csAttr.longMode = 0;
327        csAttr.avl = 0;
328        csAttr.granularity = 1;
329        csAttr.present = 1;
330        csAttr.type = 0xa;
331        csAttr.writable = 0;
332        csAttr.readable = 1;
333        csAttr.expandDown = 0;
334        csAttr.system = 1;
335
336        tc->setMiscRegNoEffect(MISCREG_CS_ATTR, csAttr);
337
338        tc->setMiscRegNoEffect(MISCREG_TSG_BASE, _gdtStart);
339        tc->setMiscRegNoEffect(MISCREG_TSG_EFF_BASE, _gdtStart);
340        tc->setMiscRegNoEffect(MISCREG_TSG_LIMIT, _gdtStart + _gdtSize - 1);
341
342        // Set the LDT selector to 0 to deactivate it.
343        tc->setMiscRegNoEffect(MISCREG_TSL, 0);
344
345        Efer efer = 0;
346        efer.sce = 1; // Enable system call extensions.
347        efer.lme = 1; // Enable long mode.
348        efer.lma = 0; // Deactivate long mode.
349        efer.nxe = 1; // Enable nx support.
350        efer.svme = 0; // Disable svm support for now. It isn't implemented.
351        efer.ffxsr = 1; // Turn on fast fxsave and fxrstor.
352        tc->setMiscReg(MISCREG_EFER, efer);
353
354        //Set up the registers that describe the operating mode.
355        CR0 cr0 = 0;
356        cr0.pg = 1; // Turn on paging.
357        cr0.cd = 0; // Don't disable caching.
358        cr0.nw = 0; // This is bit is defined to be ignored.
359        cr0.am = 0; // No alignment checking
360        cr0.wp = 0; // Supervisor mode can write read only pages
361        cr0.ne = 1;
362        cr0.et = 1; // This should always be 1
363        cr0.ts = 0; // We don't do task switching, so causing fp exceptions
364                    // would be pointless.
365        cr0.em = 0; // Allow x87 instructions to execute natively.
366        cr0.mp = 1; // This doesn't really matter, but the manual suggests
367                    // setting it to one.
368        cr0.pe = 1; // We're definitely in protected mode.
369        tc->setMiscReg(MISCREG_CR0, cr0);
370
371        tc->setMiscReg(MISCREG_MXCSR, 0x1f80);
372    }
373}
374
375template<class IntType>
376void
377X86LiveProcess::argsInit(int pageSize,
378        std::vector<AuxVector<IntType> > extraAuxvs)
379{
380    int intSize = sizeof(IntType);
381
382    typedef AuxVector<IntType> auxv_t;
383    std::vector<auxv_t> auxv = extraAuxvs;
384
385    string filename;
386    if(argv.size() < 1)
387        filename = "";
388    else
389        filename = argv[0];
390
391    //We want 16 byte alignment
392    uint64_t align = 16;
393
394    // load object file into target memory
395    objFile->loadSections(initVirtMem);
396
397    enum X86CpuFeature {
398        X86_OnboardFPU = 1 << 0,
399        X86_VirtualModeExtensions = 1 << 1,
400        X86_DebuggingExtensions = 1 << 2,
401        X86_PageSizeExtensions = 1 << 3,
402
403        X86_TimeStampCounter = 1 << 4,
404        X86_ModelSpecificRegisters = 1 << 5,
405        X86_PhysicalAddressExtensions = 1 << 6,
406        X86_MachineCheckExtensions = 1 << 7,
407
408        X86_CMPXCHG8Instruction = 1 << 8,
409        X86_OnboardAPIC = 1 << 9,
410        X86_SYSENTER_SYSEXIT = 1 << 11,
411
412        X86_MemoryTypeRangeRegisters = 1 << 12,
413        X86_PageGlobalEnable = 1 << 13,
414        X86_MachineCheckArchitecture = 1 << 14,
415        X86_CMOVInstruction = 1 << 15,
416
417        X86_PageAttributeTable = 1 << 16,
418        X86_36BitPSEs = 1 << 17,
419        X86_ProcessorSerialNumber = 1 << 18,
420        X86_CLFLUSHInstruction = 1 << 19,
421
422        X86_DebugTraceStore = 1 << 21,
423        X86_ACPIViaMSR = 1 << 22,
424        X86_MultimediaExtensions = 1 << 23,
425
426        X86_FXSAVE_FXRSTOR = 1 << 24,
427        X86_StreamingSIMDExtensions = 1 << 25,
428        X86_StreamingSIMDExtensions2 = 1 << 26,
429        X86_CPUSelfSnoop = 1 << 27,
430
431        X86_HyperThreading = 1 << 28,
432        X86_AutomaticClockControl = 1 << 29,
433        X86_IA64Processor = 1 << 30
434    };
435
436    //Setup the auxilliary vectors. These will already have endian conversion.
437    //Auxilliary vectors are loaded only for elf formatted executables.
438    ElfObject * elfObject = dynamic_cast<ElfObject *>(objFile);
439    if(elfObject)
440    {
441        uint64_t features =
442            X86_OnboardFPU |
443            X86_VirtualModeExtensions |
444            X86_DebuggingExtensions |
445            X86_PageSizeExtensions |
446            X86_TimeStampCounter |
447            X86_ModelSpecificRegisters |
448            X86_PhysicalAddressExtensions |
449            X86_MachineCheckExtensions |
450            X86_CMPXCHG8Instruction |
451            X86_OnboardAPIC |
452            X86_SYSENTER_SYSEXIT |
453            X86_MemoryTypeRangeRegisters |
454            X86_PageGlobalEnable |
455            X86_MachineCheckArchitecture |
456            X86_CMOVInstruction |
457            X86_PageAttributeTable |
458            X86_36BitPSEs |
459//            X86_ProcessorSerialNumber |
460            X86_CLFLUSHInstruction |
461//            X86_DebugTraceStore |
462//            X86_ACPIViaMSR |
463            X86_MultimediaExtensions |
464            X86_FXSAVE_FXRSTOR |
465            X86_StreamingSIMDExtensions |
466            X86_StreamingSIMDExtensions2 |
467//            X86_CPUSelfSnoop |
468//            X86_HyperThreading |
469//            X86_AutomaticClockControl |
470//            X86_IA64Processor |
471            0;
472
473        //Bits which describe the system hardware capabilities
474        //XXX Figure out what these should be
475        auxv.push_back(auxv_t(M5_AT_HWCAP, features));
476        //The system page size
477        auxv.push_back(auxv_t(M5_AT_PAGESZ, X86ISA::VMPageSize));
478        //Frequency at which times() increments
479        //Defined to be 100 in the kernel source.
480        auxv.push_back(auxv_t(M5_AT_CLKTCK, 100));
481        // For statically linked executables, this is the virtual address of the
482        // program header tables if they appear in the executable image
483        auxv.push_back(auxv_t(M5_AT_PHDR, elfObject->programHeaderTable()));
484        // This is the size of a program header entry from the elf file.
485        auxv.push_back(auxv_t(M5_AT_PHENT, elfObject->programHeaderSize()));
486        // This is the number of program headers from the original elf file.
487        auxv.push_back(auxv_t(M5_AT_PHNUM, elfObject->programHeaderCount()));
488        //This is the address of the elf "interpreter", It should be set
489        //to 0 for regular executables. It should be something else
490        //(not sure what) for dynamic libraries.
491        auxv.push_back(auxv_t(M5_AT_BASE, 0));
492
493        //XXX Figure out what this should be.
494        auxv.push_back(auxv_t(M5_AT_FLAGS, 0));
495        //The entry point to the program
496        auxv.push_back(auxv_t(M5_AT_ENTRY, objFile->entryPoint()));
497        //Different user and group IDs
498        auxv.push_back(auxv_t(M5_AT_UID, uid()));
499        auxv.push_back(auxv_t(M5_AT_EUID, euid()));
500        auxv.push_back(auxv_t(M5_AT_GID, gid()));
501        auxv.push_back(auxv_t(M5_AT_EGID, egid()));
502        //Whether to enable "secure mode" in the executable
503        auxv.push_back(auxv_t(M5_AT_SECURE, 0));
504        //The address of 16 "random" bytes.
505        auxv.push_back(auxv_t(M5_AT_RANDOM, 0));
506        //The name of the program
507        auxv.push_back(auxv_t(M5_AT_EXECFN, 0));
508        //The platform string
509        auxv.push_back(auxv_t(M5_AT_PLATFORM, 0));
510    }
511
512    //Figure out how big the initial stack needs to be
513
514    // A sentry NULL void pointer at the top of the stack.
515    int sentry_size = intSize;
516
517    //This is the name of the file which is present on the initial stack
518    //It's purpose is to let the user space linker examine the original file.
519    int file_name_size = filename.size() + 1;
520
521    const int numRandomBytes = 16;
522    int aux_data_size = numRandomBytes;
523
524    string platform = "x86_64";
525    aux_data_size += platform.size() + 1;
526
527    int env_data_size = 0;
528    for (int i = 0; i < envp.size(); ++i) {
529        env_data_size += envp[i].size() + 1;
530    }
531    int arg_data_size = 0;
532    for (int i = 0; i < argv.size(); ++i) {
533        arg_data_size += argv[i].size() + 1;
534    }
535
536    //The info_block needs to be padded so it's size is a multiple of the
537    //alignment mask. Also, it appears that there needs to be at least some
538    //padding, so if the size is already a multiple, we need to increase it
539    //anyway.
540    int base_info_block_size =
541        sentry_size + file_name_size + env_data_size + arg_data_size;
542
543    int info_block_size = roundUp(base_info_block_size, align);
544
545    int info_block_padding = info_block_size - base_info_block_size;
546
547    //Each auxilliary vector is two 8 byte words
548    int aux_array_size = intSize * 2 * (auxv.size() + 1);
549
550    int envp_array_size = intSize * (envp.size() + 1);
551    int argv_array_size = intSize * (argv.size() + 1);
552
553    int argc_size = intSize;
554
555    //Figure out the size of the contents of the actual initial frame
556    int frame_size =
557        aux_array_size +
558        envp_array_size +
559        argv_array_size +
560        argc_size;
561
562    //There needs to be padding after the auxiliary vector data so that the
563    //very bottom of the stack is aligned properly.
564    int partial_size = frame_size + aux_data_size;
565    int aligned_partial_size = roundUp(partial_size, align);
566    int aux_padding = aligned_partial_size - partial_size;
567
568    int space_needed =
569        info_block_size +
570        aux_data_size +
571        aux_padding +
572        frame_size;
573
574    stack_min = stack_base - space_needed;
575    stack_min = roundDown(stack_min, align);
576    stack_size = stack_base - stack_min;
577
578    // map memory
579    allocateMem(roundDown(stack_min, pageSize), roundUp(stack_size, pageSize));
580
581    // map out initial stack contents
582    IntType sentry_base = stack_base - sentry_size;
583    IntType file_name_base = sentry_base - file_name_size;
584    IntType env_data_base = file_name_base - env_data_size;
585    IntType arg_data_base = env_data_base - arg_data_size;
586    IntType aux_data_base = arg_data_base - info_block_padding - aux_data_size;
587    IntType auxv_array_base = aux_data_base - aux_array_size - aux_padding;
588    IntType envp_array_base = auxv_array_base - envp_array_size;
589    IntType argv_array_base = envp_array_base - argv_array_size;
590    IntType argc_base = argv_array_base - argc_size;
591
592    DPRINTF(Stack, "The addresses of items on the initial stack:\n");
593    DPRINTF(Stack, "0x%x - file name\n", file_name_base);
594    DPRINTF(Stack, "0x%x - env data\n", env_data_base);
595    DPRINTF(Stack, "0x%x - arg data\n", arg_data_base);
596    DPRINTF(Stack, "0x%x - aux data\n", aux_data_base);
597    DPRINTF(Stack, "0x%x - auxv array\n", auxv_array_base);
598    DPRINTF(Stack, "0x%x - envp array\n", envp_array_base);
599    DPRINTF(Stack, "0x%x - argv array\n", argv_array_base);
600    DPRINTF(Stack, "0x%x - argc \n", argc_base);
601    DPRINTF(Stack, "0x%x - stack min\n", stack_min);
602
603    // write contents to stack
604
605    // figure out argc
606    IntType argc = argv.size();
607    IntType guestArgc = X86ISA::htog(argc);
608
609    //Write out the sentry void *
610    IntType sentry_NULL = 0;
611    initVirtMem.writeBlob(sentry_base,
612            (uint8_t*)&sentry_NULL, sentry_size);
613
614    //Write the file name
615    initVirtMem.writeString(file_name_base, filename.c_str());
616
617    //Fix up the aux vectors which point to data
618    assert(auxv[auxv.size() - 3].a_type == M5_AT_RANDOM);
619    auxv[auxv.size() - 3].a_val = aux_data_base;
620    assert(auxv[auxv.size() - 2].a_type == M5_AT_EXECFN);
621    auxv[auxv.size() - 2].a_val = argv_array_base;
622    assert(auxv[auxv.size() - 1].a_type == M5_AT_PLATFORM);
623    auxv[auxv.size() - 1].a_val = aux_data_base + numRandomBytes;
624
625    //Copy the aux stuff
626    for(int x = 0; x < auxv.size(); x++)
627    {
628        initVirtMem.writeBlob(auxv_array_base + x * 2 * intSize,
629                (uint8_t*)&(auxv[x].a_type), intSize);
630        initVirtMem.writeBlob(auxv_array_base + (x * 2 + 1) * intSize,
631                (uint8_t*)&(auxv[x].a_val), intSize);
632    }
633    //Write out the terminating zeroed auxilliary vector
634    const uint64_t zero = 0;
635    initVirtMem.writeBlob(auxv_array_base + 2 * intSize * auxv.size(),
636            (uint8_t*)&zero, 2 * intSize);
637
638    initVirtMem.writeString(aux_data_base, platform.c_str());
639
640    copyStringArray(envp, envp_array_base, env_data_base, initVirtMem);
641    copyStringArray(argv, argv_array_base, arg_data_base, initVirtMem);
642
643    initVirtMem.writeBlob(argc_base, (uint8_t*)&guestArgc, intSize);
644
645    ThreadContext *tc = system->getThreadContext(contextIds[0]);
646    //Set the stack pointer register
647    tc->setIntReg(StackPointerReg, stack_min);
648
649    // There doesn't need to be any segment base added in since we're dealing
650    // with the flat segmentation model.
651    tc->pcState(objFile->entryPoint());
652
653    //Align the "stack_min" to a page boundary.
654    stack_min = roundDown(stack_min, pageSize);
655
656//    num_processes++;
657}
658
659void
660X86_64LiveProcess::argsInit(int intSize, int pageSize)
661{
662    std::vector<AuxVector<uint64_t> > extraAuxvs;
663    extraAuxvs.push_back(AuxVector<uint64_t>(M5_AT_SYSINFO_EHDR,
664                vsyscallPage.base));
665    X86LiveProcess::argsInit<uint64_t>(pageSize, extraAuxvs);
666}
667
668void
669I386LiveProcess::argsInit(int intSize, int pageSize)
670{
671    std::vector<AuxVector<uint32_t> > extraAuxvs;
672    //Tell the binary where the vsyscall part of the vsyscall page is.
673    extraAuxvs.push_back(AuxVector<uint32_t>(M5_AT_SYSINFO,
674                vsyscallPage.base + vsyscallPage.vsyscallOffset));
675    extraAuxvs.push_back(AuxVector<uint32_t>(M5_AT_SYSINFO_EHDR,
676                vsyscallPage.base));
677    X86LiveProcess::argsInit<uint32_t>(pageSize, extraAuxvs);
678}
679
680void
681X86LiveProcess::setSyscallReturn(ThreadContext *tc, SyscallReturn return_value)
682{
683    tc->setIntReg(INTREG_RAX, return_value.value());
684}
685
686X86ISA::IntReg
687X86_64LiveProcess::getSyscallArg(ThreadContext *tc, int &i)
688{
689    assert(i < NumArgumentRegs);
690    return tc->readIntReg(ArgumentReg[i++]);
691}
692
693void
694X86_64LiveProcess::setSyscallArg(ThreadContext *tc, int i, X86ISA::IntReg val)
695{
696    assert(i < NumArgumentRegs);
697    return tc->setIntReg(ArgumentReg[i], val);
698}
699
700X86ISA::IntReg
701I386LiveProcess::getSyscallArg(ThreadContext *tc, int &i)
702{
703    assert(i < NumArgumentRegs32);
704    return tc->readIntReg(ArgumentReg32[i++]);
705}
706
707X86ISA::IntReg
708I386LiveProcess::getSyscallArg(ThreadContext *tc, int &i, int width)
709{
710    assert(width == 32 || width == 64);
711    assert(i < NumArgumentRegs);
712    uint64_t retVal = tc->readIntReg(ArgumentReg32[i++]) & mask(32);
713    if (width == 64)
714        retVal |= ((uint64_t)tc->readIntReg(ArgumentReg[i++]) << 32);
715    return retVal;
716}
717
718void
719I386LiveProcess::setSyscallArg(ThreadContext *tc, int i, X86ISA::IntReg val)
720{
721    assert(i < NumArgumentRegs);
722    return tc->setIntReg(ArgumentReg[i], val);
723}
724