Tekkotsu Homepage
Demos
Overview
Downloads
Dev. Resources
Reference
Credits

RCRegion.h

Go to the documentation of this file.
00001 //-*-c++-*-
00002 #ifdef PLATFORM_APERIOS
00003 #  include <OPENR/RCRegion.h>
00004 #else
00005 #  ifndef INCLUDED_RCRegion_h_
00006 #  define INCLUDED_RCRegion_h_
00007 
00008 #include "Shared/ReferenceCounter.h"
00009 #include "MutexLock.h"
00010 #include "ProcessID.h"
00011 #include "Shared/plist.h"
00012 #include <sys/types.h>
00013 #include <map>
00014 #include <exception>
00015 
00016 //do you want to use the SysV shared memory call interface
00017 //or the POSIX shared memory interface?  They have different
00018 //strengths/weaknesses on different platforms... :-/
00019 #ifndef POSIX_SHM
00020 #  define POSIX_SHM 1
00021 #endif
00022 #ifndef SYSV_SHM
00023 #  define SYSV_SHM 2
00024 #endif
00025 #ifndef TEKKOTSU_SHM_STYLE
00026 #  define TEKKOTSU_SHM_STYLE POSIX_SHM
00027 #endif
00028 
00029 #if TEKKOTSU_SHM_STYLE!=SYSV_SHM && TEKKOTSU_SHM_STYLE!=POSIX_SHM
00030 #  error Unknown TEKKOTSU_SHM_STYLE setting
00031 #endif
00032 
00033 namespace ThreadNS {
00034   class Lock;
00035 }
00036 
00037 //! provides compatability with the OPEN-R type of the same name
00038 class RCRegion {
00039 public:
00040 
00041   // The type of region Identifier depends on the style of shared memory being used
00042 
00043 #if TEKKOTSU_SHM_STYLE==SYSV_SHM
00044   //! contains all information needed to attach this region from a different process
00045   struct Identifier {
00046     Identifier() : key(), shmid(), size(0) {}
00047     key_t key; //!< key_t is defined by system headers, contains system region info
00048     int shmid; //!< an integer key value which identifies the region
00049     size_t size; //!< the size of the region
00050   };
00051 
00052 #elif TEKKOTSU_SHM_STYLE==POSIX_SHM
00053   //! maximum guaranteed length for users' region names (might have a little leeway depending on process ID prefix or tmp path prefix)
00054   static const unsigned int MAX_NAME_LEN=64;
00055 
00056   //! contains all information needed to attach this region from a different process
00057   struct Identifier {
00058     Identifier() : size(0) {}
00059     char key[MAX_NAME_LEN]; //!< a string name for the key
00060     size_t size; //!< size of the region
00061   };
00062 
00063 #  ifndef USE_UNBACKED_SHM
00064   static plist::Primitive<std::string> shmRoot; //!< determines location of the file backing within file system
00065 #  endif
00066   static plist::Primitive<bool> useUniqueMemoryRegions; //!< if true, prefixes region names with #rootPID
00067   static pid_t rootPID; //!< this is the pid of the original process, used for unique names of memory regions; pid_t is from sys/types.h
00068 #endif
00069 
00070 
00071   // The constructors, offering either an Aperios-compatable version,
00072   // or a linux-specific version offering explicit control over the
00073   // key value, aids better debugging
00074 
00075 #if TEKKOTSU_SHM_STYLE==SYSV_SHM
00076   //! constructor (OPEN-R compatability)
00077   explicit RCRegion(size_t sz)
00078     : id(), base(NULL), references(NULL), lock(NULL)
00079   { init(sz,nextKey,true); }
00080   //! constructor, name isn't used for sysv-style shared memory (not OPEN-R compatable)
00081   /*! could hash the name to generate key...? */
00082   RCRegion(const std::string&, size_t sz)
00083     : id(), base(NULL), references(NULL), lock(NULL)
00084   { init(sz,nextKey,true); }
00085 
00086 #elif TEKKOTSU_SHM_STYLE==POSIX_SHM
00087   //! constructor (OPEN-R compatability, name is autogenerated)
00088   explicit RCRegion(size_t sz)
00089     : id(), base(NULL), references(NULL), lock(NULL)
00090   {
00091     char name[RCRegion::MAX_NAME_LEN];
00092     snprintf(name,RCRegion::MAX_NAME_LEN,"Rgn.%d.%u",ProcessID::getID(),static_cast<unsigned int>(++nextKey));
00093     name[RCRegion::MAX_NAME_LEN-1]='\0';
00094     init(sz,name,true);
00095   }
00096   //! constructor, specify your own name for better debugging accountability (not OPEN-R compatable)
00097   RCRegion(const std::string& name, size_t sz)
00098     : id(), base(NULL), references(NULL), lock(NULL)
00099   { init(sz,name,true); }
00100 #endif
00101 
00102   //! requests that a specified RCRegion be loaded into the current process's memory space
00103   static RCRegion * attach(const Identifier& rid);
00104   
00105   char * Base() const { return base; } //!< the pointer to the shared memory region
00106   size_t Size() const { return id.size; } //!< the size of the shared memory region
00107   static void setNextKey(key_t k) { nextKey=k; } //!< sets the next key to be used for automatic assignment to new regions
00108   static key_t getNextKey() { return nextKey+1; } //!< return the next region serial number -- doesn't actually increment it though, repeated calls will return the same value until the value is actually used
00109   const Identifier& ID() const { return id; } //!< returns the identifier of this region
00110   
00111   int NumberOfReference() const { return references[ProcessID::NumProcesses]; } //!< number of total references to this region, total of all processes
00112   int NumberOfLocalReference() const { return references[ProcessID::getID()]; } //!< number of references to the region from the current process
00113   void AddReference(); //!< adds a reference from the current process
00114   void RemoveReference(); //!< removes a reference from the current process
00115   void AddSharedReference(); //!< adds a reference which is held by another shared memory region
00116   void RemoveSharedReference(); //!< removes a reference which is held by another shared memory region
00117   
00118   static void aboutToFork(ProcessID::ProcessID_t newID); //!< does housekeeping to mark the region as attached and the same number of references in the new process as well
00119   static void faultShutdown(); //!< try to unload all regions in a clean manner
00120 
00121 #if TEKKOTSU_SHM_STYLE==SYSV_SHM
00122   //! a map from the shared memory key type to the actual region structure
00123   typedef std::map<key_t,RCRegion*> attachedRegions_t;
00124 #elif TEKKOTSU_SHM_STYLE==POSIX_SHM
00125   //! a map from the shared memory key type to the actual region structure
00126   typedef std::map<std::string,RCRegion*> attachedRegions_t;
00127 #endif
00128   static unsigned int NumberOfAttach() { return attachedRegions.size(); } //!< returns the number of regions which are currently attached in the process
00129   
00130   //! Returns an iterator to the beginning of the attached regions mapping -- it->first is the key, it->second is the RCRegion*
00131   /*! If you need thread-safety (i.e. another thread may attach/detach while you are iterating), pass true, and be sure to use attachedAdvance() to increment the iterator!
00132    *  This doesn't prevent other threads from attaching/detaching regions, it only prevents detaching the one you're on.
00133    *  When you're done with a thread-safe iterator, either attachedAdvance() it off the end, or manually call RemoveReference() on the iterator's final region */
00134   static attachedRegions_t::const_iterator attachedBegin(bool threadSafe);
00135   //! Returns an iterator to the end of the attached regions -- it->first is the key, it->second is the RCRegion*
00136   /*! If you need thread-safety (i.e. another thread may attach/detach while you are iterating), be sure to use attachedAdvance() to decrement the iterator!
00137    *  This doesn't prevent other threads from attaching/detaching regions, it only prevents detaching the one you're on. */
00138   static attachedRegions_t::const_iterator attachedEnd();
00139   //! Increments the attached region iterator in a thread-safe way -- only use this if you previously passed 'true' to begin(), or are decrementing from end()
00140   /*! If you are using an iterator obtained without thread-safety, just increment it normally -- don't switch to this or it will screw up reference counting.
00141    *  If you insist on switching back and forth between thread-safe advance (this function) and normal iterator advancing, you will need to add a reference to the current iterator's region before calling this.
00142    *  When you're done, either advance off the end, or manually call RemoveReference() on the iterator's final region */
00143   static void attachedAdvance(attachedRegions_t::const_iterator& it, int x=1);
00144   
00145   //! returns the region's MutexLock
00146   MutexLock<ProcessID::NumProcesses>& getLock() const { return *lock; }
00147   
00148   //! Different methods of handling regions with conflicting keys
00149   enum ConflictResolutionStrategy {
00150     RENAME,  //!< try another key until we find one that works (better for SYSV, maybe not so smart for POSIX)
00151     REPLACE, //!< delete the other region and try again (better for POSIX, maybe not so smart for SYSV)
00152     EXIT //!< go home and cry about it
00153   };
00154   
00155   static void setConflictResolution(ConflictResolutionStrategy crs) { conflictStrategy=crs; } //!< sets #conflictStrategy
00156   static ConflictResolutionStrategy getConflictResolution() { return conflictStrategy; } //!< returns #conflictStrategy
00157 
00158   
00159 protected:
00160   //! this protected constructor is used for attaching regions previously created by another process (see attach())
00161   RCRegion(const Identifier& rid)
00162     : id(), base(NULL), references(NULL), lock(NULL)
00163   { init(rid.size,rid.key,false); }
00164 
00165   ~RCRegion(); //!< prevents stack allocation -- needs to be heap allocated and reference counted
00166 
00167   //! the alignment multiple of the extra space at the end of the region
00168   static const unsigned int align=sizeof(unsigned int);
00169   //! the amount of space to leave at the end of the region for housekeeping (reference count and mutex lock)
00170   static const unsigned int extra=sizeof(unsigned int)*(ProcessID::NumProcesses+1)
00171                                   +sizeof(MutexLock<ProcessID::NumProcesses>);
00172   //! returns the size of the region to be allocated, given the size requested by the client
00173   static unsigned int calcRealSize(unsigned int size);
00174 
00175   //! intializes and returns #staticLock
00176   static ThreadNS::Lock& getStaticLock();
00177 
00178 #if TEKKOTSU_SHM_STYLE==SYSV_SHM
00179   //! initializes the region's information, either creating a new shared memory region or attempting to connect to a pre-existing one
00180   void init(size_t sz, key_t sug_key, bool create);
00181 #elif TEKKOTSU_SHM_STYLE==POSIX_SHM
00182   //! returns the qualified version of this region's key (see getQualifiedName(const std::string& key) )
00183   std::string getQualifiedName() const { return getQualifiedName(id.key); }
00184   //! wraps the region's key with a root path prefix and optionally a PID suffix (see #useUniqueMemoryRegions and #shmRoot)
00185   static std::string getQualifiedName(const std::string& key);
00186   //! opens a region either in "pure" shared memory, or in file-backed shared memory, based on whether USE_UNBACKED_SHM is defined
00187   int openRegion(int mode) const;
00188   //! unlinks a region either in "pure" shared memory, or in file-backed shared memory, based on whether USE_UNBACKED_SHM is defined
00189   bool unlinkRegion() const;
00190   //! initializes the region's information, either creating a new shared memory region or attempting to connect to a pre-existing one
00191   void init(size_t sz, const std::string& name, bool create);
00192 #endif
00193 
00194   //! controls what to do about creating a region with a conflicting key (i.e. another region already exists with the same key)
00195   static ConflictResolutionStrategy conflictStrategy;
00196   //! set to true if we are shutting down because of an error, and trying to unload shared regions to avoid leaking beyond program scope
00197   static bool isFaultShutdown;
00198                     
00199   static ThreadNS::Lock* staticLock; //!< a lock over all static RCRegion members for the current process
00200 
00201   static key_t nextKey; //!< serial number of next key -- starts at 1024 for TEKKOTSU_SHM_STYLE==SYSV_SHM, 0 for POSIX_SHM
00202   static attachedRegions_t attachedRegions; //!< a mapping of key values to RCRegion pointers of the attached region
00203   
00204   Identifier id; //!< key values for the region, namely the system key type (either an integer or string depending on TEKKOTSU_SHM_STYLE) and the size of the region
00205   char * base; //!< pointer to the region's user data
00206   unsigned int * references; //!< pointer to the per-process reference counts (stored within the shared region!)
00207   MutexLock<ProcessID::NumProcesses> * lock; //!< region's inter-process lock (stored within the shared region!)
00208 
00209 private:
00210   RCRegion(const RCRegion& r); //!< don't call
00211   RCRegion& operator=(const RCRegion& r); //!< don't call
00212 };
00213 
00214 /*! @file
00215  * @brief Describes RCRegion, which provides compatability with the OPEN-R type of the same name
00216  * @author ejt (Creator)
00217  *
00218  * $Author: ejt $
00219  * $Name: tekkotsu-3_0 $
00220  * $Revision: 1.5 $
00221  * $State: Exp $
00222  * $Date: 2006/08/23 19:24:20 $
00223  */
00224 
00225 #  endif
00226 #endif

Tekkotsu v3.0
Generated Wed Oct 4 00:03:45 2006 by Doxygen 1.4.7