github.com/racerxdl/gonx@v0.0.0-20210103083128-c5afc43bcbd2/services/ipc/object.go (about)

     1  package ipc
     2  
     3  import (
     4  	"github.com/racerxdl/gonx/nx/nxtypes"
     5  	"github.com/racerxdl/gonx/svc"
     6  	"unsafe"
     7  )
     8  
     9  // Used for keeping GC from collecting it
    10  var domainHolders []*Domain
    11  
    12  func cacheDomain(domain *Domain) {
    13  	for _, v := range domainHolders {
    14  		if domain == v {
    15  			return // Already cached
    16  		}
    17  	}
    18  
    19  	domainHolders = append(domainHolders, domain)
    20  }
    21  
    22  // IPCObject Represents either an object within an IPC domain or a standalone object
    23  type Object struct {
    24  	ObjectID   int32 // -1 if this represents a session, >= 0 if this represents a domain object
    25  	Content    uint64
    26  	IsBorrowed bool
    27  }
    28  
    29  func (o *Object) Recycle() {
    30  	if o.Content == 0 {
    31  		return
    32  	}
    33  
    34  	for i, v := range domainHolders {
    35  		ptr := uint64(uintptr(unsafe.Pointer(v)))
    36  		if ptr == o.Content {
    37  			o.Content = 0
    38  			domainHolders = append(domainHolders[1:], domainHolders[i+1:]...)
    39  			return
    40  		}
    41  	}
    42  
    43  	o.Content = 0
    44  }
    45  
    46  func (o *Object) SetSession(session nxtypes.Handle) {
    47  	o.Content = uint64(session)
    48  	o.ObjectID = -1
    49  }
    50  
    51  func (o Object) GetSession() nxtypes.SessionHandle {
    52  	if o.ObjectID == -1 {
    53  		return nxtypes.SessionHandle(o.Content & 0xFFFFFFFF)
    54  	}
    55  
    56  	return nxtypes.SessionHandle(0)
    57  }
    58  
    59  func (o Object) SetDomain(domain *Domain) {
    60  	cacheDomain(domain)
    61  	o.Content = uint64(uintptr(unsafe.Pointer(domain)))
    62  }
    63  
    64  func (o Object) GetDomain() *Domain {
    65  	if o.ObjectID >= 0 && o.Content != 0 && uintptr(o.Content) > svc.GetHeapBase() {
    66  		return (*Domain)(unsafe.Pointer(uintptr(o.Content)))
    67  	}
    68  
    69  	return nil
    70  }