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 "ProcessID.h"
00010 #include "IPC/Thread.h"
00011 #include <sys/types.h>
00012 #include <cstdio>
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 
00020 /*! @def POSIX_SHM
00021  *  @brief If TEKKOTSU_SHM_STYLE is set to POSIX_SHM, POSIX style shared memory will be used (shm_open, shm_unlink, mmap, munmap, ...);
00022  *  This is the default shared memory interface, both portable and stable.  By default, regular open() and unlink()
00023  *  will be used to implement the regions using file-backed shared memory.  If you define USE_UNBACKED_SHM,
00024  *  RCRegion will use shm_open/shm_unlink instead.  Unbacked shared memory is nice because there's no
00025  *  interaction with your filesystem, but isn't quite as portable.  (Cygwin didn't seem to like it too much...) */
00026 
00027 /*! @def SYSV_SHM
00028  *  @brief If TEKKOTSU_SHM_STYLE is set to SYSV_SHM, SysV style shared memory will be used (shmget, shmctl, shmat, shmdt, ...)
00029  *  SysV style seems to stick around following a program crash, and can't be unlinked pre-emptively while still in use.
00030  *  Since it appears many systems also limit the number of shared memory regions (via a sysctl configuration), leaking
00031  *  regions following repeated crashes during development gets annoying. */
00032 
00033 /*! @def NO_SHM
00034  *  @brief If TEKKOTSU_SHM_STYLE is set to NO_SHM, all shared memory operations become straight new/delete's; this restricts the program to using threads in a single process */
00035 
00036 /*! @def TEKKOTSU_SHM_STYLE
00037  *  @brief Can be set to one of POSIX_SHM, SYSV_SHM, or NO_SHM */
00038 
00039 #ifndef POSIX_SHM
00040 #  define POSIX_SHM 1
00041 #endif
00042 #ifndef SYSV_SHM
00043 #  define SYSV_SHM 2
00044 #endif
00045 #ifndef NO_SHM
00046 #  define NO_SHM 3
00047 #endif
00048 #ifndef TEKKOTSU_SHM_STYLE
00049 #  define TEKKOTSU_SHM_STYLE NO_SHM
00050 #endif
00051 
00052 #if TEKKOTSU_SHM_STYLE!=SYSV_SHM && TEKKOTSU_SHM_STYLE!=POSIX_SHM && TEKKOTSU_SHM_STYLE!=NO_SHM
00053 #  error Unknown TEKKOTSU_SHM_STYLE setting
00054 #endif
00055 
00056 #if TEKKOTSU_SHM_STYLE==POSIX_SHM
00057 namespace plist { template<class T> class Primitive; }
00058 #endif
00059 
00060 //! provides compatability with the OPEN-R type of the same name
00061 class RCRegion {
00062 public:
00063 
00064   // The type of region Identifier depends on the style of shared memory being used
00065 
00066 #if TEKKOTSU_SHM_STYLE==SYSV_SHM
00067   //! contains all information needed to attach this region from a different process
00068   struct Identifier {
00069     Identifier() : key(), shmid(), size(0) {}
00070     key_t key; //!< key_t is defined by system headers, contains system region info
00071     int shmid; //!< an integer key value which identifies the region
00072     size_t size; //!< the size of the region
00073   };
00074 
00075 #elif TEKKOTSU_SHM_STYLE==POSIX_SHM || TEKKOTSU_SHM_STYLE==NO_SHM
00076   //! maximum guaranteed length for users' region names (might have a little leeway depending on process ID prefix or tmp path prefix)
00077   static const unsigned int MAX_NAME_LEN=64;
00078 
00079   //! contains all information needed to attach this region from a different process
00080   struct Identifier {
00081     Identifier() : size(0) {} //!< constructor
00082     char key[MAX_NAME_LEN]; //!< a string name for the key
00083     size_t size; //!< size of the region
00084   };
00085 
00086 #  if TEKKOTSU_SHM_STYLE==POSIX_SHM
00087 #    ifndef USE_UNBACKED_SHM
00088   static plist::Primitive<std::string> shmRoot; //!< determines location of the file backing within file system
00089 #    endif
00090   static plist::Primitive<bool> useUniqueMemoryRegions; //!< if true, prefixes region names with #rootPID
00091   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
00092 #  endif
00093 #endif
00094 
00095 
00096   // The constructors, offering either an Aperios-compatable version,
00097   // or a linux-specific version offering explicit control over the
00098   // key value, aids better debugging
00099 
00100 #if TEKKOTSU_SHM_STYLE==SYSV_SHM
00101   //! constructor (OPEN-R compatability)
00102   explicit RCRegion(size_t sz)
00103     : id(), base(NULL), references(NULL)
00104   { init(sz,nextKey,true); }
00105   //! constructor, name isn't used for sysv-style shared memory (not OPEN-R compatable)
00106   /*! could hash the name to generate key...? */
00107   RCRegion(const std::string&, size_t sz)
00108     : id(), base(NULL), references(NULL)
00109   { init(sz,nextKey,true); }
00110 
00111 #elif TEKKOTSU_SHM_STYLE==POSIX_SHM || TEKKOTSU_SHM_STYLE==NO_SHM
00112   //! constructor (OPEN-R compatability, name is autogenerated)
00113   explicit RCRegion(size_t sz)
00114     : id(), base(NULL), references(NULL)
00115   {
00116     char name[RCRegion::MAX_NAME_LEN];
00117     snprintf(name,RCRegion::MAX_NAME_LEN,"Rgn.%d.%u",ProcessID::getID(),static_cast<unsigned int>(++nextKey));
00118     name[RCRegion::MAX_NAME_LEN-1]='\0';
00119     init(sz,name,true);
00120   }
00121   //! constructor, specify your own name for better debugging accountability (not OPEN-R compatable)
00122   RCRegion(const std::string& name, size_t sz)
00123     : id(), base(NULL), references(NULL)
00124   { init(sz,name,true); }
00125 #endif
00126 
00127   //! requests that a specified RCRegion be loaded into the current process's memory space
00128   static RCRegion * attach(const Identifier& rid);
00129   
00130   char * Base() const { return base; } //!< the pointer to the shared memory region
00131   size_t Size() const { return id.size; } //!< the size of the shared memory region
00132   static void setNextKey(key_t k) { nextKey=k; } //!< sets the next key to be used for automatic assignment to new regions
00133   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
00134   const Identifier& ID() const { return id; } //!< returns the identifier of this region
00135   
00136   int NumberOfReference() const { return references[ProcessID::NumProcesses]; } //!< number of total references to this region, total of all processes
00137   int NumberOfLocalReference() const { return references[ProcessID::getID()]; } //!< number of references to the region from the current process (in the ProcessID threadgroup sense, not necessarily system-process)
00138   void AddReference(); //!< adds a reference from the current process
00139   void RemoveReference(); //!< removes a reference from the current process
00140   void AddSharedReference(); //!< adds a reference which is held by another shared memory region
00141   void RemoveSharedReference(); //!< removes a reference which is held by another shared memory region
00142   
00143   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
00144   static void faultShutdown(); //!< try to unload all regions in a clean manner
00145 
00146 #if TEKKOTSU_SHM_STYLE==SYSV_SHM
00147   //! a map from the shared memory key type to the actual region structure
00148   typedef std::map<key_t,RCRegion*> attachedRegions_t;
00149 #elif TEKKOTSU_SHM_STYLE==POSIX_SHM || TEKKOTSU_SHM_STYLE==NO_SHM
00150   //! a map from the shared memory key type to the actual region structure
00151   typedef std::map<std::string,RCRegion*> attachedRegions_t;
00152 #endif
00153   static unsigned int NumberOfAttach() { return attachedRegions.size(); } //!< returns the number of regions which are currently attached in the process
00154   
00155   //! Returns an iterator to the beginning of the attached regions mapping -- it->first is the key, it->second is the RCRegion*
00156   /*! 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!
00157    *  This doesn't prevent other threads from attaching/detaching regions, it only prevents detaching the one you're on.
00158    *  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 */
00159   static attachedRegions_t::const_iterator attachedBegin(bool threadSafe);
00160   //! Returns an iterator to the end of the attached regions -- it->first is the key, it->second is the RCRegion*
00161   /*! 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!
00162    *  This doesn't prevent other threads from attaching/detaching regions, it only prevents detaching the one you're on. */
00163   static attachedRegions_t::const_iterator attachedEnd();
00164   //! 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()
00165   /*! 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.
00166    *  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.
00167    *  When you're done, either advance off the end, or manually call RemoveReference() on the iterator's final region */
00168   static void attachedAdvance(attachedRegions_t::const_iterator& it, int x=1);
00169   
00170   //! Different methods of handling regions with conflicting keys
00171   enum ConflictResolutionStrategy {
00172     RENAME,  //!< try another key until we find one that works (better for SYSV, maybe not so smart for POSIX)
00173     REPLACE, //!< delete the other region and try again (better for POSIX, maybe not so smart for SYSV)
00174     EXIT //!< go home and cry about it
00175   };
00176   
00177   static void setConflictResolution(ConflictResolutionStrategy crs) { conflictStrategy=crs; } //!< sets #conflictStrategy
00178   static ConflictResolutionStrategy getConflictResolution() { return conflictStrategy; } //!< returns #conflictStrategy
00179   
00180   static void setMultiprocess(bool mp) { multiprocess=mp; } //!< sets #multiprocess
00181   static bool getMultiprocess() { return multiprocess; } //!< returns #multiprocess
00182 
00183   
00184 protected:
00185   //! this protected constructor is used for attaching regions previously created by another process (see attach())
00186   RCRegion(const Identifier& rid)
00187     : id(), base(NULL), references(NULL)
00188   { init(rid.size,rid.key,false); }
00189 
00190   ~RCRegion(); //!< prevents stack allocation -- needs to be heap allocated and reference counted
00191 
00192   //! the alignment multiple of the extra space at the end of the region
00193   static const unsigned int align=sizeof(unsigned int);
00194   //! the amount of space to leave at the end of the region for housekeeping (reference counts)
00195   static const unsigned int extra=sizeof(unsigned int)*(ProcessID::NumProcesses+1);
00196   //! returns the size of the region to be allocated, given the size requested by the client
00197   static unsigned int calcRealSize(unsigned int size);
00198 
00199   //! intializes and returns #staticLock
00200   static Thread::Lock& getStaticLock();
00201 
00202 #if TEKKOTSU_SHM_STYLE==SYSV_SHM
00203   //! initializes the region's information, either creating a new shared memory region or attempting to connect to a pre-existing one
00204   void init(size_t sz, key_t sug_key, bool create);
00205 #elif TEKKOTSU_SHM_STYLE==POSIX_SHM
00206   //! returns the qualified version of this region's key (see getQualifiedName(const std::string& key) )
00207   std::string getQualifiedName() const { return getQualifiedName(id.key); }
00208   //! wraps the region's key with a root path prefix and optionally a PID suffix (see #useUniqueMemoryRegions and #shmRoot)
00209   static std::string getQualifiedName(const std::string& key);
00210   //! opens a region either in "pure" shared memory, or in file-backed shared memory, based on whether USE_UNBACKED_SHM is defined
00211   int openRegion(int mode) const;
00212   //! unlinks a region either in "pure" shared memory, or in file-backed shared memory, based on whether USE_UNBACKED_SHM is defined
00213   bool unlinkRegion() const;
00214   //! initializes the region's information, either creating a new shared memory region or attempting to connect to a pre-existing one
00215   void init(size_t sz, const std::string& name, bool create);
00216 #elif TEKKOTSU_SHM_STYLE==NO_SHM
00217   //! initializes the region's information, either pointing to an existing region or allocating a new one
00218   void init(size_t sz, const std::string& name, bool create);
00219 #endif
00220 
00221   //! controls what to do about creating a region with a conflicting key (i.e. another region already exists with the same key)
00222   static ConflictResolutionStrategy conflictStrategy;
00223   //! set to true if we are shutting down because of an error, and trying to unload shared regions to avoid leaking beyond program scope
00224   static bool isFaultShutdown;
00225   //! set to false if the different "processes" are just threads (and thus the last process reference shouldn't actually trigger unlinking a region
00226   static bool multiprocess;
00227                     
00228   static Thread::Lock* staticLock; //!< a lock over all static RCRegion members for the current process, must be obtained before changing reference counts or attaching/detaching regions
00229 
00230   static key_t nextKey; //!< serial number of next key -- starts at 1024 for TEKKOTSU_SHM_STYLE==SYSV_SHM, 0 for POSIX_SHM
00231   static attachedRegions_t attachedRegions; //!< a mapping of key values to RCRegion pointers of the attached region
00232   
00233   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
00234   char * base; //!< pointer to the region's user data
00235   unsigned int * references; //!< pointer to the per-process reference counts (stored within the shared region!)
00236 
00237 private:
00238   RCRegion(const RCRegion& r); //!< don't call
00239   RCRegion& operator=(const RCRegion& r); //!< don't call
00240 };
00241 
00242 /*! @file
00243  * @brief Describes RCRegion, which provides compatability with the OPEN-R type of the same name
00244  * @author ejt (Creator)
00245  */
00246 
00247 #  endif
00248 #endif

Tekkotsu v5.1CVS
Generated Mon May 9 04:58:49 2016 by Doxygen 1.6.3