================================================================================

https://github.com/llvm/llvm-project/blob/main/llvm/docs/GarbageCollection.rst


================================================================================
Review mailing lists


2012
https://sourceforge.net/p/oorexx/mailman/oorexx-devel/thread/CAPJz3GuHsa3oU1Z%2BAaivP3Qn1Vy_ZNF-%3D%3Dh7WRAhkr_97_PNGw%40mail.gmail.com/#msg29651973
[Oorexx-devel] More on memory problem, SysFileTree, etc..


https://sourceforge.net/p/oorexx/mailman/oorexx-devel/thread/33bd05330711050626x4021ca8t50b0940af711128d%40mail.gmail.com/#msg8692406
[Oorexx-devel] Where does the "subclasses" method come from?
To review! maybe that explains why I have no class in the REXX package.

2017
https://sourceforge.net/p/oorexx/mailman/oorexx-devel/thread/CAPJz3Gsd3Y2qwqP3vw0YqphYHUdMK%3DXguE9ffW_WzXQY6GYs8A%40mail.gmail.com/#msg35921069
[Oorexx-devel] High memory usage in ooRexx


https://sourceforge.net/p/oorexx/mailman/oorexx-devel/thread/CAB8Mfh0%3DGG41GxrvZ21QUpE3FTX2mYyq6yY_xmCZWvnmpXyEaw%40mail.gmail.com/#msg36400434
[Oorexx-devel] A simple benchmark result of the new GC code.


2024
https://sourceforge.net/p/oorexx/mailman/oorexx-devel/thread/CAPJz3GuLG76i7r93321RY%3DEMVjGbGPU_ayH0jeD3JkGmnrgFgg%40mail.gmail.com/#msg58757891
[Oorexx-devel] How IntegerZero is GC protected?


Description by Rick, the main architect of ooRexx:

Detection of live objects is done by tracing and marking objects from a few root references.
The free storage is "swept up" by scanning memory looking for unmarked objects and reclaiming that storage.
Adjacent dead objects are already recombined into larger blocks.

Live marking is how the garbage collector determines which objects still have "live" references.
The marking process starts from a few root objects, which then identifies what objects it has references to.
The identified objects are then also marked and asked to identify what object references they contain.
Eventually, this fans out through the entire active object set.
When the marking is complete, any objects that have not been touched by the live marking are "dead" and are eligible for garbage collection.

