2 * Copyright (c) 1996-2004 Barton P. Miller
4 * We provide the Paradyn Parallel Performance Tools (below
5 * described as "Paradyn") on an AS IS basis, and do not warrant its
6 * validity or performance. We reserve the right to update, modify,
7 * or discontinue this software at any time. We shall have no
8 * obligation to supply such updates or modifications or any other
9 * form of support to you.
11 * This license is for research uses. For such uses, there is no
12 * charge. We define "research use" to mean you may freely use it
13 * inside your organization for whatever purposes you see fit. But you
14 * may not re-distribute Paradyn or parts of Paradyn, in any form
15 * source or binary (including derivatives), electronic or otherwise,
16 * to any other organization or entity without our permission.
18 * (for other uses, please contact us at paradyn@cs.wisc.edu)
20 * All warranties, including without limitation, any warranty of
21 * merchantability or fitness for a particular purpose, are hereby
24 * By your use of Paradyn, you understand and agree that we (or any
25 * other person or entity with proprietary rights in Paradyn) are
26 * under no obligation to provide either maintenance services,
27 * update services, notices of latent defects, or correction of
28 * defects for Paradyn.
30 * Even if advised of the possibility of such damages, under no
31 * circumstances shall we (or any other person or entity with
32 * proprietary rights in the software licensed hereunder) be liable
33 * to you or any third party for direct, indirect, or consequential
34 * damages of any character regardless of type of action, including,
35 * without limitation, loss of profits, loss of use, loss of good
36 * will, or computer failure or malfunction. You agree to indemnify
37 * us (and any other person or entity with proprietary rights in the
38 * software licensed hereunder) for any and all liability it may
39 * incur to third parties resulting from your use of Paradyn.
42 /* $Id: process.h,v 1.344 2006/01/13 00:00:47 jodom Exp $
43 * process.h - interface to manage a process in execution. A process is a kernel
44 * visible unit with a seperate code and data space. It might not be
45 * the only unit running the code, but it is only one changed when
46 * ptrace updates are applied to the text space.
55 #include "dyninstAPI_RT/h/dyninstAPI_RT.h"
57 #include "common/h/String.h"
58 #include "common/h/vectorSet.h"
59 #include "common/h/Dictionary.h"
60 #include "common/h/Types.h"
61 #include "common/h/Timer.h"
62 #include "dyninstAPI/src/os.h"
63 #include "dyninstAPI/src/inst.h" // callWhen
64 #include "dyninstAPI/src/frame.h"
65 #include "dyninstAPI/src/showerror.h"
66 #include "dyninstAPI/src/syscalltrap.h"
67 #include "dyninstAPI/src/libState.h"
68 #include "dyninstAPI/src/signalhandler.h"
69 #include "dyninstAPI/src/rpcMgr.h"
70 #include "dyninstAPI/src/codeRange.h"
72 //#include "dyninstAPI/src/symtab.h"
73 #include "dyninstAPI/src/imageUpdate.h"
75 #include "dyninstAPI/src/infHeap.h"
77 #if (! defined( BPATCH_LIBRARY )) && defined( PAPI )
78 #include "paradynd/src/papiMgr.h"
81 // Annoying... Solaris has two /proc header files, one for the
82 // multiple-FD /proc and one for an ioctl-based compatibility /proc.
83 // /usr/include/procfs.h is the one we want, and /usr/include/sys/procfs.h
84 // is the ioctl one. This makes it impossible to have a single include
86 #if defined(os_solaris)
88 #elif defined(os_aix) || defined(os_osf) || defined(os_irix)
89 #include <sys/procfs.h>
93 #if defined( cap_unwind )
94 #include <libunwind.h>
95 #include <libunwind-ptrace.h>
96 #endif /* defined( cap_unwind ) */
98 #if defined(SHM_SAMPLING)
99 extern unsigned SHARED_SEGMENT_SIZE;
102 #define MAX_THREADS 32
103 extern unsigned activeProcesses; // number of active processes
104 // how about just processVec.size() instead? At least, this should be made
105 // a (static) member vrble of class process
107 typedef enum { unstarted_bs,
113 bootstrapped_bs } bootstrapState_t;
115 typedef enum { terminateFailed, terminateSucceeded, alreadyTerminated } terminateProcStatus_t;
117 const int LOAD_DYNINST_BUF_SIZE = 256;
123 class generatedCodeObject;
124 class replacedFunctionCall;
125 class functionReplacement;
131 class relocationEntry;
132 class fileDescriptor;
137 class dynamic_linking;
143 class syscallNotification;
145 #ifdef BPATCH_LIBRARY
147 class BPatch_function;
151 static inline unsigned ipHash(const instPoint * const &ip)
153 // assume all addresses are 4-byte aligned
154 unsigned result = (unsigned)(Address)ip;
157 // how about %'ing by a huge prime number? Nah, x % y == x when x < y
158 // so we don't want the number to be huge.
162 typedef void (*continueCallback)(timeStamp timeOfCont);
165 friend class ptraceKludge;
166 friend class dyn_thread;
167 friend class dyn_lwp;
168 friend Address loadDyninstDll(process *, char Buffer[]);
169 friend class multiTramp;
172 // PUBLIC MEMBERS FUNCTIONS
177 // Default constructor
181 process(const process *parentProc, int iPid, int iTrace_fd);
184 bool setupCreated(int iTraceLink);
185 bool setupAttached();
186 // Similar case... process execs, we need to clean everything out
187 // and reload the runtime library. This is basically creation,
188 // just without someone calling us to make sure it happens...
190 // Once we're sure an exec is finishing, there's all sorts of work to do.
196 // Shared creation tasks
199 // And parse/get the a.out
200 // Doing this post-attach allows us to one-pass parse things that need it (e.g., AIX)
201 bool setAOut(fileDescriptor &desc);
202 bool setMainFunction();
206 bool walkStackFromFrame(Frame currentFrame, // Where to start walking from
207 pdvector<Frame> &stackWalk); // return parameter
209 // Preferred function: returns a stack walk (vector of frames)
210 // for each thread in the program
211 bool walkStacks(pdvector<pdvector<Frame> > &stackWalks);
213 // Get a vector of the active frames of all threads in the process
214 bool getAllActiveFrames(pdvector<Frame> &activeFrames);
217 // Is the current address "after" the given instPoint?
218 bool triggeredInStackFrame(Frame &frame,
223 bool isInSignalHandler(Address addr);
225 void deleteThread(dynthread_t tid);
227 // Thread index functions
228 unsigned getIndexToThread(unsigned index);
229 void setIndexToThread(unsigned index, unsigned value);
230 void updateThreadIndexAddr(Address addr);
233 // Current process state
234 processState status() const { return status_;}
236 // State when we attached;
237 bool wasRunningWhenAttached() const { return stateWhenAttached_ == running; }
239 // Are we in the middle of an exec?
240 bool execing() const { return inExec_; }
242 // update the status on the whole process (ie. process state and all lwp
244 void set_status(processState st);
246 // update the status of the process and one particular lwp in the process
247 void set_lwp_status(dyn_lwp *whichLWP, processState st);
249 // should only be called by dyn_lwp::continueLWP
250 void clearCachedRegister();
252 Address previousSignalAddr() const { return previousSignalAddr_; }
253 void setPreviousSignalAddr(Address a) { previousSignalAddr_ = a; }
254 pdstring getStatusAsString() const; // useful for debug printing etc.
256 bool checkContinueAfterStop() {
257 if( continueAfterNextStop_ ) {
258 continueAfterNextStop_ = false;
264 void continueAfterNextStop() { continueAfterNextStop_ = true; }
265 static process *findProcess(int pid);
267 char * systemPrelinkCommand;
268 #if defined(sparc_sun_solaris2_4) \
269 || defined(i386_unknown_linux2_0) \
270 || defined(x86_64_unknown_linux2_4) /* Blind duplication - Ray */ \
271 || defined(rs6000_ibm_aix4_1)
272 char* dumpPatchedImage(pdstring outFile);//ccw 28 oct 2001
274 #if defined(i386_unknown_linux2_0) \
275 || defined(x86_64_unknown_linux2_4)
276 bool prelinkSharedLibrary(pdstring originalLibNameFullPath, char* dirName, Address baseAddr);
279 #if defined(sparc_sun_solaris2_4) //ccw 10 mar 2004
280 bool dldumpSharedLibrary(pdstring dyninstRT_name, char* directoryname);
283 #if defined(i386_unknown_linux2_0) \
284 || defined(x86_64_unknown_linux2_4) \
285 || defined(sparc_sun_solaris2_4)
286 char *saveWorldFindNewSharedLibraryName(pdstring originalLibNameFullPath, char* dirName);
287 void setPrelinkCommand(char *command);
291 char* dumpPatchedImage(pdstring /*outFile*/) { return NULL; }
293 bool applyMutationsToTextSection(char *textSection, unsigned textAddr, unsigned textSize);
296 bool dumpImage(pdstring outFile);
298 // This will find the named symbol in the image or in a shared object
299 // Necessary since some things don't show up as a function or variable.
300 bool getSymbolInfo( const pdstring &name, Symbol &ret );
302 // Not at all sure we want to use this anymore...
303 void overwriteImage( image* /*img */) {
307 // Appears to be the system pointer size.
308 unsigned getAddressWidth();
310 // The process keeps maps of valid (i.e. allocated) address ranges
311 bool isValidAddress(Address);
313 // And "get me a local pointer to XX" -- before we modified it.
314 void *getPtrToInstruction(Address);
316 // this is only used on aix so far - naim
317 // And should really be defined in a arch-dependent place, not process.h - bernat
318 Address getTOCoffsetInfo(Address);
320 bool dyninstLibAlreadyLoaded() { return runtime_lib != 0; }
322 rpcMgr *getRpcMgr() const { return theRpcMgr; }
324 bool getCurrPCVector(pdvector <Address> &currPCs);
326 #if defined(os_solaris) && (defined(arch_x86) || defined(arch_x86_64))
327 bool changeIntReg(int reg, Address addr);
330 void installInstrRequests(const pdvector<instMapping*> &requests);
331 void recognize_threads(const process *parent = NULL);
332 // Get LWP handles from /proc (or as appropriate)
333 bool determineLWPs(pdvector<unsigned> &lwp_ids);
335 int getPid() const { return pid;}
337 /***************************************************************************
338 **** Runtime library initialization code (Dyninst) ****
339 ***************************************************************************/
340 bool loadDyninstLib();
341 bool setDyninstLibPtr(mapped_object *libobj);
342 bool setDyninstLibInitParams();
343 bool finalizeDyninstLib();
345 bool iRPCDyninstInit();
346 static void DYNINSTinitCompletionCallback(process *, unsigned /* rpc_id */,
347 void *data, void *ret);
350 // Get the list of inferior heaps from:
352 bool getInfHeapList(pdvector<heapDescriptor> &infHeaps); // Whole process
353 bool getInfHeapList(const mapped_object *theObj,
354 pdvector<heapDescriptor> &infHeaps); // Single mapped object
356 void addInferiorHeap(const mapped_object *obj);
358 void initInferiorHeap();
360 /* Find the tramp guard addr and set it */
361 bool initTrampGuard();
362 void saveWorldData(Address address, int size, const void* src);
364 #if defined(cap_save_the_world)
366 char* saveWorldFindDirectory();
368 unsigned int saveWorldSaveSharedLibs(int &mutatedSharedObjectsSize,
369 unsigned int &dyninst_SharedLibrariesSize,
370 char* directoryName, unsigned int &count);
371 char* saveWorldCreateSharedLibrariesSection(int dyninst_SharedLibrariesSize);
373 void saveWorldCreateHighMemSections(pdvector<imageUpdate*> &compactedHighmemUpdates,
374 pdvector<imageUpdate*> &highmemUpdates,
376 void saveWorldCreateDataSections(void* ptr);
377 void saveWorldAddSharedLibs(void *ptr);//ccw 14 may 2002
378 void saveWorldloadLibrary(pdstring tmp, void *brk_ptr) {
379 loadLibraryUpdates.push_back(tmp);
380 loadLibraryBRKs.push_back(brk_ptr);
384 void addLib(char *lname);//ccw 30 jul 2002
387 #endif // cap_save_the_world
390 bool writeDataSpace(void *inTracedProcess,
391 u_int amount, const void *inSelf);
392 bool readDataSpace(const void *inTracedProcess, u_int amount,
393 void *inSelf, bool displayErrMsg);
395 bool writeTextSpace(void *inTracedProcess, u_int amount, const void *inSelf);
396 bool writeTextWord(caddr_t inTracedProcess, int data);
398 bool readTextSpace(const void *inTracedProcess, u_int amount,
401 static bool IndependentLwpControl() {
402 #if defined(os_linux)
408 void independentLwpControlInit();
410 bool continueProc(int signalToContinueWith = -1);
412 bool terminateProc();
414 // Detach from a process, deleting data to prep for reattaching
415 // NOTE: external callers should use this function, not ::detach
416 bool detachProcess(const bool leaveRunning);
419 bool detach(const bool leaveRunning);
422 // Clear out all dynamically allocated process data
423 void deleteProcess();
427 // instPoint isn't const; it may get an updated list of
428 // instances since we generate them lazily.
429 bool replaceFunctionCall(instPoint *point,const int_function *newFunc);
431 bool dumpCore(const pdstring coreFile);
433 // Set whatever OS-level process flags are needed
434 bool setProcessFlags();
435 bool unsetProcessFlags(); // Counterpart to above
437 bool getDynamicCallSiteArgs(instPoint *callSite,
438 pdvector<AstNode *> &args);
440 // Trampoline guard get/set functions
441 Address trampGuardBase(void) { return trampGuardBase_; }
443 // PUBLIC DATA MEMBERS
447 // Need a code range of multiTramps
448 // Look up to see if a multiTramp already covers this address.
449 multiTramp *findMultiTramp(Address addr);
451 void addMultiTramp(multiTramp *multi);
453 void removeMultiTramp(multiTramp *multi);
455 // Replaced function calls...
456 void addModifiedCallsite(replacedFunctionCall *RFC);
458 // And replaced functions
459 void addFunctionReplacement(functionReplacement *,
460 pdvector<codeRange *> &overwrittenObjs);
462 codeRange *findModifiedPointByAddr(Address addr);
463 void removeModifiedPoint(Address addr);
465 // Did we override the address of this call?
466 Address getReplacedCallAddr(Address origAddr) const;
467 bool wasCallReplaced(Address origAddr) const;
469 ////////////////////////////////////////////////
470 // Address to <X> mappings
471 ////////////////////////////////////////////////
474 //interface call to Dyninst pass-through debugging
475 Address stepi(bool verbose, int lwp);
480 void print_instrucs(unsigned char *buffer, unsigned size,
483 void disass(Address start, Address end);
484 void disass(Address start, Address end, bool leave_files);
486 #if defined( os_linux )
488 Address getVsyscallStart() { return vsyscall_start_; }
489 Address getVsyscallEnd() { return vsyscall_end_; }
490 Address getVsyscallText() { return vsyscall_text_; }
491 void setVsyscallRange(Address start, Address end)
492 { vsyscall_start_ = start; vsyscall_end_ = end; }
493 void *getVsyscallData() { return vsyscall_data_; }
494 void setVsyscallData(void *data) { vsyscall_data_ = data; }
501 // True if we've reached or past a certain state
502 bool reachedBootstrapState(bootstrapState_t state) const { return bootstrapState >= state; }
503 bool suppressEventConts() { return suppressCont_; }
504 void setSuppressEventConts(bool s) { suppressCont_ = s; }
506 pdstring getBootstrapStateAsString() const;
507 bootstrapState_t getBootstrapState() {return bootstrapState;}
509 // Strictly increments (we never drop back down)
510 void setBootstrapState(bootstrapState_t state) {
512 if (bootstrapState > state)
513 cerr << "Warning: attempt to revert bootstrap state from "
514 << bootstrapState << " to " << state << endl;
516 bootstrapState = state;
517 startup_cerr << "(" << getPid() << ") Setting bootstrap state to "
518 << getBootstrapStateAsString() << endl;
521 void resetBootstrapState(bootstrapState_t state) {
522 // Every so often we need to force this to a particular value
523 bootstrapState = state;
526 // Callbacks for higher level code (like BPatch) to learn about new
527 // functions and InstPoints.
529 BPatch_function *(*new_func_cb)(process *p, int_function *f);
530 BPatch_point *(*new_instp_cb)(process *p, int_function *f, instPoint *ip,
533 //Trigger the callbacks from a lower level
534 BPatch_function *newFunctionCB(int_function *f)
535 { assert(new_func_cb); return new_func_cb(this, f); }
536 BPatch_point *newInstPointCB(int_function *f, instPoint *pt, int type)
537 { assert(new_instp_cb); return new_instp_cb(this, f, pt, type); }
539 //Register callbacks from the higher level
540 void registerFunctionCallback(BPatch_function *(*f)(process *p,
542 { new_func_cb = f; };
543 void registerInstPointCallback(BPatch_point *(*f)(process *p, int_function *f,
544 instPoint *ip, int type))
545 { new_instp_cb = f; }
547 void warnOfThreadDelete(dyn_thread *thr);
548 // inferior heap management
552 // PRIVATE DATA MEMBERS (and structure definitions)....
557 /////////////////////////////////////////////////////////////////
558 // System call trap tracking
559 /////////////////////////////////////////////////////////////////
562 // Overloaded: Address for linux-style, syscall # for /proc
563 syscallTrap *trapSyscallExitInternal(Address syscall);
564 bool clearSyscallTrapInternal(syscallTrap *trappedSyscall);
566 // Check all traps entered for a match to the syscall
567 bool checkTrappedSyscallsInternal(Address syscall);
571 // Trampoline guard location -- actually an addr in the runtime library.
575 // PRIVATE MEMBER FUNCTIONS
581 bool getDyninstRTLibName();
582 bool loadDYNINSTlib();
583 #if defined(os_linux)
584 // There are two mutually incompatible load types... split into
586 bool loadDYNINSTlib_libc20();
587 bool loadDYNINSTlib_libc21();
589 bool loadDYNINSTlibCleanup(dyn_lwp *trappingLWP);
590 bool trapDueToDyninstLib(dyn_lwp *trappingLWP);
592 // trapAddress is not set on non-NT, we discover it inline
593 bool trapAtEntryPointOfMain(dyn_lwp *checkLWP, Address trapAddress = 0);
594 bool wasCreatedViaAttach() { return creationMechanism_ == attached_cm; }
595 bool wasCreatedViaAttachToCreated() { return creationMechanism_ == attachedToCreated_cm; }
597 // This is special, since it's orthogonal to the others. We're forked if
598 // the "parent process" is non-null
599 bool wasCreatedViaFork() { return parent != NULL; }
602 bool insertTrapAtEntryPointOfMain();
603 bool handleTrapAtEntryPointOfMain(dyn_lwp *trappingLWP);
607 pdstring getProcessStatus() const;
609 static pdstring tryToFindExecutable(const pdstring &progpath, int pid);
610 // os-specific implementation. Returns empty string on failure.
611 // Otherwise, returns a full-path-name for the file. Tries every
612 // trick to determine the full-path-name, even though "progpath" may
613 // be unspecified (empty string)
615 bool isDynamicallyLinked() const { return mapped_objects.size() > 1; }
617 // handleIfDueToSharedObjectMapping: if a trap instruction was caused by
618 // a dlopen or dlclose event then return true
619 bool handleIfDueToSharedObjectMapping();
625 // getSharedObjects: This routine is called before main() to get and
626 // process all shared objects that have been mapped into the process's
628 bool processSharedObjects();
630 // addASharedObject: This routine is called whenever a new shared object
631 // has been loaded by the run-time linker after the process starts running
632 // It processes the image, creates new resources
633 bool addASharedObject(mapped_object *);
635 // return the list of dynamically linked libs
636 const pdvector<mapped_object *> &mappedObjects() { return mapped_objects; }
638 // getMainFunction: returns the main function for this process
639 int_function *getMainFunction() const { return main_function; }
641 #if !defined(BPATCH_LIBRARY)
642 // findOneFunction: returns the function associated with function "func"
643 // and module "mod". This routine checks both the a.out image and any
644 // shared object images for this function.
645 // mcheyney - should return NULL if function is excluded!!!!
647 int_function *findOnlyOneFunction(resource *func,resource *mod);
649 //this routine searches for a function in a module. Note that res is a vector
650 // due to gcc emitting duplicate constructors/destructors
651 bool findAllFuncsByName(resource *func, resource *mod, pdvector<int_function *> &res);
655 enum mt_cache_result { not_cached, cached_mt_true, cached_mt_false };
656 enum mt_cache_result cached_result;
660 // If true is passed for ignore_if_mt_not_set, then an error won't be
661 // initiated if we're unable to determine if the program is multi-threaded.
662 // We are unable to determine this if the daemon hasn't yet figured out
663 // what libraries are linked against the application. Currently, we
664 // identify an application as being multi-threaded if it is linked against
665 // a thread library (eg. libpthreads.a on AIX). There are cases where we
666 // are querying whether the app is multi-threaded, but it can't be
667 // determined yet but it also isn't necessary to know.
668 bool multithread_capable(bool ignore_if_mt_not_set = false);
670 // Do we have the RT-side multithread functions available
671 bool multithread_ready(bool ignore_if_mt_not_set = false);
673 dyn_thread *STdyn_thread();
675 // findFuncByName: returns function associated with "func_name"
676 // This routine checks both the a.out image and any shared object images
678 //int_function *findFuncByName(const pdstring &func_name);
680 bool findFuncsByAll(const pdstring &funcname,
681 pdvector<int_function *> &res,
682 const pdstring &libname = "");
684 // Specific versions...
685 bool findFuncsByPretty(const pdstring &funcname,
686 pdvector<int_function *> &res,
687 const pdstring &libname = "");
688 bool findFuncsByMangled(const pdstring &funcname,
689 pdvector<int_function *> &res,
690 const pdstring &libname = "");
692 bool findVarsByAll(const pdstring &varname,
693 pdvector<int_variable *> &res,
694 const pdstring &libname = "");
696 void getLibAndFunc(const pdstring &name,
700 // And we often internally want to wrap the above to return one
701 // and only one func...
702 int_function *findOnlyOneFunction(const pdstring &name,
703 const pdstring &libname = "");
705 // Find the code sequence containing an address
706 // Note: fix the name....
707 codeRange *findCodeRangeByAddress(Address addr);
708 int_function *findFuncByAddr(Address addr);
710 instPoint *findInstPByAddr(Address addr);
711 // Should be called once per address an instPoint points to
712 // (multiples for relocated functions)
713 void registerInstPointAddr(Address addr, instPoint *inst);
714 void unregisterInstPointAddr(Address addr, instPoint *inst);
716 bool addCodeRange(codeRange *codeobj);
717 bool deleteCodeRange(Address addr);
719 // No function is pushed onto return vector if address can't be resolved
721 pdvector<int_function *>pcsToFuncs(pdvector<Frame> stackWalk);
723 // findModule: returns the module associated with "mod_name"
724 // this routine checks both the a.out image and any shared object
725 // images for this module
726 // if check_excluded is true it checks to see if the module is excluded
727 // and if it is it returns 0. If check_excluded is false it doesn't check
728 // if substring_match is true, the first module whose name contains
729 // the provided string is returned.
730 // Wildcard: handles "*" and "?"
731 mapped_module *findModule(const pdstring &mod_name, bool wildcard = false);
732 // And the same for objects
733 // Wildcard: handles "*" and "?"
734 mapped_object *findObject(const pdstring &obj_name, bool wildcard = false);
736 // getAllFunctions: returns a vector of all functions defined in the
737 // a.out and in the shared objects
738 void getAllFunctions(pdvector<int_function *> &);
740 // getAllModules: returns a vector of all modules defined in the
741 // a.out and in the shared objects
742 void getAllModules(pdvector<mapped_module *> &);
744 void triggerNormalExitCallback(int exitCode);
745 void triggerSignalExitCallback(int signalnum);
747 // triggering normal exit callback and cleanup process happen at different
748 // times. if triggerSignalExitCallback is called, this function should
749 // also be called at the same time.
751 // this function makes no callback to dyninst but only does cleanup work
752 bool handleProcessExit();
754 #ifndef BPATCH_LIBRARY
755 bool SearchRelocationEntries(const image *owner, instPoint &instr,
756 int_function *&target,
757 Address target_addr, Address base_addr);
760 // Checks the mapped object for signal handlers
761 void findSignalHandler(mapped_object *obj);
764 // Manually copy inferior heaps past the end of text segments
765 void copyDanglingMemory(process *parent);
767 bool handleForkEntry();
768 bool handleForkExit(process *child);
769 bool handleExecEntry(char *arg0);
770 bool handleExecExit();
772 // Generic handler for anything else waiting on a system call
773 // Returns true if handling was done
774 bool handleSyscallExit(eventWhat_t syscall, dyn_lwp *lwp_with_event);
778 dyn_thread *getThread(dynthread_t tid);
779 dyn_lwp *getLWP(unsigned lwp_id);
781 // return NULL if not found
782 dyn_lwp *lookupLWP(unsigned lwp_id);
784 // This is an lwp which controls the entire process. This lwp is a
785 // fictional lwp in the sense that it isn't associated with a specific lwp
786 // in the system. For both single-threaded and multi-threaded processes,
787 // this lwp represents the process as a whole (ie. all of the individual
788 // lwps combined). This lwp will be NULL if no such lwp exists which is
789 // the case for multi-threaded linux processes.
790 dyn_lwp *getRepresentativeLWP() const {
791 return representativeLWP;
794 dyn_thread *getInitialThread() const {
795 if(threads.size() == 0)
801 dyn_thread *createInitialThread();
802 void addThread(dyn_thread *thread);
803 dyn_lwp *createRepresentativeLWP();
805 // fictional lwps aren't saved in the real_lwps vector
806 dyn_lwp *createFictionalLWP(unsigned lwp_id);
807 dyn_lwp *createRealLWP(unsigned lwp_id, int lwp_index);
809 void deleteLWP(dyn_lwp *lwp_to_delete);
811 int maxNumberOfThreads();
813 int waitforRPC(int *status,bool block = false);
815 const process *getParent() const {return parent;}
819 void processCost(unsigned obsCostLow, timeStamp wallTime,
820 timeStamp processTime);
822 bool extractBootstrapStruct(DYNINST_bootstrapStruct *);
823 bool isBootstrappedYet() const;
826 // Since we don't define these, 'private' makes sure they're not used:
827 process &operator=(const process &); // assign oper
831 dynamic_linking *getDyn() { return dyn; }
833 Address getObservedCostAddr() const { return costAddr_; }
834 void updateObservedCostAddr(Address addr) { costAddr_ = addr;}
837 // Add a signal handler that was detected
838 void addSignalHandler(Address addr, unsigned size);
840 // Used to be ifdefed, now not because of rework
841 // Goes right to the multitramp and installs/uninstalls
843 bool uninstallMutations();
844 bool reinstallMutations();
848 bool flushInstructionCache_(void *baseAddr, size_t size); //ccw 25 june 2001
850 bool continueProc_(int sig);
852 // terminateProcStatus_t is defined at the top of this file.
853 terminateProcStatus_t terminateProc_();
854 bool dumpCore_(const pdstring coreFile);
855 bool osDumpImage(const pdstring &imageFileName, pid_t pid, Address codeOff);
857 dyn_lwp *query_for_stopped_lwp();
858 dyn_lwp *stop_an_lwp(bool *wasRunning);
862 // wait until the process stops
863 bool waitUntilStopped();
864 #if defined (os_linux)
865 bool waitUntilLWPStops();
870 dyn_lwp *query_for_running_lwp();
872 // returns true iff ok to operate on the process (attached)
873 bool isAttached() const;
875 // returns true if the process is stopped (AKA we can operate on it)
876 bool isStopped() const;
878 // if the process has exited
879 bool hasExited() const;
882 // Prolly shouldn't be public... but then we need a stack of
884 // This is an lwp which controls the entire process. This lwp is a
885 // fictional lwp in the sense that it isn't associated with a specific lwp
886 // in the system. For both single-threaded and multi-threaded processes,
887 // this lwp represents the process as a whole (ie. all of the individual
888 // lwps combined). This lwp will be NULL if no such lwp exists which is
889 // the case for multi-threaded linux processes.
892 #if defined(cap_proc)
893 bool get_entry_syscalls(sysset_t *entry);
894 bool get_exit_syscalls(sysset_t *exit);
895 bool set_entry_syscalls(sysset_t *entry);
896 bool set_exit_syscalls(sysset_t *exit);
899 #if defined(cap_proc_fd)
900 bool get_status(pstatus_t *) const;
901 #endif // cap_proc_fd
905 static bool getExecFileDescriptor(pdstring filename,
907 bool waitForTrap, // Should we wait for process init
909 fileDescriptor &desc);
910 mapped_object *getAOut() { assert(mapped_objects.size()); return mapped_objects[0];}
913 // Needed by instPoint
914 // hasBeenBound: returns true if the runtime linker has bound the
915 // function symbol corresponding to the relocation entry in at the address
916 // specified by entry and base_addr. If it has been bound, then the callee
917 // function is returned in "target_pdf", else it returns false.
918 bool hasBeenBound(const relocationEntry &entry, int_function *&target_pdf,
922 bool isRunning_() const;
923 // needed to initialize the 'wasRunningWhenAttached' member vrble.
924 // Determines whether the process is running by doing a low-level OS
925 // check, not by checking member vrbles like status_. May assume that
926 // process::attach() has already run, but can't assume anything else.
927 // May barf with a not-yet-implemented error on a given platform if the
928 // platform doesn't yet support attaching to a running process. But
929 // there's no reason why we shouldn't be able to implement this on any
930 // platform; after all, the output from the "ps" command can be used
931 // (T --> return false, S or R --> return true, other --> return ?)
934 static void inferiorMallocCallback(process *proc, unsigned /* rpc_id */,
935 void *data, void *result);
937 void inferiorMallocDynamic(int size, Address lo, Address hi);
938 void inferiorFreeCompact(inferiorHeap *hp);
939 int findFreeIndex(unsigned size, int type, Address lo, Address hi);
942 // Handling of inferior memory management
943 #if defined(USES_DYNAMIC_INF_HEAP)
944 // platform-specific definition of "near" (i.e. close enough for one-insn jump)
945 void inferiorMallocConstraints(Address near_, Address &lo, Address &hi, inferiorHeapType type);
946 // platform-specific buffer size alignment
947 void inferiorMallocAlign(unsigned &size);
948 #endif /* USES_DYNAMIC_INF_HEAP */
951 Address inferiorMalloc(unsigned size, inferiorHeapType type=anyHeap,
952 Address near_=0, bool *err=NULL);
953 void inferiorFree(Address item);
954 bool inferiorRealloc(Address item, unsigned newSize);
957 /*Address inferiorMalloc(process *p, unsigned size, inferiorHeapType type=anyHeap,
958 Address near_=0, bool *err=NULL);
959 void inferiorFree(process *p, Address item, const pdvector<addrVecType> &);
961 // garbage collect instrumentation
963 void deleteGeneratedCode(generatedCodeObject *del);
964 void gcInstrumentation();
965 void gcInstrumentation(pdvector<pdvector<Frame> >&stackWalks);
967 ///////////////////////////////////////////////////
968 // Process class members
969 ///////////////////////////////////////////////////
973 ///////////////////////////////
975 ///////////////////////////////
977 const process *parent;
978 pdvector<mapped_object *> mapped_objects;
979 // And a shortcut pointer
980 mapped_object *runtime_lib;
981 // ... and keep the name around
982 pdstring dyninstRT_name;
984 // We have to perform particular steps based on how we were started.
985 typedef enum { unknown_cm,
988 attachedToCreated_cm } creationMechanism_t;
990 // Use accessor method that checks before returning...
991 creationMechanism_t creationMechanism_;
992 // Users may want to leave a process in the same state as it was;
993 // for example, if attached.
994 processState stateWhenAttached_;
996 int_function *main_function; // Usually, but not always, "main"
998 ///////////////////////////////
999 // Shared library handling
1000 ///////////////////////////////
1001 dynamic_linking *dyn;
1004 ///////////////////////////////
1006 ///////////////////////////////
1007 dyn_lwp *representativeLWP;
1008 // LWPs are index by their id
1009 dictionary_hash<unsigned, dyn_lwp *> real_lwps;
1010 // Threads are accessed by index.
1011 int max_number_of_threads;
1012 pdvector<dyn_thread *> threads;
1014 dynthread_t mapIndexToTid(int index);
1015 bool deferredContinueProc;
1016 Address previousSignalAddr_;
1017 bool continueAfterNextStop_;
1020 processState status_; /* running, stopped, etc. */
1023 // For platforms where we have to guess what the next signal is caused by.
1024 // Currently: Linux/ptrace
1025 bool nextTrapIsExec;
1026 // More sure then looking at /proc/pid
1027 pdstring execPathArg; // Argument given to exec
1028 pdstring execFilePath; // Full path info
1029 bool inExec_; // Used to be a status vrble, but is orthogonal to running/stopped
1031 ///////////////////////////////
1033 ///////////////////////////////
1037 ///////////////////////////////
1039 ///////////////////////////////
1040 bool collectSaveWorldData;//this is set to collect data for
1043 pdvector<imageUpdate*> imageUpdates;//ccw 28 oct 2001
1044 pdvector<imageUpdate*> highmemUpdates;//ccw 20 nov 2001
1045 pdvector<dataUpdate*> dataUpdates;//ccw 26 nov 2001
1046 pdvector<pdstring> loadLibraryCalls;//ccw 14 may 2002
1047 pdvector<pdstring> loadLibraryUpdates;//ccw 14 may 2002
1048 pdvector<void*> loadLibraryBRKs;
1049 int requestTextMiniTramp; //ccw 20 jul 2002
1052 // Pipe between mutator and mutatee
1053 int traceLink; /* pipe to transfer traces data over */
1055 // the following 3 are used in perfStream.C
1056 // Should migrate to process level when we get the LL tracePipe
1062 ///////////////////////////////
1063 // Address lookup members
1064 ///////////////////////////////
1065 // Trap address to base tramp address (for trap instrumentation)
1066 dictionary_hash<Address, Address> trampTrapMapping;
1067 // Address to instPoint mapping
1068 dictionary_hash<Address, instPoint *> instPMapping_;
1069 // There may be duplicate entries in the above.
1071 // Address to executable code pieces (functions, miniTramps, baseTramps, ...) mapping
1072 codeRangeTree codeRangesByAddr_;
1073 // Get a mutator-side pointer to mutatee-side data without readDataSpace...
1074 // codeRangeTree readableSections_;
1075 // codeSections_ and dataSections_ instead...
1076 // Address -> multiTramp mapping...
1077 codeRangeTree modifiedAreas_;
1078 // And an integer->multiTramp so we can replace multis easily
1079 dictionary_hash<int, multiTramp *> multiTrampDict;
1081 // Keep track of function replacements so that we can fix them
1083 dictionary_hash<Address, replacedFunctionCall *> replacedFunctionCalls_;
1085 // Address -> instruction pointer (with sanity checking)
1086 codeRangeTree codeSections_;
1087 codeRangeTree dataSections_;
1090 codeRangeTree signalHandlerLocations_;
1093 // Startup and initialization
1095 bootstrapState_t bootstrapState;
1096 unsigned char savedCodeBuffer[BYTES_TO_SAVE];
1097 #if defined(arch_x86) || defined(arch_x86_64)
1098 unsigned char savedStackFrame[BYTES_TO_SAVE];
1100 dyn_saved_regs *savedRegs;
1102 Address dyninstlib_brk_addr;
1103 Address main_brk_addr;
1105 bool runProcessAfterInit;
1107 #if defined(os_windows)
1108 // On windows we need to temporarily keep details of process creation in
1109 // order to handle their debug mechanism. We create the process, then get a message
1110 // about it (instead of our "pull" mechanism on other platforms). This gives us
1111 // space to stash the info.
1112 // Instead of tracking what we need to peel out, we keep the whole thing for later.
1114 handleT processHandle_;
1115 handleT mainFileHandle_;
1116 Address mainFileBase_;
1119 ////////////////////
1121 ////////////////////
1122 bool splitHeaps; /* are there separate code/data heaps? */
1123 bool heapInitialized_;
1124 inferiorHeap heap; /* the heap */
1125 bool inInferiorMallocDynamic; // The oddest recursion problem...
1127 /////////////////////
1128 // System call and signal handling
1129 /////////////////////
1130 // Tracing for whatever mechanism we use to notify us of syscalls made
1131 // by the process (fork/exec/exit)
1132 syscallNotification *tracedSyscalls_;
1134 // A list of traps inserted at system calls
1135 pdvector<syscallTrap *> syscallTraps_;
1137 /////////////////////
1139 /////////////////////
1140 pdvector<instMapping *> tracingRequests;
1141 pdvector<generatedCodeObject *> pendingGCInstrumentation;
1143 // Total observed cost. To avoid 64-bit math in the base tramps, we
1144 // use a 32-bit temporary accumulator and periodically dump it to
1146 uint64_t cumulativeObsCost;
1147 unsigned lastObsCostLow; // Value of counter last time we checked it
1148 Address costAddr_; // Address of global cost in the mutatee
1150 Address threadIndexAddr; // Thread ID->index mapping
1151 Address trampGuardBase_; // Tramp recursion index mapping
1153 ///////////////////////////////
1154 // Platform-specific
1155 ///////////////////////////////
1157 #if defined( arch_ia64 )
1158 unw_addr_space * unwindAddressSpace;
1159 void * unwindProcessArg;
1161 bool insertAndRegisterDynamicUnwindInformation( unw_dyn_info_t * unwindInformation );
1164 #if defined(os_linux)
1166 // Linux vsyscall stuff
1168 Address vsyscall_start_;
1169 Address vsyscall_end_;
1170 Address vsyscall_text_;
1171 void *vsyscall_data_;
1178 process *ll_createProcess(const pdstring file, pdvector<pdstring> *argv,
1179 pdvector<pdstring> *envp,
1180 const pdstring dir, int stdin_fd, int stdout_fd,
1183 process *ll_attachProcess(const pdstring &progpath, int pid);
1185 process *ll_attachToCreatedProcess(int pid, const pdstring &progpath);
1187 bool isInferiorAllocated(process *p, Address block);
1189 #if !defined(os_linux)
1190 inline void process::independentLwpControlInit() { }
1193 extern pdvector<process *> processVec;