The live and liveGeneral methods only mark fields that are references to other objects (i.e., RexxInternalObject and any of it's subclasses).
Other fields, such as ints, bools, etc. do not get marked.

If a new field is added to a class, then the live and liveGeneral methods must be updated to include the new field if and only if the field is an object type.
Failure to do so will likely result in that reference object getting improperly garbage collected because it is not marked as being a live object.

There are two methods that perform this tracing.
The live() method is only used during garbage collection and is highly optimized for that purpose because it is used a lot.
The liveGeneral() method performs the same object traversal process, but is used for less frequently used traversals such as saving/restoring programs compiled using rexxc.

This version (year 2018) treats "big" objects differently and will return the memory to the system when the object is garbage collected.
A "big" object is currently defined as greater than 1/2 meg for the 32-bit version and 1 meg for the 64-bit version.
A big part of the simplification came from removing a bit of baggage from the original OS/2 code that doesn't really apply any more.
Removing that allowed a lot of additional code to be deleted that probably was never getting used any way.

With an object like a very big array that holds lots of objects, it is necessary to expand the marking stack size during the GC process.

Ok, now I'm getting the expected out-of-memory error.
Reworked a bit how the live stack is managed and also added some predictive code to collection class allocations to try to predict ahead of time how large the live stack should be, which allows allocations error to (mostly) be handled as regular errors.

We know how much free space is still available to be given out, but we don't know the total amount of free space there is because it is likely a lot of the previously given out storage is now dead objects.
A GC event is a fairly expensive process, so you don't want to do one until you really need to, which also maximizes the amount of storage that gets swept up and also reduces memory fragmentation.

The ooRexx garbage collector is partially generational.
All of the objects contained in the flattened rexx.img file are restored into a separate object space and given a special mark ("OldSpace") that indicates these objects are never to be garbage collected.
They are also not traced during a garbage collection cycle, which can cause a problem if a reference to an object residing in the normal object heap is ever stored in a field of an oldspace object.
Without special attention, these objects could end up getting garbage collected inappropriately.

To solve this problem, the OrefSet macro is used to detect the situation where a new space object is being stored in an oldspace object.
This implements a write barrier that detects that situation and adds the object to a special table that tracks all references from the oldspace to the newspace.
The reference count is a counter of how many references we have.
The OrefSet barrier also detects if the field being written into crosses that barrier so that the reference counts can be decremented.

OrefSet is necessary for setting any reference field in a class that might get stored in the saved image.
Classes that don't implement this properly can result in some very nasty (and hard to debug) garbage collection problems.
Generally, it is good practice to use OrefSet whenever you are setting an object reference.
The one exclusion are any of the classes in the <Transient> grouping in PrimitiveClasses.xml.
These are classes that represent runtime state, and will never be stored in the image file.
These classes are permitted to just directly assign the fields without requiring OrefSet().
That is the only exception, but you need to understand the situation when deciding not to use OrefSet().
If not certain of whether it is required, then use it, since it is never an error to use it, but it might be an error to omit it.


================================================================================

Remember:
    RexxMemory.hpp
    // this can be enabled to switch on memory profiling info
    #define MEMPROFILE

    // Keep this declaration here, before #include "MemorySegment.hpp"
    // Otherwise you will get a compilation error "redefinition of 'validateObject'".
    #define CHECKOREFS


Remember :
    To activate the GC diagnostics, add these definitions in RexxCore.h :
    [later]
    no... RexxCore.h is not included by all the files !
        #define CHECKOREFS      --> MemorySegment.hpp, used in RexxMemory.cpp
        #define MEMPROFILE      --> RexxMemory.hpp, DeadObject.hpp, RexxMemory.cpp, DeadObject.cpp
        #define VERBOSE_GC      --> RexxMemory.hpp, MemorySegment.cpp
    or better : could be added in lib/orxwin32.mak to my_cdebug, when debug mode.
        /DCHECKOREFS /DMEMPROFILE /DVERBOSE_GC
    or added in CMakeCacheText.txt
        CMAKE_CXX_FLAGS_DEBUG:STRING=/D_DEBUG /DCHECKOREFS /MDd /Zi /Ob0 /Od /RTC1
        CMAKE_C_FLAGS_DEBUG:STRING=/D_DEBUG /DCHECKOREFS /MDd /Zi /Ob0 /Od /RTC1


Remember :
    When the crash occurs during GC (ex : in ObjectHeader::isObjectMarked), it's possible
    to see which ooRexx object is corrupted. Here the object is 0x7eeff200
        rexx.dll!ObjectHeader::isObjectMarked(unsigned int mark)  Line 106 + 0xa bytes	C++
        rexx.dll!RexxInternalObject::isObjectMarked(unsigned int markword)  Line 247 + 0x16 bytes	C++
        rexx.dll!RexxListTable::live(unsigned int liveMark)  Line 55 + 0x26 bytes	C++
    >	rexx.dll!RexxMemory::markObjectsMain(RexxObject * rootObject)  Line 374	C++                 <-- markObject = 0x7eeff200 {size=2129676696 elements=0x7eeff214 }  RexxListTable with OVERWRITTEN size !!!
        rexx.dll!RexxMemory::markObjects()  Line 645	C++
        rexx.dll!RexxMemory::collect()  Line 1022	C++

    A conditional break "newObj == 0x7eeff200" on the last line of RexxMemory::newObject (RexxMemory.cpp)
    lets stop the execution when the object is created. If too long, then modify the source :
        if (newObj == (RexxObject*)0x7eeff200)
        {
            int dummy=0;    //  <-- put breakpoint here
        }
        return newObj;
    Once the interpreter is stopped here, it's relatively easy to do a code review of the methods
    in the call stack, to check if an intermediate object must be protected.

    If needed, a data breakpoint can be set on the part of memory which is overwritten
    (here the 'size' attribute). In my case, was triggered when the object was inserted
    in the list of dead objects.


================================================================================
Review occurrences of CHECKOREFS in ooRexx 4.2
================================================================================

MemorySegment.hpp
#ifndef CHECKOREFS
      inline void validateObject(size_t bytes) {};
#else
      void validateObject(size_t bytes); // Must be moved to .cpp file because compile error with Interpreter::logicError
#endif


MemorySegment.cpp
#ifdef CHECKOREFS
void MemorySegmentSet::validateObject(size_t bytes)
{
  /* is object invalid size?           */
  if (!IsValidSize(bytes)) {
      /* Yes, this is not good.  Exit      */
      /* Critical Section and report       */
      /* unrecoverable error.              */
      Interpreter::logicError("Bad object detected during Garbage Collection, unable to continue");
  }
}
#endif


RexxMemory.cpp
RexxMemory::RexxMemory()
    : oldSpaceSegments(OREF_NULL), newSpaceNormalSegments(OREF_NULL), newSpaceLargeSegments(OREF_NULL) /*, newSpaceSingleSegments(OREF_NULL) */
{
...
    /* See if we want this debug info    */
    /*or not by default, its always      */
    /*setable from OREXX code.           */
#ifdef CHECKOREFS
    this->orphanCheck = true;            /* default value for OREF checking   */
#else
    this->orphanCheck = false;           /* default value for OREF checking   */
#endif


RexxMemory.hpp
// Unlike ooRexx5 before rev 12948, the OrefSet macro doesn't have the problem of double evaluation of v.
// No need to replace it by an inline function.
#ifndef CHECKOREFS
#define OrefSet(o,r,v) ((o)->isOldSpace() ? memoryObject.setOref((void *)&(r),(RexxObject *)v) : (RexxObject *)(r=v))
#else
#define OrefSet(o,r,v) memoryObject.checkSetOref((RexxObject *)o, (RexxObject **)&(r), (RexxObject *)v, __FILE__, __LINE__)
#endif


RexxMemory.cpp
void RexxMemory::restore()
{
...
    memoryObject.enableOrefChecks();     /* enable setCheckOrefs...           */
}


Setup.cpp
void RexxMemory::createImage(const char *imageTarget)
{
...
  memoryObject.enableOrefChecks();     /* enable setCheckOrefs...           */


================================================================================
Review occurences of #ifdef in ooRexx5 source
================================================================================

#ifdef MEMPROFILE
void DeadObjectPool::dumpMemoryProfile(FILE *outFile)
void LargeSegmentSet::dumpMemoryProfile(FILE *outfile)
void SingleObjectSegmentSet::dumpMemoryProfile(FILE *outfile)
void NormalSegmentSet::dumpMemoryProfile(FILE *outfile)
MemorySegment *MemoryObject::newLargeSegment(size_t requestedBytes, size_t minBytes)
void MemoryObject::saveImage(const char *imageTarget)
{

#ifdef VERBOSE_GC
class MemoryObject
    inline void verboseMessage(const char *message)
    inline void verboseMessage(const char *message, size_t sub1) {
    inline void verboseMessage(const char *message, size_t sub1, size_t sub2) {
    inline void verboseMessage(const char *message, const char *sub1, size_t sub2) {
    inline void verboseMessage(const char *message, size_t sub1, const char *sub2) {
    inline void verboseMessage(const char *message, size_t sub1, size_t sub2, size_t sub3) {
    inline void verboseMessage(const char *message, size_t sub1, const char *sub2, const char *sub3) {


#ifdef _DEBUG
          // does this object pass the basic validity tests?
          if (!o->isValid())
          {
              // provide a warning message about an invalid object
              o->dumpObject();
          }


#ifdef CHECKOREFS
void MemoryObject::mark(RexxInternalObject *markObject)


ObjectClass.cpp
bool RexxInternalObject::isValid()
{
    // Test #1, is the size valid
    if (!Memory::isValidSize(getObjectSize()))
    {
        return false;
    }

#if 0
    // The following tests seem line a good idea, but unfortunately
    // it only works with live objects. A dead object on the pool
    // has neither a valid bahaviour pointer nor a valid virtual function pointer.
    // I'm leaving this in here just in case we figure out how to make these tests work.

    size_t typeNumber = getObjectTypeNumber();
    // Test #2 is the type indicator correct?
    if (typeNumber > T_Last_Class_Type)
    {
        return false;
    }
    // Test #3, is the object's virtual function pointer the correct one for the type.
    // this can detect problems where the front part of the object has been overlayed.
    if (!checkVirtualFunctions(memoryObject.virtualFunctionTable[typeNumber]))
    {
        return false;
    }
#endif

    // the object is at least consistent
    return true;
}


==========================================================================
MemorySegment.hpp
==========================================================================


--------------------------------------------------------------------------
ooRexx 4.2 only

class MemorySegment : public MemorySegmentHeader
{

  public:

   inline void *operator new(size_t size, void *segment) { return segment; }
   inline void  operator delete(void *) { }
   inline void  operator delete(void *, void *) { }

   inline void combine(MemorySegment *nextSegment) { segmentSize += nextSegment->segmentSize + MemorySegmentOverhead; }
   inline void shrink(size_t delta) { segmentSize -= delta; }
   inline bool isAdjacentTo(MemorySegment *seg) { return end() == (char *)seg; }
   inline bool isLastBlock(char *addr, size_t length) { return (addr + length) == end(); }
   inline bool isFirstBlock(char *addr) { return addr == start(); }

   DeadObject *lastDeadObject();
   DeadObject *firstDeadObject();


class MemorySegmentSet
{

  public:

      inline void *operator new(size_t size, void *segment) { return segment; }
      inline void  operator delete(void * size) { }
      inline void  operator delete(void * size, void *segment) { }

      inline bool isInSegmentSet(RexxObject *object)

      inline bool isInSegmentSet(RexxObject *object)
      {
          MemorySegment *segment = first();
          while (segment != NULL)
          {
              if (segment->isInSegment(object))
              {
                  return true;
              }
              segment = next(segment);
          }
          return false;
      }

      virtual MemorySegment *donateSegment(size_t allocationLength);

  protected:

      virtual void collectEmptySegments();

      MemorySegment *findEmptySegment(size_t allocationLength);
      MemorySegment *splitSegment(size_t allocationLength);
      void mergeSegments(size_t allocationLength);
      void combineEmptySegments(MemorySegment *front, MemorySegment *back);

      virtual size_t suggestMemoryContraction();

      MemorySegment *largestActiveSegment();
      MemorySegment *largestEmptySegment();

      void releaseEmptySegments(size_t releaseSize);
      void releaseSegment(MemorySegment *segment);

      MemorySegment *getSegment(size_t requestLength, size_t minimumLength);
      void activateEmptySegments();

    MemorySegment emptySegments;          /* our empty segment chain (used for reserves) */


class NormalSegmentSet : public MemorySegmentSet
{
  public:

    virtual size_t suggestMemoryContraction();

    inline size_t recommendedMaximumMemorySize() { return (size_t)((float)liveObjectBytes/(1.0 - NormalMemoryContractionThreshold)); }


protected:

    void expandOrCollect(size_t allocationLength);


--------------------------------------------------------------------------------
ooRexx 5.2 only

class MemorySegment : public MemorySegmentHeader
{

  public:

   void transferSegment(MemorySegment *segment);

   inline RexxInternalObject *startObject() { return (RexxInternalObject *)start(); }
   inline RexxInternalObject *endObject() { return (RexxInternalObject *)end(); }

   // This rounds to segment sized chunks, not taking the overhead into account.
   static inline size_t roundSegmentBoundary(size_t n) { return Memory::roundUp(n, SegmentSize); }

   static const size_t MemorySegmentOverhead = sizeof(MemorySegmentHeader);

   // default size for a segment allocation, we go larger on 64-bit
   static const size_t SegmentSize = (256 * Memory::LargeAllocationUnit * 2);
   // our threshold for moving to a larger block allocation scheme
   static const size_t LargeBlockThreshold = Memory::LargeAllocationUnit * 4;
   // our threshold for moving to an object per block allocation scheme
   // a default segment size seems a logical threshold
   static const size_t SingleBlockThreshold = SegmentSize;


class MemorySegmentSet
{

  public:

      void transferSegment(MemorySegment *segment);

      void sweepSingleSegment(MemorySegment *sweepSegment);

      MemorySegment *largestActiveSegment();

      static const size_t MinimumSegmentSize;
      // amount of usable space in a minimum sized segment
      static const size_t MinimumSegmentDeadSpace;
      // default size for a larger segment allocation
      static const size_t LargeSegmentSize;
      // allocation available in a default segment
      static const size_t SegmentDeadSpace;
      // space available in a larger allocation.
      static const size_t LargeSegmentDeadSpace;


class NormalSegmentSet : public MemorySegmentSet
{

  private:

    // index of first dead free chain.  We start with the previous
    // chain, as older tokenized images can contain objects smaller
    // than our minimum.  If these are garbage collected individually,
    // we need a place to put them.
    static const size_t FirstDeadPool = Memory::MinimumObjectSize / Memory::ObjectGrain;
    // The largest size element we'll keep in a subpool
    static const size_t LargestSubpool = 512;
    // The index of the last subpool dead chain
    static const size_t LastDeadPool = LargestSubpool / Memory::ObjectGrain;
    // number of free chains (we index zero based, so we need to
    // allocate one additional pool)
    static const size_t DeadPools = LastDeadPool + 1;

    // the threshold to trigger expansion of the normal segment set.
    static const double NormalMemoryExpansionThreshold;
    // allocation request for the recovery segment
    static const size_t RecoverSegmentSize = ((MemorySegment::SegmentSize/2) - MemorySegment::MemorySegmentOverhead);
    // initial allocation size for normal space.
    static const size_t InitialNormalSegmentSpace;

    // map an object length to an allocation deadpool.  NOTE:  this
    // assumes the length has already been rounded to ObjectGrain!
    static inline size_t lengthToDeadPool(size_t l) { return ((l) / Memory::ObjectGrain); }
    // map a dead pool index to the size of blocks held in the pool
    static inline size_t deadPoolToLength(size_t d) { return ((d) * Memory::ObjectGrain); }


class LargeSegmentSet : public MemorySegmentSet
{
  public:
    void    getInitialSet();

protected:

    // initial allocation size for large space.
    static const size_t InitialLargeSegmentSpace;

    size_t suggestMemoryExpansion() override;

  private:

    // the threshold to trigger expansion of the normal segment set.
    static const double LargeMemoryExpansionThreshold;
    inline size_t recommendedMemorySize() { return (size_t)((float)liveObjectBytes/(1.0 - LargeMemoryExpansionThreshold)); }


/**
 * A segment set used for allocating the largest objects. We
 * allocate a segment dedicated to each object and will return
 * the segment when the object is garbage collected.
 */
class SingleObjectSegmentSet : public MemorySegmentSet
{
  public:

#ifdef KEEP_DEFAULT_CONSTRUCTOR
    /* the default constructor */
    SingleObjectSegmentSet() : MemorySegmentSet("SingleObjectSegmentSet") { ; }
#endif
    SingleObjectSegmentSet(MemoryObject *memory);

    virtual ~SingleObjectSegmentSet()
    {
#ifdef MEMPROFILE
        fprintf(stderr, "[SingleObjectSegmentSet] destructor this=%p name=\"%s\"\n", this, name);
        this->dumpMemoryProfile(stderr);
#endif
    }

    void   dumpMemoryProfile(FILE *outfile) override;
    RexxInternalObject *handleAllocationFailure(size_t allocationLength);
    RexxInternalObject *allocateObject(size_t allocationLength);

protected:

    void addDeadObject(DeadObject *object) override;
    void addDeadObject(char *object, size_t length) override;
    MemorySegment *allocateSegment(size_t requestLength, size_t minimumLength) override;
    void completeSweepOperation() override;

  private:

    // the limit of new segments we will allocate before forcing a GC.
    // this is kept fairly small, since repeated allocations is frequently a
    // sign that we have segments we can release.
    static const size_t ForceGCThreshold = 4;

    size_t         allocationsSinceLastGC;// number of objects allocated since the last GC.
    size_t         allocationCount;       // total number of allocations
    size_t         returnCount;           // the count of segments we've returned to system
};


================================================================================
Comparison of ooRexx 4.2 with 5.2

ooRexx 4.2
----------
DeadObject.cpp                  almost identical
DeadObject.hpp                  almost identical
files.html                      identical
GlobalProtectedObject.hpp       almost identical
MemorySegment.cpp               different
MemorySegment.hpp               roughly identical (many renamings, preprocessor constants replaced by C++ constants)
MemoryStats.cpp
MemoryStats.hpp
ProtectedObject.cpp
ProtectedObject.hpp
    RexxEnvelope.cpp
    RexxEnvelope.hpp
    RexxInternalStack.cpp
    RexxInternalStack.hpp
RexxMemory.cpp
RexxMemory.hpp
RexxSmartBuffer.cpp
RexxSmartBuffer.hpp
Setup.cpp
UninitDispatcher.cpp
UninitDispatcher.hpp


ooRexx 5.2
----------
DeadObject.cpp                  almost identical
DeadObject.hpp                  almost identical
    Envelope.cpp
    Envelope.hpp
    ExternalFileBuffer.hpp
    FileNameBuffer.cpp
    FileNameBuffer.hpp
files.html                      identical
    GlobalNames.cpp
    GlobalNames.h
    GlobalNames.hpp
GlobalProtectedObject.hpp       almost identical
    InternalStack.cpp
    InternalStack.hpp
    MapBucket.cpp
    MapBucket.hpp
    MapTable.cpp
    MapTable.hpp
    Memory.hpp
MemorySegment.cpp               different
MemorySegment.hpp               roughly identical (many renamings, preprocessor constants replaced by C++ constants)
        #define MemorySegmentOverhead       (sizeof(MemorySegmentHeader))
            static const size_t MemorySegmentOverhead = sizeof(MemorySegmentHeader);
        #define MemorySegmentPoolOverhead   (sizeof(MemorySegmentPoolHeader))
            not found
        64bit #define SegmentSize (256*1024*2)
        32bit #define SegmentSize (256*1024)
           static const size_t SegmentSize = (256 * Memory::LargeAllocationUnit * 2);
        new class SingleObjectSegmentSet
    MemoryStack.cpp
    MemoryStack.hpp
MemoryStats.cpp
MemoryStats.hpp
    NumberArray.cpp
    NumberArray.hpp
    PointerBucket.cpp
    PointerBucket.hpp
    PointerTable.cpp
    PointerTable.hpp
ProtectedObject.cpp
ProtectedObject.hpp
RexxMemory.cpp
RexxMemory.hpp
Setup.cpp
SmartBuffer.cpp
SmartBuffer.hpp
UninitDispatcher.cpp
UninitDispatcher.hpp


RexxMemory      --> MemoryObject
new class SingleObjectSegmentSet


-------------------------------------------------------------------------------
diff ooRexx 4.2 / 5.2

class MemorySegmentSet
{

  public:

      typedef enum { SET_UNINITIALIZED, SET_NORMAL, SET_LARGEBLOCK, SET_OLDSPACE } SegmentSetID;
      typedef enum { SET_UNINITIALIZED, SET_NORMAL, SET_LARGEBLOCK, SET_OLDSPACE, SET_SINGLEOBJECT } SegmentSetID;


      void addSegment(MemorySegment *segment, bool createDeadObject = 1);
      void addSegment(MemorySegment *segment);


  protected:


-------------------------------------------------------------------------------
No equivalent in ooRexx 4.2 (review done 07/01/2026)

// ooRexx 4.2 doesn't have SingleObjectSegmentSet
RexxInternalObject *SingleObjectSegmentSet::allocateObject(size_t requestLength)
{
    memory->verboseMessage("Allocating a single segment object of %zu bytes to %s" line_end, requestLength, name);

    // it is possible that we could have a pattern where a large number of
    // short-lived objects get allocated without triggering a garbage collection. Since
    // this segment set expands for each object allocation, we would never trigger a GC
    // until we had an actual allocation failure. It is better to be proactive and
    // prune the dead segments before attempting the allocation if they have been
    // accumulating
    if (allocationsSinceLastGC > ForceGCThreshold)
    {
        memory->verboseMessage("Single object force threshold reached" line_end);
        return OREF_NULL;       // this will trigger the GC
    }



// No transfer in ooRexx 4.2
// ooRexx 5.2
void MemorySegmentSet::transferSegment(MemorySegment *segment)
{
    memory->verboseMessage("Segment of %zu bytes transferred to %s" line_end, segment->size(), name);


// ooRexx 4.2 has no expansion algorithm
// ooRexx 5.2
size_t LargeSegmentSet::suggestMemoryExpansion()
{
    // since we have just done a GC, we have metrics on the size of live
    // and dead storage. Get the current percentage
    float freePercent = freeMemoryPercentage();

    memory->verboseMessage("Large segment set free memory percentage is %d" line_end, (int)(freePercent * 100.0));


// ooRexx 5.2 has no contraction algorithm
// ooRexx 4.2
size_t MemorySegmentSet::suggestMemoryContraction()
    return 0
size_t NormalSegmentSet::suggestMemoryContraction()
    implemented


// ooRexx 4.2 and ooRexx 5.2 : this method is NOP??
void LargeSegmentSet::completeSweepOperation()
{
    memory->verboseMessage("Large segment sweep complete.  Largest block is %zu, smallest block is %zu" line_end, largestObject, smallestObject);
}


// ooRexx 4.2 has some verbose messages, but different from ooRexx 5.2
I did not align them.
void  MemoryObject::runUninits()
{
    // if we're already processing this, don't try to do this
    // recursively.
    if (processingUninits)
    {
        return;
    }

    // ok, turn on the interlock
    processingUninits = true;
    verboseMessage("Starting to process pending uninit methods\n");
...
    // turn off the interlock
    processingUninits = false; ;
    verboseMessage("Done processing pending uninit methods\n");
}


================================================================================
Verbose messages added in ooRexx 4.2 (07/01/2026)
================================================================================


RexxInternalObject *NormalSegmentSet::handleAllocationFailure(size_t allocationLength)
{
    memory->verboseMessage("Normal allocation failure for %zu bytes" line_end, allocationLength);


RexxInternalObject *LargeSegmentSet::handleAllocationFailure(size_t allocationLength)
{
    memory->verboseMessage("Large object allocation failure for %zu bytes" line_end, allocationLength);


RexxInternalObject *SingleObjectSegmentSet::handleAllocationFailure(size_t allocationLength)
{
    memory->verboseMessage("Single object allocation failure for %zu bytes" line_end, allocationLength);



void MemorySegmentSet::addSegment(MemorySegment *segment)
{
    memory->verboseMessage("Adding a segment of %zu bytes to %s" line_end, segment->size(), name);



size_t NormalSegmentSet::suggestMemoryExpansion()
{
    // since we have just done a GC, we have metrics on the size of live
    // and dead storage. Get the current percentage
    float freePercent = freeMemoryPercentage();

    memory->verboseMessage("Normal segment set free memory percentage is %d" line_end, (int)(freePercent * 100.0));


MemorySegment *MemoryObject::newSegment(size_t requestedBytes, size_t minBytes)
{
    // first make sure we've got enough space for the control
    // information. We don't do any rounding. The segment set has already
    // decided what the apropriate size should be. In some cases (i.e., the single object
    // segment set), rounding would just waste memory.
    requestedBytes = requestedBytes + MemorySegment::MemorySegmentOverhead;
    verboseMessage("Allocating a new segment of %d bytes\n", requestedBytes);
    // try to allocate a new segment
    MemorySegment *segment = newSegment(requestedBytes);
    if (segment == NULL)
    {
        verboseMessage("Allocating a boundary new segment of %d bytes\n", requestedBytes);
        // Segmentsize is the minimum size request we handle.  If
        // minbytes is small, then we're just adding a segment to the
        // small pool.  Reduce the request to SegmentSize and try again.
        // For all other requests, try once more with the minimum.
        minBytes = minBytes + MemorySegment::MemorySegmentOverhead;
        verboseMessage("Allocating a fallback new segment of %d bytes\n", minBytes);
        // try to allocate once more...if this fails, the caller will
        // have to handle it.
        segment = newSegment(minBytes);
    }
    return segment;                      // return the allocated segment
}


void MemoryObject::scavengeSegmentSets(MemorySegmentSet *requestor, size_t allocationLength)
{
...
    if (largeObject != NULL)
    {
        verboseMessage("Donating an object of %zu bytes from %s to %s\n", largeObject->getObjectSize(), donor->name, requestor->name);
        // we need to insert this into the normal dead chain
        // locations.
        requestor->addDeadObject(largeObject);
    }


================================================================================
Code review to see if TraceObject may be the cause of GC slowdown (done on 07/01/2026)
================================================================================
Answer: no


RexxActivation::traceInstruction                looks good
2.00 ms   0,0 %	2.00 ms
1.00 ms   0,0 %	1.00 ms
1.00 ms   0,0 %	1.00 ms
RexxActivation::traceEntry()                    looks good
1.00 ms   0,0 %	1.00 ms
14.00 ms   0,0 %	11.00 ms
2.00 ms   0,0 %	2.00 ms
3.00 ms   0,0 %	2.00 ms
RexxActivation::traceVariable                   looks good
RexxActivation::traceIntermediate               looks good
RexxActivation::traceResult                     looks good
RexxActivation::traceOperator                   looks good
RexxActivation::traceArgument                   looks good
19.18 s   7,8 %	2.00 ms
RexxActivation::traceDotVariable
RexxActivation::traceMessage                    looks good
2.00 ms   0,0 %	2.00 ms
RexxActivation::traceAssignment
RexxActivation::traceKeywordResult


traceValue                                      looks good
   inline void              traceResultValue(RexxObject * v) { traceValue(v, TRACE_PREFIX_RESULT); };
RexxInstructionAddress::execute
RexxInstructionCommand::execute
no impact on json
but must add a test in traceResultValue!

RexxActivation::traceEntryOrExit


================================================================================
2015 Sept

GC review
stringArgument can return a new string
which should be protected
--> review all the calls of stringArgument : done in v4.2

idem optionalStringArgument : done in v4.2
idem ->requiredString : done in v4.2
idem requiredStringArg : no problem, stored in expression stack
idem required_string : no problem, stored in expression stack
idem requestArray : done in v4.2
idem REQUEST_ARRAY : done in v4.2
idem makeArray : done

--------------------------------------------------------------------------------
Review the fixes done for GC in executor.
The goal is to apply them to v4.2

12/03/2012 "Commit pending changes" --> lot of changes for GC
06/03/2012 diary : list plenty of GC fixes
04/03/2012 diary : GC fixes
16/08/2011 diary : GC fixes
    Remember
    RexxCollection.cpp, RexxHashTableCollection::copy : newObj is not protected.
        Should be protected only if ActivityManager::currentActivity != NULL, otherwise crash in implementation of ProtectedObject's methods
        (RexxHashTableCollection::copy is called during interpreter initialization, and at this time, ActivityManager::currentActivity == NULL).


ArrayClass.cpp                              done 4.2, 4.2 work
RexxObject  *RexxArray::copy(void)
    todo : newArray is not protected


BuiltinFunctions.cpp                        done 4.2, 4.2 work
BUILTIN(VALUE)
before
            result = ((RexxString *)OREF_PERIOD)->concat(variable->upper());
after
            variable = variable->upper();
            ProtectedObject p(variable);
            result = ((RexxString *)OREF_PERIOD)->concat(variable);


CallInstruction.cpp                         done 4.2 work
void RexxInstructionCall::execute(
    ProtectedObject p_name;
    ...
            p_name = _name;


ClassClass.cpp                              done 4.2 work
ProtectedObject p1(enhanced_instance_mdict);
ProtectedObject p(enhancing_class_methods);


ClassClass.cpp                              done 4.2 work
RexxString *RexxClass::defaultName()
    /*RexxString * */ ProtectedObject defaultname = this->id;  /* use the id directly               */
                                         /* prefix with "The"                 */
    defaultname = ((RexxString*)defaultname)->concatToCstring("The ");
    /* add on "class"                    */
    defaultname = ((RexxString*)defaultname)->concatWithCstring(" class");


ClassClass.cpp                              done 4.2 work (including method_object)
RexxObject *RexxClass::defineMethod(
    ProtectedObject p(method_name);
    JLF : method_object should be also protected, according to my comment in diary on 16/08/2011


ClassClass.cpp                              done 4.2 work
RexxObject *RexxClass::defineClassMethod(RexxString *method_name, RexxMethod *newMethod)
    ProtectedObject p(method_name);


ClassClass.cpp                              done 4.2 work
RexxObject *RexxClass::deleteMethod(
    ProtectedObject p(method_name);


ClassClass.cpp                              done 4.2 work
RexxMethod *RexxClass::method(
    ProtectedObject p(method_name);


ClassClass.cpp                              done 4.2 work
void RexxClass::methodDictionaryMerge(
        ProtectedObject p(method_name);


ClassClass.cpp                              done 4.2 work
RexxTable *RexxClass::methodDictionaryCreate(
        ProtectedObject p(method_name);


ContextClass.cpp                            done 4.2 work
void RexxContext::live(size_t liveMark)
    (jlf : I don't see this variable in .h, is it coming from the superclass ?)
    memory_mark(this->objectVariables);


ContextClass.cpp                            done 4.2 work
void RexxContext::liveGeneral(int reason)
    memory_mark_general(this->objectVariables);


ContextClass.cpp                            not done
void RexxContext::flatten(RexxEnvelope *envelope)
  flatten_reference(newThis->objectVariables, envelope);                jlf : are you sure ??? not done


DirectoryClass.cpp                          done 4.2 work
RexxObject *RexxDirectory::copy()
    jlf : newObj must be protected (todo)


DirectoryClass.cpp                          done 4.2 work
RexxObject *RexxDirectory::setEntry(
    ProtectedObject p(entryname);


DirectoryClass.cpp                          done 4.2 work
RexxObject *RexxDirectory::setMethod(
    ProtectedObject p(entryname);


DirectoryClass.cpp                          done 4.2 work
RexxObject *RexxDirectory::newRexx(
    ProtectedObject p(newDirectory);


DoInstruction.cpp                           done 4.2 work
void RexxInstructionDo::execute(
    /*RexxObject * */ ProtectedObject result; /* expression evaluation result      */
    ...
                if (isOfClass(Array, (RexxObject*)result))      /* already an array item?            */
    ...
                        reportException(Error_Execution_noarray, (RexxObject*)result);
    ...
                if (isOfClass(Array, (RexxObject*)result))      /* already an array item?            */
    ...
                        reportException(Error_Execution_noarray, (RexxObject*)result);
    ...
                if (isOfClass(Integer, (RexxObject*)result) && context->digits() >= Numerics::DEFAULT_DIGITS)
    ...
                    count = ((RexxInteger *)(RexxObject*)result)->getValue();
    ...
                    if (!((RexxObject*)result)->requestNumber(count, number_digits()))
    ...
                if (isOfClass(Integer, (RexxObject*)result) && context->digits() >= Numerics::DEFAULT_DIGITS)
    ...
                    count = ((RexxInteger *)(RexxObject*)result)->getValue();
    ...
                    if (!((RexxObject*)result)->requestNumber(count, number_digits()))


DoInstruction.cpp                           done 4.2 work
void RexxInstructionDo::controlSetup(
    /*RexxObject * */ ProtectedObject result; /* expression result                 */
    ...
    + several casts


ExceptionClass.cpp                          not done (not in official 4.2)
void ExceptionClass::live(size_t liveMark)
    memory_mark(this->objectVariables);
}


ExceptionClass.cpp                          not done (not in official 4.2)
void ExceptionClass::liveGeneral(int reason)
    memory_mark_general(this->objectVariables);
}


ExceptionClass.cpp                          not done (not in official 4.2)
void ExceptionClass::flatten(RexxEnvelope *envelope)
  flatten_reference(newThis->objectVariables, envelope);

  cleanUpFlatten
}


ExceptionClass.cpp                          not done (not in official 4.2)
RexxDirectory *ExceptionClass::getCondition()
        ProtectedObject p(condition);


ExpressionStack.cpp                         done 4.2 work
#include "ProtectedObject.hpp"


ExpressionStack.cpp                         done 4.2 work
RexxString *RexxExpressionStack::requiredStringArg(
    ProtectedObject p(newStr);


ExpressionStack.cpp                         done 4.2 work
RexxString *RexxExpressionStack::optionalStringArg(
    ProtectedObject p(newStr);


ForwardInstruction.cpp
void RexxInstructionForward::execute(       done 4.2 work
    ProtectedObject p_message;
    ...
        _message = REQUEST_STRING(temp);    /* get the string version            */
        p_message = _message;
        _message = _message->upper();       /* and force to uppercase            */
        p_message = _message;


IdentityTableClass.cpp                      already done in official 4.2
#include "ProtectedObject.hpp"


IdentityTableClass.cpp                      already done in official 4.2
RexxObject *RexxIdentityTable::newRexx(RexxObject **args, size_t argCount)
    ProtectedObject p(newObj);


InstructionParser.cpp                       done 4.2 work
RexxInstruction *RexxSource::callNew()
    /* RexxString * */ ProtectedObject _condition = (RexxObject*)OREF_NULL; /* clear the condition               */
    ...
    + casts


InstructionParser.cpp                       done 4.2 work
RexxInstruction *RexxSource::raiseNew()
    /* RexxString * */ ProtectedObject _condition = token->value;           /* use the condition string value    */
    ...
    + casts


InstructionParser.cpp                       done 4.2 work (including newObject - another occurence also protected)
RexxInstruction *RexxSource::signalNew()
    /* RexxString * */ ProtectedObject _condition = (RexxString*)OREF_NULL; /* and no condition                  */
    ...
    + casts
    ----
    jlf : newObject to protect ? (not done)


IntegerClass.cpp                            done 4.2 work
RexxString *RexxInteger::concatBlank(
  ProtectedObject p(other);


IntegerClass.cpp                            done 4.2 work
RexxString *RexxInteger::concat(
  ProtectedObject p(other);


Interpreter.cpp                             done 4.2 work
RexxClass *Interpreter::findClass(RexxString *className)
    ProtectedObject p(internalName);


InterpreterInstance.cpp                     done 4.2 work
CommandHandler *InterpreterInstance::resolveCommandHandler(RexxString *name)
    ProtectedObject p(upperName);


InterpretInstruction.cpp                    done 4.2 work
void RexxInstructionInterpret::execute(
    ProtectedObject p(interpretString);


ListClass.cpp                               done 4.2 work
RexxObject *RexxList::copy(void)
    jlf : newlist must be protected (todo)


ListClass.cpp                               done 4.2 work
RexxSupplier *RexxList::supplier(void)
    indices = this->makeArrayIndices();
    ProtectedObject p_indices(indices);
    values = this->makeArray();          /* get the list values               */
    ProtectedObject p_values(values);


ListClass.cpp                               already done in official 4.2
RexxList *RexxList::newRexx(
    ProtectedObject p(newList);


MessageClass.cpp                            done v4.2 work (newMessage already done)
RexxObject *RexxMessage::newRexx(
    ProtectedObject m(msgName);
    ...
        ProtectedObject p(newMessage);


MethodClass.cpp                             done v4.2 work
RexxMethod *RexxMethod::newMethodObject(RexxString *pgmname, RexxObject *source, RexxObject *position, RexxSource *parentSource)
        ProtectedObject p(sourceString);
    ...
            ProtectedObject p(sourceString);


MethodClass.cpp                             done v4.2 work
RexxMethod *RexxMethod::newRexx(
            ProtectedObject p(option);


ObjectClass.cpp                             done v4.2 work
RexxMethod *RexxObject::instanceMethod(RexxString  *method_name)
    ProtectedObject p(method_name);


ObjectClass.cpp                             done v4.2 work (optim ok ?)
RexxObject * RexxObject::copy()
    jlf : newObj must be protected (todo)


ObjectClass.cpp                             done v4.2 work
void RexxObject::copyIntoTail(RexxCompoundTail *tail)
    ProtectedObject p(value);


ObjectClass.cpp                             done v4.2 work
RexxObject  *RexxObject::setMethod(
    ProtectedObject p(msgname);


ObjectClass.cpp                             done v4.2 work
RexxObject  *RexxObject::unsetMethod(
  ProtectedObject p(msgname);


ObjectClass.cpp                             done v4.2 work
RexxObject  *RexxObject::requestRexx(
    className = stringArgument(className, ARG_ONE)->upper();
    ProtectedObject p_className(className);
    RexxString *class_id = this->id()->upper();      /* get the class name in uppercase   */
    ProtectedObject p_class_id(class_id);


ObjectClass.cpp                             done v4.2 work
RexxObject *RexxObject::sendWith(RexxObject *message, RexxArray *arguments)
    decodeMessageName(this, message, messageName, startScope);
    ProtectedObject m(messageName);

    arguments = arrayArgument(arguments, ARG_TWO);
    ProtectedObject p(arguments);


ObjectClass.cpp                             done v4.2 work
RexxObject *RexxObject::send(RexxObject **arguments, size_t argCount)
    ProtectedObject m(messageName);


ObjectClass.cpp                             done v4.2 work
RexxMessage *RexxObject::startWith(RexxObject *message, RexxArray *arguments)
    ProtectedObject p(arguments);


ObjectClass.cpp                             done v4.2 work
RexxMessage *RexxObject::startCommon(RexxObject *message, RexxObject **arguments, size_t argCount)
    ProtectedObject m(messageName);


ObjectClass.cpp                             done v4.2 work
void RexxObject::decodeMessageName(RexxObject *target, RexxObject *message, RexxString *&messageName, RexxObject *&startScope)
        ProtectedObject p(messageArray);


ObjectClass.cpp                             done v4.2 work
RexxObject  *RexxObject::defMethods(
        name = name->upper();              /* make sure the name is upperCase.  */
        ProtectedObject p(name);


ObjectClass.cpp                             done v4.2 work (including methcopy)
RexxObject  *RexxObject::defMethod(
    msgname = msgname->upper();          /* add this as an uppercase name     */
    ProtectedObject p(msgname);
    ---
    jlf : methcopy to protect ? (not sure...)(todo)


ObjectClass.cpp                             done v4.2 work
RexxString *RexxObject::concatRexx(RexxObject *otherObj)
    RexxString *alias = (RexxString *)REQUEST_STRING(this);
    ProtectedObject p(alias);


ObjectClass.cpp                             done v4.2 work
RexxString *RexxObject::concatBlank(RexxObject *otherObj)
    RexxString *alias = (RexxString *)REQUEST_STRING(this);
    ProtectedObject p(alias);


OptionsInstruction.cpp                      done v4.2 work
void RexxInstructionOptions::execute(
    stringVal = REQUEST_STRING(value);   /* get the string version            */
    ProtectedObject p(stringVal);


PackageClass.cpp                            done v4.2 work
PackageClass *PackageClass::loadPackage(RexxString *name, RexxArray *s)
        s = arrayArgument(s, "source");
        ProtectedObject p(s);


PackageClass.cpp                            done v4.2 work
PackageClass *PackageClass::newRexx(
        RexxArray *sourceArray = arrayArgument(_source, "source");
        ProtectedObject p(sourceArray);
        package = instance->loadRequires(activity, nameString, sourceArray);
    }

    ProtectedObject p(package);


PackageManager.cpp                          done v4.2 work
RoutineClass *PackageManager::createRegisteredRoutine(RexxString *function)
    RoutineClass *func = new RoutineClass(function, new RegisteredRoutine(function, (RexxRoutineHandler *)entry));
    function = function->upper();
    ProtectedObject p(function);


PackageManager.cpp                          done v4.2 work
RexxObject *PackageManager::dropRegisteredRoutine(RexxString *name)
    name = name->upper();
    ProtectedObject p(name);


PackageManager.cpp                          done v4.2 work
RexxObject *PackageManager::queryRegisteredRoutine(RexxString *name)
    name = name->upper();
    ProtectedObject p(name);


PackageManager.cpp                          done v4.2 work
bool PackageManager::callNativeRoutine(RexxActivity *activity, RexxString *name,
    name = name->upper();
    ProtectedObject p(name);


ProtectedObject.hpp                         not done (for me it's useful, but modifying this class may be not appreciated)
// To let the compiler tell you it's forbidden !
// You want to assign a rexx object, not an other protected object.
// The list of protected objects is broken if such an assignement is done.
private:
    ProtectedObject(const ProtectedObject&);
    ProtectedObject &operator=(const ProtectedObject&);


QueueClass.cpp                              done v4.2 work
RexxObject *RexxQueue::supplier()
    RexxArray *values = this->makeArray();          /* convert into an array             */
    ProtectedObject p(values);


QueueClass.cpp                              done v4.2 work
RexxObject *RexxQueue::newRexx(RexxObject **init_args, size_t argCount)
    RexxObject *newObj =  new RexxQueue;             /* get a new queue                   */
    ProtectedObject p(newObj);


QueueInstruction.cpp                        done v4.2 work
void RexxInstructionQueue::execute(
    ProtectedObject p_value;
    ...
        value = REQUEST_STRING(result);    /* get the string version            */
        p_value = value;


RaiseInstruction.cpp                        done v4.2 work
void RexxInstructionRaise::execute(
    ProtectedObject p_result;
    ProtectedObject p_description;
    ProtectedObject p_additional;
...
        _additional = TheNullArray->copy(); /* change default additional info    */
        p_additional = _additional;
...
        errorcode = REQUEST_STRING(rc);    /* get the string version            */
        ProtectedObject p(errorcode);
...
        _description = (RexxString *)this->description->evaluate(context, stack);
        p_description = _description;
...
        _additional = this->additional[0]->evaluate(context, stack);
        p_additional = _additional;
...
        _result = this->result->evaluate(context, stack);
        p_result = _result;
...
            _additional = REQUEST_ARRAY(_additional);
            p_additional = _additional;


RelationClass.cpp                           already done in official v4.2
RexxObject *RexxRelation::newRexx(
    RexxRelation *newObj = new_relation();             /* get a new relation                */
    ProtectedObject p(newObj);


RexxActivation.cpp                          not done, not needed 4.2
void RexxActivation::live(size_t liveMark)
    memory_mark(this->contextObject);
    memory_mark(this->arguments); // arguments can be user-redefined (ex : yield), must be marked


RexxActivation.cpp                          not done, not needed 4.2
void RexxActivation::liveGeneral(int reason)
    memory_mark_general(this->contextObject);
    memory_mark_general(this->arguments); // arguments can be user-redefined (ex : yield), must be marked


RexxActivation.cpp                          done 4.2, 4.2 work
void RexxActivation::raise(
{
    ProtectedObject p_conditionobj;
...
        conditionobj = new_directory();    /* get a new directory               */
        p_conditionobj = conditionobj;


RexxActivation.cpp                          was cancelled, nothing to apply for 4.2
RexxObject *RexxActivation::evaluateLocalCompoundVariable(RexxString *stemName, size_t index, RexxObject **tail, size_t tailCount)
    if (tracingIntermediates())
    {
        ProtectedObject p(stem_table);


// JLF : fix of Rony problem ? NO !
RexxActivation.cpp                          done 4.2, 4.2 work (keep the change made in official, which is different)
StackFrameClass *RexxActivation::createStackFrame()
    ProtectedObject p_arguments(arguments); // getArguments() returns a new array, so must be protected
    ProtectedObject p;
    return new (p) StackFrameClass(type, getMessageName(), (BaseExecutable *)getExecutableObject(), target, arguments, getTraceBack(), getContextLineNumber());


RexxActivation.hpp                          not needed 4.2
   RexxActivation      *parent;        // previous running activation for internal call/interpret
   RexxArray           *arguments;     /* user-redefined, GC protected      */          <-- jlf : new
   RexxObject         **arglist;       /* activity argument list            */


RexxActivity.cpp                            done v4.2 work
RexxDirectory *RexxActivity::createConditionObject(RexxString *condition, RexxObject *rc, RexxString *description, RexxObject *additional, RexxObject *result)
    RexxDirectory *conditionObj = new_directory();
    ProtectedObject p(conditionObj);


RexxActivity.cpp                            done v4.2 work
RexxString *RexxActivity::messageSubstitution(
    size_t substitutions = additional->size();  /* get the substitution count        */
    /* RexxString * */ ProtectedObject newmessage = OREF_NULLSTRING;        /* start with a null string          */
...
        /* RexxString * */ ProtectedObject front = message->extractC(0, subposition - 1);
        /* pull off the remainder            */
        /* RexxString * */ ProtectedObject back = message->extractC(subposition + 1, message->getCLength() - (subposition + 1));
...
        /* not a good number?                */
        /* RexxString * */ ProtectedObject stringVal = OREF_NULLSTRING;
...
        /* accumulate the front part         */
        ProtectedObject front_stringVal = ((RexxString*)front)->concat(stringVal);
        newmessage = ((RexxString*)newmessage)->concat(front_stringVal);
...
    /* add on any remainder              */
    newmessage = ((RexxString*)newmessage)->concat(message);


RexxActivity.cpp                            done v4.2 work
RexxObject *RexxActivity::display(RexxDirectory *exobj)
    /* get the header                    */
    /* RexxString * */ ProtectedObject text = SystemInterpreter::getMessageHeader(errorCode);
...
    else                                 /* add to the message text           */
    {
        text = ((RexxString*)text)->concat(SystemInterpreter::getMessageText(Message_Translations_error));
...
    /* add on the error number           */
    ProtectedObject rcString = REQUEST_STRING(rc);
    text = ((RexxString*)text)->concatWith(rcString, ' ');
...
        /* add on the "running" part         */
        text = ((RexxString*)text)->concatWith(SystemInterpreter::getMessageText(Message_Translations_running), ' ');
        /* add on the program name           */
        text = ((RexxString*)text)->concatWith(programname, ' ');
...
            /* Yes, add on the "line" part       */
            text = ((RexxString*)text)->concatWith(SystemInterpreter::getMessageText(Message_Translations_line), ' ');
            /* add on the line number            */
            ProtectedObject positionString = REQUEST_STRING(position);
            text = ((RexxString*)text)->concatWith(positionString, ' ');
...
    text = ((RexxString*)text)->concatWithCstring(":  ");
    /* and finally the error message     */
    text = ((RexxString*)text)->concat((RexxString *)exobj->at(OREF_ERRORTEXT));
...
        else                               /* add to the message text           */
        {
            text = ((RexxString*)text)->concat(SystemInterpreter::getMessageText(Message_Translations_error));
        }
        /* add on the error number           */
        text = ((RexxString*)text)->concatWith((RexxString *)rc, ' ');
        /* add on the ":  "                  */
        text = ((RexxString*)text)->concatWithCstring(":  ");
        /* and finally the error message     */
        text = ((RexxString*)text)->concat(secondary);


RexxActivity.cpp                            done v4.2 work
RexxObject *RexxActivity::displayDebug(RexxDirectory *exobj)
  RexxString *secondary;               /* secondary message                 */
  /* RexxString * */ ProtectedObject text;/* constructed final message         */
...
  ProtectedObject rcString = REQUEST_STRING(exobj->at(OREF_RC));
  text = ((RexxString*)text)->concatWith(rcString, ' ');
                                       /* add on the ":  "                  */
  text = ((RexxString*)text)->concatWithCstring(":  ");
                                       /* and finally the error message     */
  text = ((RexxString*)text)->concatWith((RexxString *)exobj->at(OREF_ERRORTEXT), ' ');
...
    text = ((RexxString*)text)->concatWith((RexxString *)exobj->at(OREF_CODE), ' ');
                                       /* add on the ":  "                  */
    text = ((RexxString*)text)->concatWithCstring(":  ");
                                       /* and finally the error message     */
    text = ((RexxString*)text)->concat(secondary);


RexxActivity.cpp                            not done, specific to executor
void  RexxActivity::traceOutput(       /* write a line of trace information */
    ProtectedObject p_line = line->stringTrace(); /* get traceable form of this        */
    + casts


RexxBehaviour.cpp                           done 4.2, 4.2 work
RexxObject *RexxBehaviour::copy()
    RexxBehaviour *newBehaviour = (RexxBehaviour *)this->clone();
    ProtectedObject p(newBehaviour);


RexxCompoundTable.cpp                       done v4.2 work
RexxCompoundElement *RexxCompoundTable::findEntry(
    /* create a new compound variable */
    ProtectedObject p_tailString(tail->makeString());
    anchor = new_compoundElement(p_tailString);


RexxInstruction.cpp                         already done in official v4.2
RexxInstructionRaise::execute
    _result to protect (done)
    _description to protect (done)
    _additional to protect (done)


RexxNativeActivation.cpp                    done v4.2 work
int RexxNativeActivation::stemSort(const char *stemname, int order, int type, size_t start, size_t end, size_t firstcol, size_t lastcol)
        RexxString *tail = OREF_NULLSTRING ;
        ProtectedObject p2(tail); // JLF useless here !
...
            tail = tail->upper();
            p2 = tail; // JLF here, it's useful


RexxNativeActivation.cpp                    done v4.2 work (keep the change made in official, which is different)
StackFrameClass *RexxNativeActivation::createStackFrame()
    ProtectedObject p;
    return new (p) StackFrameClass(type, getMessageName(), (BaseExecutable *)getExecutableObject(), receiver, getArguments(), new_string(COMPILED_MARKER), SIZE_MAX);


RexxVariableDictionary.cpp                  done v4.2
RexxVariableBase  *RexxVariableDictionary::getVariableRetriever(
    variable = variable->upper();        /* upper case the variable           */
    ProtectedObject p(variable);


RoutineClass.cpp                            done v4.2
RexxObject *RoutineClass::callWithRexx(RexxArray *args)
    args = arrayArgument(args, ARG_ONE);
    ProtectedObject p(args);


RoutineClass.cpp                            done v4.2
RoutineClass *RoutineClass::newRoutineObject(RexxString *pgmname, RexxObject *source, RexxObject *position, RexxSource *parentSource)
        RexxString *sourceString = source->makeString();
        ProtectedObject p(sourceString);
...
            RexxString *sourceString = newSourceArray ->get(counter)->makeString();
            ProtectedObject p(sourceString);


RoutineClass.cpp                            done v4.2
RoutineClass *RoutineClass::newRoutineObject(RexxString *pgmname, RexxArray *source, RexxObject *position)
            RexxString *sourceString = newSourceArray ->get(counter)->makeString();
            ProtectedObject p(sourceString);


SayInstruction.cpp                          done v4.2
void  RexxInstructionSay::execute(
    RexxString *value;                   /* string version of output value    */
    ProtectedObject p_value;
...
        value = REQUEST_STRING(result);    /* get the string version            */
        p_value = value;


SignalInstruction.cpp                       done v4.2
void RexxInstructionSignal::execute(
            stringResult = REQUEST_STRING(result);
            ProtectedObject p(stringResult);


SourceFile.cpp                              not done, specific executor
void RexxSource::live(size_t liveMark)
  memory_mark(this->interpret_activation);      <-- jlf : added by me
}


SourceFile.cpp                              not done, specific executor
void RexxSource::liveGeneral(int reason)
  memory_mark_general(this->interpret_activation);  <-- jlf : added by me
}


SourceFile.cpp                              not done, specific executor
void RexxSource::flatten (RexxEnvelope *envelope)
    this->securityManager = OREF_NULL;
    this->interpret_activation = OREF_NULL;         <-- jlf : added by me
...
    flatten_reference(newThis->interpret_activation, envelope);

  cleanUpFlatten
}


SourceFile.cpp                              done v4.2 but keeping the changes of official
StackFrameClass *RexxSource::createStackFrame()
    ProtectedObject p;
    return new (p) StackFrameClass(FRAME_PARSE, programName, OREF_NULL, OREF_NULL, OREF_NULL, traceBack(clauseLocation, 0, true), clauseLocation.getLineNumber());


SourceFile.cpp                              done v4.2 but differently from executor
RexxString *RexxSource::extract(
    /* RexxString * */ ProtectedObject line = OREF_NULLSTRING;  /* returned source line              */
    RexxString *source_line;             /* current extracting line           */
    size_t  counter;                     /* line counter                      */
...
            /* concatenate the next line on      */
            if (newline) line = ((RexxString*)line)->concatWith(this->get(counter), '\n');
            else line = ((RexxString*)line)->concat(this->get(counter));
        }
        /* now add on the last part          */
        if (newline) line = ((RexxString*)line)->concatWith(this->get(counter)->extractB(0, location.getEndOffset()), '\n');
        else line = ((RexxString*)line)->concat(this->get(counter)->extractB(0, location.getEndOffset()));


SourceFile.cpp                              done v4.2
RexxClass *RexxSource::findClass(RexxString *className)
    RexxString *internalName = className->upper();   /* upper case it                     */
    ProtectedObject p(internalName);


SourceFile.cpp                              done v4.2
void RexxSource::classDirective()
    RexxString *public_name = this->commonString(name->upper());
    ProtectedObject p(public_name);


SourceFile.cpp                              done v4.2
void RexxSource::methodDirective()
    RexxString *internalname = this->commonString(name->upper());
    ProtectedObject p(internalname);
...
            decodeExternalMethod(internalname, externalname, library, procedure);
            ProtectedObject p_library(library);
            ProtectedObject p_procedure(procedure);


SourceFile.cpp                              done v4.2
void RexxSource::attributeDirective()
    RexxString *internalname = this->commonString(name->upper());
    ProtectedObject p(internalname);
...
                decodeExternalMethod(internalname, externalname, library, procedure);
                ProtectedObject p_library(library);
                ProtectedObject p_procedure(procedure);
...
                decodeExternalMethod(internalname, externalname, library, procedure);
                ProtectedObject p_library(library);
                ProtectedObject p_procedure(procedure);
...
                    procedure = procedure->concatToCstring("GET");
                    p_procedure = procedure;
...
                decodeExternalMethod(internalname, externalname, library, procedure);
                ProtectedObject p_library(library);
                ProtectedObject p_procedure(procedure);
...
                    procedure = procedure->concatToCstring("SET");
                    p_procedure = procedure;


SourceFile.cpp                              done v4.2
void RexxSource::constantDirective()
    RexxString *internalname = this->commonString(name->upper());
    ProtectedObject p(internalname);


SourceFile.cpp                              done v4.2 but differently from executor
RexxString *RexxSource::commonString(
    ProtectedObject p(string); // JLF I see a lot of calls where string is a not protected object


SourceFile.cpp                              not done because the fix for commonString is enough
RexxArray  *RexxSource::words(
    word = ((RexxString *)(string->word(IntegerOne)))->upper();
    ProtectedObject p(word);


SourceFile.cpp                              not done... complicated, many occurences of _instruction
RexxCode *RexxSource::translateBlock(
    jlf : _instruction to protect ? (not done)


SourceFile.cpp                              already done
RexxArray *RexxSource::extractSource(
        /* get the result array              */
        RexxArray *source = new_array(location.getEndLine() - location.getLineNumber() + 1);
        ProtectedObject p(source);


StackFrameClass.cpp                         already done
void StackFrameClass::live(size_t liveMark)
    memory_mark(this->objectVariables);
}


StackFrameClass.cpp                         already done
void StackFrameClass::liveGeneral(int reason)
    memory_mark_general(this->objectVariables);
}


StackFrameClass.cpp                         already done
void StackFrameClass::flatten(RexxEnvelope *envelope)
  newThis->objectVariables = OREF_NULL;

  cleanUpFlatten
}


StackFrameClass.cpp                         already done
#include "ProtectedObject.hpp"


StackFrameClass.cpp                         not done, no longer needed because I kept the official approach
/**
 * Allocate a new GC-protected StackFrame object
 *
 * @param size   The size of the object.
 * @param p      The protected object
 *
 * @return The newly allocated object.
 */
void *StackFrameClass::operator new(size_t size, ProtectedObject &p)
{
    /* Get new object                    */
    p = new_object(size, T_StackFrame);
    return p;
}


StackFrameClass.hpp                         not done, no longer needed because I kept the official approach
class RexxSource;
class ProtectedObject;
...
    void *operator new(size_t);
    void *operator new(size_t, ProtectedObject &);      <-- this one was added by me, but no longer needed


StemClass.cpp                               done v4.2
RexxObject *RexxStem::request(
    makeclass = stringArgument(makeclass, ARG_ONE)->upper();
    ProtectedObject p(makeclass);


StemClass.cpp                               already done
RexxObject *RexxStem::newRexx(
    newObj = new RexxStem ((RexxString *)name);   /* get a new stem                    */
    ProtectedObject p(newObj);


StringClass.cpp                             already done
RexxString *RexxString::newRexx(RexxObject **init_args, size_t argCount)
    string = new_string(string->getStringData(), string->getBLength(), string->getCLength(), string->getCharset(), string->getEncoding());
    ProtectedObject p(string);


SupplierClass.cpp                           already done
RexxObject  *RexxSupplierClass::newRexx(
    RexxObject *newObj = new RexxSupplier();
    ProtectedObject p = newObj;


TableClass.cpp                              already done
#include "ProtectedObject.hpp"


TableClass.cpp                              already done
RexxObject *RexxTable::newRexx(
    RexxTable *newObj = new_table();                /* get a new table                   */
    ProtectedObject p(newObj);


TraceInstruction.cpp                        not done (not sure it's needed)
void RexxInstructionTrace::execute(
        result = this->expression->evaluate(context, stack);
        ProtectedObject p_result(result);
        value = REQUEST_STRING(result);    /* force to string form              */
        ProtectedObject p_value(value);


WeakReferenceClass.cpp                      already done
void WeakReference::live(size_t liveMark)
    // we need to get called, but we don't do any marking of the referent.
    // we do, however, need to mark the object variables in case this is a subclass.
    memory_mark(this->objectVariables);


WeakReferenceClass.cpp                      already done
void WeakReference::liveGeneral(int reason)
    // this might be a subclass, so we need to mark the object variables always
    memory_mark_general(this->objectVariables);


WeakReferenceClass.cpp                      already done
void WeakReference::flatten(RexxEnvelope *envelope)
  setUpFlatten(WeakReference)
   // not normally needed, but this might be a subclass
   flatten_reference(newThis->objectVariables, envelope);


WeakReferenceClass.cpp                      already done
RexxObject *WeakReference::newRexx(RexxObject **init_args, size_t argCount)
  RexxObject *newObj = new WeakReference(refObj);
  ProtectedObject p(newObj);

===============================================================================
2015 sept 13

GC review
stringArgument can return a new string
which should be protected
--> review all the calls of stringArgument : done

idem optionalStringArgument : done
idem ->requiredString : done
idem requiredStringArg : no problem, stored in expression stack
idem required_string : no problem, stored in expression stack
idem requestArray : done
idem REQUEST_ARRAY : done
idem makeArray : done


===============================================================================
2013 apr 13

[GC]
Fix crash due to unprotected object.
In ClassClass.cpp
method RexxClass::enhanced : enhanced_instance_mdict must be GC-protected.
method RexxClass::subclass : enhancing_class_methods must be GC-protected.


===============================================================================
2012 mar 23

Remember :
GC crash while running functional-test.rex :
The list of protected objects was corrupted, because of that :
In RexxExpressionMessage::evaluate (ExpressionMessage.cpp), I declared _target as a protected object.
The assignment result = _target, which was supposed to store the RexxObject target in the protected
object result, corrupted the list of protected objects because the default operator= stored a copy of
all the attributes of _target onto the protected object result, overwriting the next attribute.
Fixed by declaring these methods private :
    ProtectedObject(const ProtectedObject&);
    ProtectedObject &operator=(const ProtectedObject&);
Now the compiler forces to cast like that :
result = (RexxObject*)_target
[later]
I think I don't need to protect the intermediate objects returned by ->evaluate, because they should
be protected by the stack. I keep the changes made to ProtectedObject.


===============================================================================
2012 mar 06

Another GC crash
 	rexx.dll!RexxMemory::markObjectsMain(RexxObject * rootObject)  Line 373 + 0xc bytes	C++
 	rexx.dll!RexxMemory::markObjects()  Line 653	C++
 	rexx.dll!RexxMemory::collect()  Line 1030	C++
 	rexx.dll!NormalSegmentSet::handleAllocationFailure(unsigned int allocationLength)  Line 1272	C++
 	rexx.dll!RexxMemory::newObject(unsigned int requestLength, unsigned int type)  Line 1110 + 0x12 bytes	C++
 	rexx.dll!new_object(unsigned int s, unsigned int t)  Line 426 + 0x1e bytes	C++
 	rexx.dll!RexxListTable::operator new(unsigned int size, unsigned int initialSize)  Line 94 + 0x16 bytes	C++
 	rexx.dll!RexxList::getFree()  Line 123 + 0x12 bytes	C++
 	rexx.dll!RexxList::insert(RexxObject * _value, RexxObject * _index)  Line 556 + 0x8 bytes	C++
 	rexx.dll!RexxList::append(RexxObject * _value)  Line 542	C++
 	rexx.dll!RexxActivity::generateProgramInformation(RexxDirectory * exobj)  Line 941	C++
 	rexx.dll!RexxActivity::createExceptionObject(long errcode, RexxString * description, RexxArray * additional, RexxObject * result)  Line 894	C++
 	rexx.dll!RexxActivity::raiseException(long errcode, RexxString * description, RexxArray * additional, RexxObject * result)  Line 774 + 0x18 bytes	C++
 	rexx.dll!RexxActivation::raise(RexxString * condition, RexxObject * rc, RexxString * description, RexxObject * additional, RexxObject * resultObj, RexxDirectory * conditionobj)  Line 1639	C++
 	rexx.dll!RexxActivation::raiseExit(RexxString * condition, RexxObject * rc, RexxString * description, RexxObject * additional, RexxObject * resultObj, RexxDirectory * conditionobj)  Line 1544	C++
>	rexx.dll!RexxInstructionRaise::execute(RexxActivation * context, RexxExpressionStack * stack)  Line 280	C++
 	rexx.dll!RexxActivation::run(RexxObject * _receiver, RexxString * msgname, RexxObject * * _arglist, unsigned int _argcount, RexxInstruction * start, ProtectedObject & resultObj)  Line 544	C++
----------
Review of RexxInstructionRaise::execute
    _result to protect (done)
    _description to protect (done)
    _additional to protect (done)
Review of RexxActivation::raise
    _conditionObj to protect if not a propagation, because new directory created (done)


Previous protection are not enough... Crash again.
Now using /DCHECKOREFS
 	rexx.dll!RexxInternalObject::getObjectTypeNumber()  Line 2045 + 0x3 bytes	C++
 	rexx.dll!RexxInternalObject::isObjectType(unsigned int t)  Line 263 + 0xf bytes	C++
 	rexx.dll!RexxMemory::objectReferenceOK(RexxObject * o)  Line 339 + 0xa bytes	C++
 	rexx.dll!RexxMemory::orphanCheckMark(RexxObject * markObject, RexxObject * * pMarkObject)  Line 1565 + 0xc bytes	C++
 	rexx.dll!RexxMemory::markGeneral(void * obj)  Line 1471	C++
 	rexx.dll!StackFrameClass::liveGeneral(int reason)  Line 143	C++
 	rexx.dll!RexxMemory::killOrphans(RexxObject * rootObject)  Line 440	C++
 	rexx.dll!RexxMemory::markObjects()  Line 641	C++
 	rexx.dll!RexxMemory::collect()  Line 1030	C++
 	rexx.dll!NormalSegmentSet::handleAllocationFailure(unsigned int allocationLength)  Line 1272	C++
 	rexx.dll!RexxMemory::newObject(unsigned int requestLength, unsigned int type)  Line 1110 + 0x12 bytes	C++
 	rexx.dll!new_object(unsigned int s, unsigned int t)  Line 426 + 0x1e bytes	C++
 	rexx.dll!RexxListTable::operator new(unsigned int size, unsigned int initialSize)  Line 94 + 0x16 bytes	C++
 	rexx.dll!RexxList::getFree()  Line 123 + 0x12 bytes	C++
 	rexx.dll!RexxList::insert(RexxObject * _value, RexxObject * _index)  Line 556 + 0x8 bytes	C++
 	rexx.dll!RexxList::append(RexxObject * _value)  Line 542	C++
 	rexx.dll!RexxActivity::generateProgramInformation(RexxDirectory * exobj)  Line 941	C++
 	rexx.dll!RexxActivity::createExceptionObject(long errcode, RexxString * description, RexxArray * additional, RexxObject * result)  Line 894	C++
 	rexx.dll!RexxActivity::raiseException(long errcode, RexxString * description, RexxArray * additional, RexxObject * result)  Line 774 + 0x18 bytes	C++
 	rexx.dll!RexxActivation::raise(RexxString * condition, RexxObject * rc, RexxString * description, RexxObject * additional, RexxObject * resultObj, RexxDirectory * conditionobj)  Line 1641	C++
 	rexx.dll!RexxActivation::raiseExit(RexxString * condition, RexxObject * rc, RexxString * description, RexxObject * additional, RexxObject * resultObj, RexxDirectory * conditionobj)  Line 1544	C++
 	rexx.dll!RexxInstructionRaise::execute(RexxActivation * context, RexxExpressionStack * stack)  Line 289	C++
 	rexx.dll!RexxActivation::run(RexxObject * _receiver, RexxString * msgname, RexxObject * * _arglist, unsigned int _argcount, RexxInstruction * start, ProtectedObject & resultObj)  Line 544	C++
 	rexx.dll!RexxCode::run(RexxActivity * activity, RexxMethod * method, RexxObject * receiver, RexxString * msgname, RexxObject * * argPtr, unsigned int argcount, ProtectedObject & result)  Line 136	C++
 	rexx.dll!RexxMethod::run(RexxActivity * activity, RexxObject * receiver, RexxString * msgname, RexxObject * * argPtr, unsigned int count, ProtectedObject & result)  Line 325	C++
>	rexx.dll!RexxObject::messageSend(RexxString * msgname, RexxObject * * arguments, unsigned int count, ProtectedObject & result)  Line 793	C++             // JLF : "yield"
----------
objectReferenceOK :
o = 0x7f23f050 {objectVariables=0x00000000 operatorMethods=0x00558920 classInstance=0x7fcc0a50 }
    objectSize = 6
    instanceClass.id = "Object"
    RexxBehaviour *type = o->getObjectType();       // JLF : NULL
StackFrameClass::liveGeneral :
    memory_mark_general(this->name);                // JLF this->name = 0x7f23f050
        this = 0x7de6d440 {type=0x0052ee64 "METHOD" name=0x7f23f050 executable=0x7fcc2e90 ...}
So we have a problem with the argument 'name' passed to the StackFrameClass constructor.
RexxActivation::createStackFrame
    pass getMessageName() : I don't see a problem here, because returns this->settings.msgname which is protected.
    The name stored in settings.msgname comes from the method RexActivation::run, I don't think there is a problem here.
    But I see a potential problem with the local variable 'arguments' : receives a new array returned by getArguments() --> must be protected (done)
RexxNativeActivation::createStackFrame
    pass getMessageName() : I don't see a problem here, because returns this->msgname which is protected.
    The names comes from :
        RexxNativeActivation::run : _msgname
        RexxNativeActivation::callNativeRoutine : functionName
            RexxNativeRoutine::call : functionName
        RexxNativeActivation::callRegisteredRoutine : functionName
            RegisteredRoutine::call : functionName
RexxSource::createStackFrame
    pass programName : I don't see a problem here
    The programName comes from :
        RexxSource::RexxSource
PackageManager::callNativeRoutine
    Maybe a problem here : name = name->upper(); --> to protect (done)
SystemInterpreter::invokeExternalFunction : target
    RexxActivation::externalCall : target
        RexxInstructionCall::execute --> I see a problem here : _name = REQUEST_STRING(result) --> to protect (done)
RexxActivation::callExternalRexx : target


review of risky code :
->upper
    RexxBehaviour::methodObject : no risk ?
    RexxClass::defineMethod : done
    RexxClass::defineClassMethod : done
    RexxClass::deleteMethod : done
    RexxClass::method : done
    RexxClass::methodDictionaryCreate : done
    RexxDirectory::setEntry : done
    RexxDirectory::remove : no risk ?
    RexxDirectory::setMethod : done
    RexxObject::instanceMethod : to protect because of reportException (done)
    RexxObject::setMethod : done
    RexxObject::unsetMethod : done
    RexxObject::requestRexx : two variables to protect (done)
    RexxObject::decodeMessageName : no risk ?
    RexxObject::defMethods : done
    RexxObject::defMethod : done
    RexxStem::request : done
    RexxNativeActivation::stemSort : incomplete protection (fixed)
    RexxVariableDictionary::getVariableRetriever : done
    BUILTIN(VALUE) : to protect (done, the code has been slightly rewritten)
    RexxInstructionForward::execute : done
    PackageManager::createRegisteredRoutine : done
    PackageManager::dropRegisteredRoutine : done
    PackageManager::queryRegisteredRoutine : done
    PackageManager::callNativeRoutine : done
    RexxSource::findClass : done
    RexxSource::classDirective : done
    RexxSource::extensionDirective : done
    RexxSource::methodDirective : done
    RexxSource::attributeDirective : done
    RexxSource::constantDirective : done
    RexxSource::words : done
    Interpreter::findClass : I think it must be protected because a method could be attached to the environment, no ? (done)
    InterpreterInstance::resolveCommandHandler : done
    SystemInterpreter::valueFunction : no risk, I think
    SystemInterpreter::valueFunction : I think it's ok, SystemInterpreter::allocateResultMemory has no relation with GC
REQUEST_STRING (requestString)
    RexxClass::methodDictionaryMerge : done
    RexxClass::methodDictionaryCreate : already done
    RexxInteger::concatBlank : to protect, I think (done)
    RexxInteger::concat : to protect, I think (done)
    RexxObject::copyIntoTail : done
    RexxObject::concatRexx : done
    RexxObject::concatBlank : done
    RexxStem::sort : is there a risk of GC in array->put(nextValue, j + bounds) ? (NOT done)
    StringClass.cpp : I hope it's ok ! did not investigate
    RexxActivity::display : done, but really not sure if I need to do that
    RexxActivity::displayDebug :  done, but really not sure if I need to do that
    RexxActivity::callFunctionExit : nothing done, I don't understand the code with temp
    RexxInstructionDo::execute : done
    RexxInstructionDo::controlSetup : done
    RexxInstructionForward::execute : done
    RexxInstructionInterpret::execute : done
    RexxInstructionOptions::execute : done
    RexxInstructionQueue::execute : done
    RexxInstructionRaise::execute : done
    RexxInstructionSay::execute : done
    RexxInstructionSignal::execute : done
    RexxInstructionTrace::execute : done
requestString
    RexxMethod::newRexx : I think protection is needed (done)
    RexxNativeActivation::processArguments : is ok, according to the comment
    RexxExpressionStack::requiredStringArg : done
    RexxExpressionStack::optionalStringArg : done
makeString
    RexxMethod::newMethodObject : done
    RoutineClass::newRoutineObject : done
    RoutineClass::newRoutineObject : done
    RexxCompoundTable::findEntry : done
arrayArgument (requestArray)
    RexxObject::sendWith : for me, protection is needed, no ? (done)
    RexxObject::startWith : for me, protection is needed, no ? (done)
    RexxObject::decodeMessageName : for me, protection is needed, no ? (done)
    PackageClass::loadPackage : for me, protection is needed, no ? (done)
    PackageClass::newRexx :  for me, protection is needed, no ? (done)
    RoutineClass::callWithRexx : for me, protection is needed, no ? (done)
    RexxNativeActivation::processArguments : is ok, according to the comment
    RexxNativeActivation::objectToValue : is ok, according to the comment
requestArray (makeArray)
    RexxMethod::newMethodObject : already protected
    RoutineClass::newRoutineObject : already protected
makeArray
    RexxArray::toString : already protected
    RexxList::supplier : done
    RexxQueue::supplier : done
    RexxActivity::display : already protected
    RexxInstructionDo::execute : is ok, assigned to this
    RexxSource::getGuard : is ok, assigned to this
->request
    Nothing new to protect (requestString and requestArray already reviewed)
required_string (macro, requiredStringArg)
    requiredStringArg already reviewed
optional_string (macro, optionalStringArg)
    optionalStringArg already reviewed
decodeMessageName : the string returned in messageName is not protected, see what's done by the caller
    RexxObject::sendWith : for me, protection needed, no ? (done)
    RexxObject::send : for me, protection needed, no ? (done)
    RexxObject::startCommon : for me, protection needed, no ? (done)
    RexxMessage::newRexx : for me, protection needed, no ? (done)
->concat
    RexxObject::requestRexx : I think it's ok, methodLookup should not trigger a GC, right ?
    RexxActivity::messageSubstitution : done
    RexxActivity::traceOutput : done
    RexxSource::commonString : no "->concat" inside, but while looking for "->concat", I saw a lot of calls to commonString where the passed parameter is not protected. Now the parameter string is protected.
    RexxSource::callNew : done
    RexxSource::raiseNew : done
    RexxSource::signalNew : done
    RexxSource::extract : done
    RexxSource::methodDirective : done
    RexxSource::attributeDirective : done
->evaluate
    RexxActivation::evaluateLocalCompoundVariable : done --> cancelled
    <to continue...> --> not needed, the objects should be protected by the stack
decodeExternalMethod
    RexxSource::methodDirective : done
    RexxSource::attributeDirective : done


===============================================================================
2012 mar 04

Fixed a GC crash.
RexxActivity::generateProgramInformation calls createStackFrame.
In RexxActivation::createStackFrame, the last line is
    return new StackFrameClass(type, getMessageName(), (BaseExecutable *)getExecutableObject(), target, arguments, getTraceBack(), getContextLineNumber());
The operator 'new' of StackFrameClass is overloaded and returns a new object before the constructor is called.
This object is not protected.
The call to getTraceBack triggered a GC and the new object was put on the list of dead objects.
The object is returned to generateProgramInformation which puts it in the stackFrames list.
Later, crash because the behaviour pointer of the stack frame is NULL.
Fixed by passing a ProtectedObject to the 'new' operator of StackFrameClass.
Applied the same fix to :
RexxSource::createStackFrame
RexxNativeActivation::createStackFrame


Fixed another GC crash, but less sure I identified the real problem...
A crash occured while searching the method ~available on a supplier. The behaviour was NULL.
I have a subclass of Supplier (CoactivitySupplier) whose init method creates an empty array.
That could explain the problem : in case of GC during init, the supplier is put on the list of dead objects.
After modifying RexxSupplierClass::newRexx to protect newObj before sending the message "init",
no more crash (for the moment).


Remember :
Fix done in RexxSupplierClass::newRexx also done in :
(search for OREF_INIT in interpreter source files)
RexxDirectory::newRexx
RexxIdentityTable::newRexx
RexxList::newRexx
RexxMessage::newRexx
PackageClass::newRexx
RexxQueue::newRexx
RexxRelation::newRexx
RexxStem::newRexx
RexxString::newRexx
RexxSupplierClass::newRexx
RexxTable::newRexx
WeakReference::newRexx


ContextClass : mark this->objectVariables.
It's an exported class, so better to do that... (done)


===============================================================================
2011 oct 26

Fixed a crash in relation with RexxContextualSource and GC :
Must mark objectVariables.


===============================================================================
2011 aug 16

Fixed a crash in relation with source literals and GC.
Two problems :
1) Forgot to replace RexxDirectory by RexxList when disabling the optimization
for source literals (was a copy-paste of optimization done for string literals).
2) The constructor RexxSourceLiteral::RexxSourceLiteral can trigger a GC. Must protect
'this'.


Remember1:
----------
When the crash occurs during GC (ex : in ObjectHeader::isObjectMarked), it's possible
to see which ooRexx object is corrupted. Here the object is 0x7eeff200
 	rexx.dll!ObjectHeader::isObjectMarked(unsigned int mark)  Line 106 + 0xa bytes	C++
 	rexx.dll!RexxInternalObject::isObjectMarked(unsigned int markword)  Line 247 + 0x16 bytes	C++
 	rexx.dll!RexxListTable::live(unsigned int liveMark)  Line 55 + 0x26 bytes	C++
>	rexx.dll!RexxMemory::markObjectsMain(RexxObject * rootObject)  Line 374	C++                 <-- markObject = 0x7eeff200 {size=2129676696 elements=0x7eeff214 }  RexxListTable with OVERWRITTEN size !!!
 	rexx.dll!RexxMemory::markObjects()  Line 645	C++
 	rexx.dll!RexxMemory::collect()  Line 1022	C++

A conditional break "newObj == 0x7eeff200" on the last line of RexxMemory::newObject (RexxMemory.cpp)
lets stop the execution when the object is created. If too long, then modify the source :
    if (newObj == (RexxObject*)0x7eeff200)
    {
        int dummy=0;    //  <-- put breakpoint here
    }
    return newObj;
Once the interpreter is stopped here, it's relatively easy to do a code review of the methods
in the call stack, to check if an intermediate object must be protected.

If needed, a data breakpoint can be set on the part of memory which is overwritten
(here the 'size' attribute). In my case, was triggered when the object was inserted
in the list of dead objects.


Remember2:
----------
Occurences of new_directory, not protected (no crash so far, except for createConditionObject) :
DirectoryClass.cpp, RexxDirectory::newRexx (05/03/2012 : done when fixing OREF_INIT)
ExceptionClass.cpp, ExceptionClass::getCondition (05/03/2012 : done)
RexxActivation.cpp, RexxActivation::raise  : here, the conditionObj is passed by argument.
                                             BUT there is one case where conditionObj is created. To protect !
    called by RexxActivation::raiseExit --> the directory conditionobj is passed by argument, no need of protect here.
        called by RexxInstructionRaise::execute --> the directory conditionobj is created here, seems ok because comes from context->getConditionObj()
                                                    [06/03/2012] Got a GC crash where RexxInstructionRaise::execute is in the call stack...
                                                                 After a new review, I think that following variables must be protected : _result, _additional
    called by RexxInstructionRaise::execute --> the directory is created here, seems ok because comes from context->getConditionObj().
RexxActivity.cpp, RexxActivity::createConditionObject (fixed in sandbox)

Other potential problems. A fresh created object is not protected, and some calls are made that could trigger GC.
RexxBehaviour.cpp, RexxBehaviour::copy : newBehaviour is not protected. (05/03/2012 : done)
RexxBehaviour.cpp, RexxBehaviour::addScope : this->scopes->allAt(TheNilObject) creates an object which is not protected. (05/03/2012 : added to this->scopes, so seems protected)
RexxCollection.cpp, RexxHashTableCollection::copy : newObj is not protected.
    Should be protected only if ActivityManager::currentActivity != NULL, otherwise crash in implementation of ProtectedObject's methods
    (RexxHashTableCollection::copy is called during interpreter initialization, and at this time, ActivityManager::currentActivity == NULL).
ArrayClass.cpp, RexxArray::copy : newArray is not protected.
ClassClass.cpp, RexxClass::defineMethod : method_name and method_object are not protected.
ClassClass.cpp, RexxClass::methodDictionaryCreate : method_name is not protected.
DirectoryClass.cpp, RexxDirectory::copy : newObj is not protected.
ListClass.cpp, RexxList::copy : newList is not protected.
ObjectClass.cpp, RexxObject::copy : newObj is not protected.
ObjectClass.cpp, RexxObject::defMethod : msgname and methcopy are not protected.
InstructionParser.cpp, RexxSource::signalNew : newObject is not protected.
SourceFile.cpp, RexxSource::translateBlock : _instruction is not protected.


===============================================================================
2011 aug 14

Fixed a crash that occured after GC : in RexxActivity::createConditionObject),
the value returned by new_directory() must be protected.


===============================================================================
2010 july 3

Debug crash in gc
RexxMemory::markObjectsMain
    markObject->live(liveMark);

0x003d2b8c                                          --> this is 0x7eee1ac0->behaviour
Access violation reading location 0x44414550        --> this is the vfptr of the behaviour of a string

((*(RexxVirtualBase*)(&(*(RexxInternalObject*)(&*markObject))))).__vfptr


RexxMemory::mark(RexxObject *markObject)
    pushLiveStack((RexxObject *)markObject->behaviour);
markObject = 0x7eee1ac0                             --> see below, this is the 30th element of string array
    [RexxString]
               if tmp<2 then         -- start at first char

called by RexxArray::live(size_t liveMark)      ArrayClass.cpp
where this = 0x7f30ed70
this->objects = 7f30ed98
arrayPtr=7f30ee0c
0x7f30ee0c - 0x7f30ed98 = 116 = 29 * 4 --> this is the 30th element

element 1 to 13 : not a string... but doesn't be a problem
+		(*(RexxString*)this->get(14)).stringData	0x7eee36a4 "  len1=length(arg1string)        -- get length of string"	char [4]
+		(*(RexxString*)this->get(15)).stringData	0x7eee3704 "  newArr=.array~new        -- create new array for the arguments"	char [4]
+		(*(RexxString*)this->get(16)).stringData	0x7eee376c "  newArr[1]=new1string     -- "new"-string"	char [4]
+		(*(RexxString*)this->get(18)).stringData	0x7eee37e4 "  prepend=""               -- optional prepend string (if positioning before start!)"	char [4]
+		(*(RexxString*)this->get(20)).stringData	0x7eee388c "  arg2startori=arg2start         -- save passed-in value, if any"	char [4]
+		(*(RexxString*)this->get(21)).stringData	0x7eee38f4 "  if arg4pad=="" then arg4pad=" "-- define blank as the default pad char"	char [4]
+		(*(RexxString*)this->get(23)).stringData	0x7eee398c "  if arg(3,"Exists") then  -- start in "target"-string"	char [4]
+		(*(RexxString*)this->get(24)).stringData	0x7eee2dfc "  do"	char [4]
+		(*(RexxString*)this->get(25)).stringData	0x7eee2e2c "     if datatype(arg2start,"W") then"	char [4]
+		(*(RexxString*)this->get(26)).stringData	0x7eee2e7c "     do"	char [4]
+		(*(RexxString*)this->get(27)).stringData	0x7eee2eac "        if arg2start<0 then      -- negative, start from right"	char [4]
+		(*(RexxString*)this->get(28)).stringData	0x7eee2f14 "        do"	char [4]
+		(*(RexxString*)this->get(29)).stringData	0x7eee2f44 "           tmp=len1+arg2start+1  -- get starting position"	char [4]
+		(*(RexxString*)this->get(30)).stringData	0x7eee1ae4 "           if tmp<2 then         -- start at first char"	char [4]
+		(*(RexxString*)this->get(31)).stringData	0x7eee1b44 "           do"	char [4]
+		(*(RexxString*)this->get(32)).stringData	0x7eee1b7c "              if tmp<0 then"	char [4]

The behaviour of the 30th element is broken :
+		((*(RexxVirtualBase*)(&(*(RexxInternalObject*)(&*(((*(RexxInternalObject*)(&*(this->get(28))))).behaviour)))))).__vfptr	0x003aa62c const RexxBehaviour::`vftable'	*
+		((*(RexxVirtualBase*)(&(*(RexxInternalObject*)(&*(((*(RexxInternalObject*)(&*(this->get(29))))).behaviour)))))).__vfptr	0x003aa62c const RexxBehaviour::`vftable'	*
+		((*(RexxVirtualBase*)(&(*(RexxInternalObject*)(&*(((*(RexxInternalObject*)(&*(this->get(30))))).behaviour)))))).__vfptr	0x44414548	*
+		((*(RexxVirtualBase*)(&(*(RexxInternalObject*)(&*(((*(RexxInternalObject*)(&*(this->get(31))))).behaviour)))))).__vfptr	0x003aa62c const RexxBehaviour::`vftable'	*
+		((*(RexxVirtualBase*)(&(*(RexxInternalObject*)(&*(((*(RexxInternalObject*)(&*(this->get(32))))).behaviour)))))).__vfptr	0x003aa62c const RexxBehaviour::`vftable'	*

the behaviour of 30th element is stored at 0x7eee1acc


called by RexxMemory::markObjectsMain(RexxObject *rootObject)
where rootObject =
+		rootObject	0x003d2a90 class RexxMemory memoryObject {markWord=1 markReason=1 variableCache=0x7f5b55a8 ...}	RexxObject *

called by RexxMemory::markObjects()

called by RexxMemory::collect()

objectclass.hpp
inline void   setBehaviour(RexxBehaviour *b) { behaviour = b; }         <-- this method is called to assign the behavior of type 22 (T_String)
>	rexx.dll!RexxInternalObject::setBehaviour(RexxBehaviour * b)  Line 265 + 0x10 bytes	C++
 	rexx.dll!RexxObject::initializeNewObject(unsigned int mark, void * vft, RexxBehaviour * b)  Line 362	C++
 	rexx.dll!RexxMemory::newObject(unsigned int requestLength, unsigned int type)  Line 1134	C++
 	rexx.dll!new_object(unsigned int s, unsigned int t)  Line 422 + 0x1e bytes	C++
 	rexx.dll!RexxString::newString(const char * string, unsigned int length)  Line 1894 + 0xd bytes	C++
 	rexx.dll!new_string(const char * s, unsigned int l)  Line 521	C++
 	rexx.dll!RexxSource::get(unsigned int _position)  Line 838 + 0x1d bytes	C++
 	rexx.dll!RexxSource::extractSource(SourceLocation & location)  Line 1119 + 0x10 bytes	C++                 <-- counter = 735
 	rexx.dll!RexxCode::getSource()  Line 199	C++
 	rexx.dll!BaseExecutable::source()  Line 149	C++
 	rexx.dll!CPPCode::run(RexxActivity * activity, RexxMethod * method, RexxObject * receiver, RexxString * messageName, RexxObject * * argPtr, unsigned int count, ProtectedObject & result)  Line 144 + 0x6 bytes	C++
 	rexx.dll!RexxMethod::run(RexxActivity * activity, RexxObject * receiver, RexxString * msgname, RexxObject * * argPtr, unsigned int count, ProtectedObject & result)  Line 325	C++
 	rexx.dll!RexxObject::messageSend(RexxString * msgname, RexxObject * * arguments, unsigned int count, ProtectedObject & result)  Line 793	C++
 	rexx.dll!RexxExpressionStack::send(RexxString * message, unsigned int count, ProtectedObject & result)  Line 74 + 0x33 bytes	C++
 	rexx.dll!RexxExpressionMessage::evaluate(RexxActivation * context, RexxExpressionStack * stack)  Line 139	C++
 	rexx.dll!RexxExpressionMessage::evaluate(RexxActivation * context, RexxExpressionStack * stack)  Line 123 + 0x23 bytes	C++
 	rexx.dll!RexxInstructionAssignment::execute(RexxActivation * context, RexxExpressionStack * stack)  Line 122 + 0x1d bytes	C++
 	rexx.dll!RexxActivation::run(RexxObject * _receiver, RexxString * msgname, RexxObject * * _arglist, unsigned int _argcount, RexxInstruction * start, ProtectedObject & resultObj)  Line 522	C++
 	rexx.dll!RexxCode::call(RexxActivity * activity, RoutineClass * routine, RexxString * msgname, RexxObject * * argPtr, unsigned int argcount, RexxString * calltype, RexxString * environment, int context, ProtectedObject & result)  Line 116	C++
 	rexx.dll!RexxCode::call(RexxActivity * activity, RoutineClass * routine, RexxString * msgname, RexxObject * * argPtr, unsigned int argcount, ProtectedObject & result)  Line 92	C++
 	rexx.dll!RoutineClass::call(RexxActivity * activity, RexxString * msgname, RexxObject * * argPtr, unsigned int argcount, ProtectedObject & result)  Line 234	C++
 	rexx.dll!InterpreterInstance::runRequires(RexxActivity * activity, RexxString * name, RoutineClass * code)  Line 877	C++
 	rexx.dll!InterpreterInstance::loadRequires(RexxActivity * activity, RexxString * shortName, RexxString * fullName)  Line 932	C++
 	rexx.dll!RexxSource::loadRequires(RexxActivity * activity, RexxString * target)  Line 6082 + 0x14 bytes	C++
 	rexx.dll!PackageClass::loadPackage(RexxString * name, RexxArray * s)  Line 366 + 0x16 bytes	C++             <-- rgf_util2.rex


The previous behaviour is overwritten by
inline void insertAfter(DeadObject *newDead)            DeadObject.hpp
where newDead = 7eee1ac0
 	rexx.dll!DeadObject::insertAfter(DeadObject * newDead)  Line 89	C++
 	rexx.dll!DeadObjectPool::add(DeadObject * obj)  Line 165	C++
>	rexx.dll!NormalSegmentSet::addDeadObject(char * object, unsigned int length)  Line 461	C++
 	rexx.dll!MemorySegmentSet::sweep()  Line 1170	C++
 	rexx.dll!RexxMemory::collect()  Line 1038	C++
 	rexx.dll!NormalSegmentSet::handleAllocationFailure(unsigned int allocationLength)  Line 1272	C++
 	rexx.dll!RexxMemory::newObject(unsigned int requestLength, unsigned int type)  Line 1117 + 0x12 bytes	C++ <-- length = 48, we are in "small object" part (lesser than LargeBlockThreshold 4096)
 	rexx.dll!new_object(unsigned int s, unsigned int t)  Line 422 + 0x1e bytes	C++
 	rexx.dll!RexxString::newString(const char * string, unsigned int length)  Line 1894 + 0xd bytes	C++
 	rexx.dll!new_string(const char * s, unsigned int l)  Line 521	C++
 	rexx.dll!new_string(const char * s, unsigned int l)  Line 521	C++
 	rexx.dll!RexxSource::get(unsigned int _position)  Line 838 + 0x1d bytes	C++
 	rexx.dll!RexxSource::extractSource(SourceLocation & location)  Line 1119 + 0x10 bytes	C++                 <-- counter = 754
 	rexx.dll!RexxCode::getSource()  Line 199	C++
 	rexx.dll!BaseExecutable::source()  Line 149	C++
 	rexx.dll!CPPCode::run(RexxActivity * activity, RexxMethod * method, RexxObject * receiver, RexxString * messageName, RexxObject * * argPtr, unsigned int count, ProtectedObject & result)  Line 144 + 0x6 bytes	C++
 	rexx.dll!RexxMethod::run(RexxActivity * activity, RexxObject * receiver, RexxString * msgname, RexxObject * * argPtr, unsigned int count, ProtectedObject & result)  Line 325	C++
 	rexx.dll!RexxObject::messageSend(RexxString * msgname, RexxObject * * arguments, unsigned int count, ProtectedObject & result)  Line 793	C++
 	rexx.dll!RexxExpressionStack::send(RexxString * message, unsigned int count, ProtectedObject & result)  Line 74 + 0x33 bytes	C++
 	rexx.dll!RexxExpressionMessage::evaluate(RexxActivation * context, RexxExpressionStack * stack)  Line 139	C++
 	rexx.dll!RexxExpressionMessage::evaluate(RexxActivation * context, RexxExpressionStack * stack)  Line 123 + 0x23 bytes	C++
 	rexx.dll!RexxInstructionAssignment::execute(RexxActivation * context, RexxExpressionStack * stack)  Line 122 + 0x1d bytes	C++
 	rexx.dll!RexxActivation::run(RexxObject * _receiver, RexxString * msgname, RexxObject * * _arglist, unsigned int _argcount, RexxInstruction * start, ProtectedObject & resultObj)  Line 522	C++
 	rexx.dll!RexxCode::call(RexxActivity * activity, RoutineClass * routine, RexxString * msgname, RexxObject * * argPtr, unsigned int argcount, RexxString * calltype, RexxString * environment, int context, ProtectedObject & result)  Line 116	C++
 	rexx.dll!RexxCode::call(RexxActivity * activity, RoutineClass * routine, RexxString * msgname, RexxObject * * argPtr, unsigned int argcount, ProtectedObject & result)  Line 92	C++
 	rexx.dll!RoutineClass::call(RexxActivity * activity, RexxString * msgname, RexxObject * * argPtr, unsigned int argcount, ProtectedObject & result)  Line 234	C++
 	rexx.dll!InterpreterInstance::runRequires(RexxActivity * activity, RexxString * name, RoutineClass * code)  Line 877	C++
 	rexx.dll!InterpreterInstance::loadRequires(RexxActivity * activity, RexxString * shortName, RexxString * fullName)  Line 932	C++
 	rexx.dll!RexxSource::loadRequires(RexxActivity * activity, RexxString * target)  Line 6082 + 0x14 bytes	C++
 	rexx.dll!PackageClass::loadPackage(RexxString * name, RexxArray * s)  Line 366 + 0x16 bytes	C++             <-- rgf_util2.rex
    while loading rgf_util2.rex

Why is 0x7eee1ac0 a dead object ?
In RexxSource::extractSource, the array "source" is created, but is not a ProtectedObject.


================================================================================

Revue des protected objects
Risque de GC avant l'initialisation :

ObjectClass.cpp
RexxObject::operator new(
    ProtectedObject newObject = new (classObject) RexxObject;


================================================================================

While testing pipeline/one-liners.rex, got a GC crash...
It's part of the remaining code to review (->evaluate).
Strange... I fixed the crash by protecting the variables _super and _target in RexxExpressionMessage::evaluate.
But, they should be protected by the stack, no ?
_target = this->target->evaluate(context, stack);       --> see code below, the result is pushed on the stack
_super = this->super->evaluate(context, stack);     (not called in my case)
>	rexx.dll!RexxParseVariable::evaluate(RexxActivation * context, RexxExpressionStack * stack)  Line 102	C++
 	rexx.dll!RexxExpressionMessage::evaluate(RexxActivation * context, RexxExpressionStack * stack)  Line 97 + 0x1b bytes	C++
 	rexx.dll!RexxInstructionAssignment::execute(RexxActivation * context, RexxExpressionStack * stack)  Line 109 + 0x1b bytes	C++
 	rexx.dll!RexxActivation::run(RexxObject * _receiver, RexxString * msgname, RexxObject * * _arglist, unsigned int _argcount, RexxInstruction * start, ProtectedObject & resultObj)  Line 544	C++
----------
RexxObject  *RexxParseVariable::evaluate(
    RexxActivation      *context,      /* current activation context        */
    RexxExpressionStack *stack )       /* evaluation stack                  */
{
    RexxVariable *variable = context->getLocalVariable(variableName, index);
    RexxObject *value = variable->getVariableValue();/* get the value                     */
    ...
    stack->push(value);                  /* place on the evaluation stack     */        <-- here, the result is protected
    ...
    return value;                        /* return the located variable       */
}


================================================================================
Code review of hasReferences
================================================================================

Object.hpp
     inline void setHasNoReferences() { flags |= NoRefBit; }
     inline void setHasReferences() { flags &= ~NoRefBit; }
     inline bool hasReferences() { return (flags & NoRefBit) == 0; }
     inline bool hasNoReferences() { return (flags & NoRefBit) != 0; }


setHasNoReferences
used by
    BufferClass
    IntegerClass
    NumberStringClass
    PointerClass
    StringClass
    NativeActivation
    RexxActivation for default constructor
    NumberArray


setHasReferences
used by
    IntegerClass
    NumberStringClass
    ObjectClass when getObjectVariables
    StringClass when numberString, setNumberString
    RexxActivation when allocateStackFrame


/**
 * Perform a marking operation on all objects in a segment
 * (only called for an image restore)
 */
void MemorySegment::markAllObjects()
{
    RexxInternalObject *op = startObject();
    RexxInternalObject *ep = endObject();
    while (op < ep)
    {
        // all objects have an associated behaviour, make sure it is marked
        memory_mark_general(op->behaviour);

        // not every object has references to other objects (strings are
        // a good example). We can skip calling the live method if we know they don't
        if (op->hasReferences())
        {
            // yes, there are references, we need to fix them up.
            op->liveGeneral(RESTORINGIMAGE);
        }
        op =op->nextObject();   // we are just marking each object in order.
    }
}



void MemoryObject::restoreImage()
{
...
    // now loop through the image buffer fixing up the objects.
    while (objectPointer < endPointer)
    {
...
        // if the object has references, call liveGeneral() to cause these references to
        // be converted back into real pointers
        if (objectPointer->hasReferences())
        {
            objectPointer->liveGeneral(RESTORINGIMAGE);
        }
        // advance to the next object in the image
        objectPointer = objectPointer->nextObject();
    }



void MemoryObject::liveGeneral(MarkReason reason)
{
    memory_mark_general(saveStack);
    memory_mark_general(old2new);
    memory_mark_general(globalStrings);
    memory_mark_general(environment);
    memory_mark_general(commonRetrievers);
    memory_mark_general(system);
    memory_mark_general(rexxPackage);
    memory_mark_general(globalReferences);

    // now call the various subsystem managers to mark their references
    Interpreter::liveGeneral(reason);
    SystemInterpreter::liveGeneral(reason);
    ActivityManager::liveGeneral(reason);
    PackageManager::liveGeneral(reason);
    // mark any protected objects we've been watching over

    GlobalProtectedObject *p = protectedObjects;
    while (p != NULL)
    {
        memory_mark_general(p->protectedObject);
        p = p->next;
    }
}
