Compare commits

..

2 Commits

Author SHA1 Message Date
fur%netscape.com
1c43d4984f This is a copy of regalloc_code2_BRANCH from Netscape's private repository,
as it existed in January of 1998.


git-svn-id: svn://10.0.0.236/branches/regalloc_code2_BRANCH@22571 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-02 16:12:08 +00:00
(no author)
cfe021ff88 This commit was manufactured by cvs2svn to create branch
'regalloc_code2_BRANCH'.

git-svn-id: svn://10.0.0.236/branches/regalloc_code2_BRANCH@22567 18797224-902f-48f8-a5cc-f745e15eee43
1999-03-02 15:57:58 +00:00
100 changed files with 5324 additions and 9137 deletions

View File

@@ -0,0 +1,134 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "BitSet.h"
// Return the next bit after index set to true or -1 if none.
//
Int32 BitSet::nextOne(Int32 pos) const
{
++pos;
if (pos < 0 || Uint32(pos) >= universeSize)
return -1;
Uint32 offset = getWordOffset(pos);
Uint8 index = getBitOffset(pos);
Word* ptr = &word[offset];
Word currentWord = *ptr++ >> index;
if (currentWord != Word(0)) {
while ((currentWord & Word(1)) == 0) {
++index;
currentWord >>= 1;
}
return (offset << nBitsInWordLog2) + index;
}
Word* limit = &word[getSizeInWords(universeSize)];
while (ptr < limit) {
++offset;
currentWord = *ptr++;
if (currentWord != Word(0)) {
index = 0;
while ((currentWord & Word(1)) == 0) {
++index;
currentWord >>= 1;
}
return (offset << nBitsInWordLog2) + index;
}
}
return -1;
}
// Return the next bit after index set to false or -1 if none.
//
Int32 BitSet::nextZero(Int32 pos) const
{
++pos;
if (pos < 0 || Uint32(pos) >= universeSize)
return -1;
Uint32 offset = getWordOffset(pos);
Uint8 index = getBitOffset(pos);
Word* ptr = &word[offset];
Word currentWord = *ptr++ >> index;
if (currentWord != Word(~0)) {
for (; index < nBitsInWord; ++index) {
if ((currentWord & Word(1)) == 0) {
Int32 ret = (offset << nBitsInWordLog2) + index;
return (Uint32(ret) < universeSize) ? ret : -1;
}
currentWord >>= 1;
}
}
Word* limit = &word[getSizeInWords(universeSize)];
while (ptr < limit) {
++offset;
currentWord = *ptr++;
if (currentWord != Word(~0)) {
for (index = 0; index < nBitsInWord; ++index) {
if ((currentWord & Word(1)) == 0) {
Int32 ret = (offset << nBitsInWordLog2) + index;
return (Uint32(ret) < universeSize) ? ret : -1;
}
currentWord >>= 1;
}
}
}
return -1;
}
#ifdef DEBUG_LOG
// Print the set.
//
void BitSet::printPretty(LogModuleObject log)
{
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("[ "));
for (Int32 i = firstOne(); i != -1; i = nextOne(i)) {
Int32 currentBit = i;
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%d", currentBit));
Int32 nextBit = nextOne(currentBit);
if (nextBit != currentBit + 1) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" "));
continue;
}
while ((nextBit != -1) && (nextBit == (currentBit + 1))) {
currentBit = nextBit;
nextBit = nextOne(nextBit);
}
if (currentBit > (i+1))
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("-%d ", currentBit));
else
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" %d ", currentBit));
i = currentBit;
}
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("]\n"));
}
#endif // DEBUG_LOG

View File

@@ -0,0 +1,195 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _BITSET_H_
#define _BITSET_H_
#include "Fundamentals.h"
#include "LogModule.h"
#include "Pool.h"
#include <string.h>
//------------------------------------------------------------------------------
// BitSet -
class BitSet
{
private:
#if (PR_BITS_PER_WORD == 64)
typedef Uint64 Word;
#elif (PR_BITS_PER_WORD == 32)
typedef Uint32 Word;
#endif
static const nBitsInWord = PR_BITS_PER_WORD;
static const nBytesInWord = PR_BYTES_PER_WORD;
static const nBitsInWordLog2 = PR_BITS_PER_WORD_LOG2;
static const nBytesInWordLog2 = PR_BYTES_PER_WORD_LOG2;
// Return the number of Word need to store the universe.
static Uint32 getSizeInWords(Uint32 sizeOfUniverse) {return (sizeOfUniverse + (nBitsInWord - 1)) >> nBitsInWordLog2;}
// Return the given element offset in its containing Word.
static Uint32 getBitOffset(Uint32 element) {return element & (nBitsInWord - 1);}
// Return the Word offset for the given element int the universe.
static Uint32 getWordOffset(Uint32 element) {return element >> nBitsInWordLog2;}
// Return the mask for the given bit index.
static Word getMask(Uint8 index) {return Word(1) << index;}
private:
Uint32 universeSize; // Size of the universe
Word* word; // universe memory.
private:
// No copy constructor.
BitSet(const BitSet&);
// Check if the given set's universe is of the same size than this universe.
void checkUniverseCompatibility(const BitSet& set) const {assert(set.universeSize == universeSize);}
// Check if pos is valid for this set's universe.
void checkMember(Int32 pos) const {assert(pos >=0 && Uint32(pos) < universeSize);}
public:
// Create a bitset of universeSize bits.
BitSet(Pool& pool, Uint32 universeSize) : universeSize(universeSize) {word = new(pool) Word[getSizeInWords(universeSize)]; clear();}
// Return the size of this bitset.
Uint32 getSize() const {return universeSize;}
// Clear the bitset.
void clear() {memset(word, 0x00, getSizeInWords(universeSize) << nBytesInWordLog2);}
// Clear the bit at index.
void clear(Uint32 index) {checkMember(index); word[getWordOffset(index)] &= ~getMask(index);}
// Set the bitset.
void set() {memset(word, 0xFF, getSizeInWords(universeSize) << nBytesInWordLog2);}
// Set the bit at index.
void set(Uint32 index) {checkMember(index); word[getWordOffset(index)] |= getMask(index);}
// Return true if the bit at index is set.
bool test(Uint32 index) const {checkMember(index); return (word[getWordOffset(index)] & getMask(index)) != 0;}
// Union with the given bitset.
inline void or(const BitSet& set);
// Intersection with the given bitset.
inline void and(const BitSet& set);
// Difference with the given bitset.
inline void difference(const BitSet& set);
// Copy set.
inline BitSet& operator = (const BitSet& set);
// Return true if the bitset are identical.
friend bool operator == (const BitSet& set1, const BitSet& set2);
// Return true if the bitset are different.
friend bool operator != (const BitSet& set1, const BitSet& set2);
// Logical operators.
BitSet& operator |= (const BitSet& set) {or(set); return *this;}
BitSet& operator &= (const BitSet& set) {and(set); return *this;}
BitSet& operator -= (const BitSet& set) {difference(set); return *this;}
// Return the first bit at set to true or -1 if none.
Int32 firstOne() const {return nextOne(-1);}
// Return the next bit after index set to true or -1 if none.
Int32 nextOne(Int32 pos) const;
// Return the first bit at set to false or -1 if none.
Int32 firstZero() const {return nextZero(-1);}
// Return the next bit after index set to false or -1 if none.
Int32 nextZero(Int32 pos) const;
// Iterator to conform with the set API.
typedef Int32 iterator;
// Return true if the walk is ordered.
static bool isOrdered() {return true;}
// Return the iterator for the first element of this set.
iterator begin() const {return firstOne();}
// Return the next iterator.
iterator advance(iterator pos) const {return nextOne(pos);}
// Return true if the iterator is at the end of the set.
bool done(iterator pos) const {return pos == -1;}
// Return the element corresponding to the given iterator.
Uint32 get(iterator pos) const {return pos;}
#ifdef DEBUG_LOG
// Print the set.
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
// Union with the given bitset.
//
inline void BitSet::or(const BitSet& set)
{
checkUniverseCompatibility(set);
Word* src = set.word;
Word* dst = word;
Word* limit = &src[getSizeInWords(universeSize)];
while (src < limit)
*dst++ |= *src++;
}
// Intersection with the given bitset.
//
inline void BitSet::and(const BitSet& set)
{
checkUniverseCompatibility(set);
Word* src = set.word;
Word* dst = word;
Word* limit = &src[getSizeInWords(universeSize)];
while (src < limit)
*dst++ &= *src++;
}
// Difference with the given bitset.
//
inline void BitSet::difference(const BitSet& set)
{
checkUniverseCompatibility(set);
Word* src = set.word;
Word* dst = word;
Word* limit = &src[getSizeInWords(universeSize)];
while (src < limit)
*dst++ &= ~*src++;
}
// Copy the given set into this set.
//
inline BitSet& BitSet::operator = (const BitSet& set)
{
checkUniverseCompatibility(set);
if (this != &set)
memcpy(word, set.word, getSizeInWords(universeSize) << nBytesInWordLog2);
return *this;
}
// Return true if the given set is identical to this set.
inline bool operator == (const BitSet& set1, const BitSet& set2)
{
set1.checkUniverseCompatibility(set2);
if (&set1 == &set2)
return true;
return memcmp(set1.word, set2.word, BitSet::getSizeInWords(set1.universeSize) << BitSet::nBytesInWordLog2) == 0;
}
inline bool operator != (const BitSet& set1, const BitSet& set2) {return !(set1 == set2);}
#endif // _BITSET_H

View File

@@ -0,0 +1,159 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _COALESCING_H_
#define _COALESCING_H_
#include "Fundamentals.h"
#include "Pool.h"
#include "RegisterPressure.h"
#include "InterferenceGraph.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "SparseSet.h"
#include "RegisterAllocator.h"
#include "RegisterAllocatorTools.h"
#if 1
// Performing an ultra conservative coalescing meens that when we look at
// candidates (source,destination) for coalescing we need to make sure
// that the combined interference of the source and destination register
// will not exceed the total number of register available for the register
// class.
#define ULTRA_CONSERVATIVE_COALESCING
#else
// If we are not doing an ultra conservative coalescing we have to make sure
// that the total number of neighbor whose degree is greater than the total
// number of register is not greater than the total number of register.
#undef ULTRA_CONSERVATIVE_COALESCING
#endif
template <class RegisterPressure>
struct Coalescing
{
static bool coalesce(RegisterAllocator& registerAllocator);
};
template <class RegisterPressure>
bool Coalescing<RegisterPressure>::coalesce(RegisterAllocator& registerAllocator)
{
Pool& pool = registerAllocator.pool;
// Initialize the lookup table
//
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* newRange = new RegisterName[2 * rangeCount];
RegisterName* coalescedRange = &newRange[rangeCount];
RegisterName* name2range = registerAllocator.name2range;
init(coalescedRange, rangeCount);
SparseSet interferences(pool, rangeCount);
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
bool removedInstructions = false;
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.lndList;
Uint32 nNodes = controlGraph.nNodes;
// Walk the nodes in the loop nesting depth list.
for (Int32 n = nNodes - 1; n >= 0; n--) {
InstructionList& instructions = nodes[n]->getInstructions();
InstructionList::iterator it = instructions.begin();
while (!instructions.done(it)) {
Instruction& instruction = instructions.get(it);
it = instructions.advance(it);
if ((instruction.getFlags() & ifCopy) != 0) {
assert(instruction.getInstructionUseBegin() != instruction.getInstructionUseEnd() && instruction.getInstructionUseBegin()[0].isRegister());
assert(instruction.getInstructionDefineBegin() != instruction.getInstructionDefineEnd() && instruction.getInstructionDefineBegin()[0].isRegister());
RegisterName source = findRoot(name2range[instruction.getInstructionUseBegin()[0].getRegisterName()], coalescedRange);
RegisterName destination = findRoot(name2range[instruction.getInstructionDefineBegin()[0].getRegisterName()], coalescedRange);
if (source == destination) {
instruction.remove();
} else if (!iGraph.interfere(source, destination)) {
InterferenceVector* sourceVector = iGraph.getInterferenceVector(source);
InterferenceVector* destinationVector = iGraph.getInterferenceVector(destination);
#ifdef ULTRA_CONSERVATIVE_COALESCING
interferences.clear();
InterferenceVector* vector;
for (vector = sourceVector; vector != NULL; vector = vector->next) {
RegisterName* neighbors = vector->neighbors;
for (Uint32 i = 0; i < vector->count; i++)
interferences.set(findRoot(neighbors[i], coalescedRange));
}
for (vector = destinationVector; vector != NULL; vector = vector->next) {
RegisterName* neighbors = vector->neighbors;
for (Uint32 i = 0; i < vector->count; i++)
interferences.set(findRoot(neighbors[i], coalescedRange));
}
Uint32 count = interferences.getSize();
#else // ULTRA_CONSERVATIVE_COALESCING
trespass("not implemented");
Uint32 count = 0;
#endif // ULTRA_CONSERVATIVE_COALESCING
if (count < 6 /* FIX: should get the number from the class */) {
// Update the interferences vector.
if (sourceVector == NULL) {
iGraph.setInterferenceVector(source, destinationVector);
sourceVector = destinationVector;
} else if (destinationVector == NULL)
iGraph.setInterferenceVector(destination, sourceVector);
else {
InterferenceVector* last = NULL;
for (InterferenceVector* v = sourceVector; v != NULL; v = v->next)
last = v;
assert(last);
last->next = destinationVector;
iGraph.setInterferenceVector(destination, sourceVector);
}
// Update the interference matrix.
for (InterferenceVector* v = sourceVector; v != NULL; v = v->next) {
RegisterName* neighbors = v->neighbors;
for (Uint32 i = 0; i < v->count; i++) {
RegisterName neighbor = findRoot(neighbors[i], coalescedRange);
iGraph.setInterference(neighbor, source);
iGraph.setInterference(neighbor, destination);
}
}
instruction.remove();
coalescedRange[source] = destination;
removedInstructions = true;
}
}
}
}
}
registerAllocator.rangeCount = compress(registerAllocator.name2range, coalescedRange, registerAllocator.nameCount, rangeCount);
delete newRange;
return removedInstructions;
}
#endif // _COALESCING_H_

View File

@@ -0,0 +1,283 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef NEW_LAURENTM_CODE
#include "Coloring.h"
#include "VirtualRegister.h"
#include "FastBitSet.h"
#include "FastBitMatrix.h"
#include "CpuInfo.h"
bool Coloring::
assignRegisters(FastBitMatrix& interferenceMatrix)
{
PRUint32 *stackPtr = new(pool) PRUint32[vRegManager.count()];
return select(interferenceMatrix, stackPtr, simplify(interferenceMatrix, stackPtr));
}
PRInt32 Coloring::
getLowestSpillCostRegister(FastBitSet& bitset)
{
PRInt32 lowest = bitset.firstOne();
if (lowest != -1)
{
Flt32 cost = vRegManager.getVirtualRegister(lowest).spillInfo.spillCost;
for (PRInt32 r = bitset.nextOne(lowest); r != -1; r = bitset.nextOne(r))
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
if (!vReg.spillInfo.infiniteSpillCost && (vReg.spillInfo.spillCost < cost))
{
cost = vReg.spillInfo.spillCost;
lowest = r;
}
}
}
return lowest;
}
PRUint32* Coloring::
simplify(FastBitMatrix interferenceMatrix, PRUint32* stackPtr)
{
// first we construct the sets low and high. low contains all nodes of degree
// inferior to the number of register available on the processor. All the
// nodes with an high degree and a finite spill cost are placed in high.
// Nodes of high degree and infinite spill cost are not included in either sets.
PRUint32 nRegisters = vRegManager.count();
FastBitSet low(pool, nRegisters);
FastBitSet high(pool, nRegisters);
FastBitSet stack(pool, nRegisters);
for (VirtualRegisterManager::iterator i = vRegManager.begin(); !vRegManager.done(i); i = vRegManager.advance(i))
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(i);
if (vReg.getClass() == vrcStackSlot)
{
stack.set(i);
vReg.colorRegister(nRegisters);
}
else
{
if (vReg.colorInfo.interferenceDegree < NUMBER_OF_REGISTERS)
low.set(i);
else // if (!vReg.spillInfo.infiniteSpillCost)
high.set(i);
// Set coloring info.
vReg.spillInfo.willSpill = false;
switch(vReg.getClass())
{
case vrcInteger:
vReg.colorRegister(LAST_GREGISTER + 1);
break;
case vrcFloatingPoint:
case vrcFixedPoint:
vReg.colorRegister(LAST_FPREGISTER + 1);
break;
default:
PR_ASSERT(false); // Cannot happen.
}
}
}
// push the stack registers
PRInt32 j;
for (j = stack.firstOne(); j != -1; j = stack.nextOne(j))
*stackPtr++ = j;
// simplify
while (true)
{
PRInt32 r;
while ((r = getLowestSpillCostRegister(low)) != -1)
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
/* update low and high */
FastBitSet inter(interferenceMatrix.getRow(r), nRegisters);
for (j = inter.firstOne(); j != -1; j = inter.nextOne(j))
{
VirtualRegister& neighbor = vRegManager.getVirtualRegister(j);
// if the new interference degree of one of his neighbor becomes
// NUMBER_OF_REGISTERS - 1 then it is added to the set 'low'.
PRUint32 maxInterference = 0;
switch (neighbor.getClass())
{
case vrcInteger:
maxInterference = NUMBER_OF_GREGISTERS;
break;
case vrcFloatingPoint:
case vrcFixedPoint:
maxInterference = NUMBER_OF_FPREGISTERS;
break;
default:
PR_ASSERT(false);
}
if ((vRegManager.getVirtualRegister(j).colorInfo.interferenceDegree-- == maxInterference))
{
high.clear(j);
low.set(j);
}
vReg.colorInfo.interferenceDegree--;
interferenceMatrix.clear(r, j);
interferenceMatrix.clear(j, r);
}
low.clear(r);
// Push this register.
*stackPtr++ = r;
}
if ((r = getLowestSpillCostRegister(high)) != -1)
{
high.clear(r);
low.set(r);
}
else
break;
}
return stackPtr;
}
bool Coloring::
select(FastBitMatrix& interferenceMatrix, PRUint32* stackBase, PRUint32* stackPtr)
{
PRUint32 nRegisters = vRegManager.count();
FastBitSet usedRegisters(NUMBER_OF_REGISTERS + 1); // usedRegisters if used for both GR & FPR.
FastBitSet preColoredRegisters(NUMBER_OF_REGISTERS + 1);
FastBitSet usedStack(nRegisters + 1);
bool success = true;
Int32 lastUsedSSR = -1;
// select
while (stackPtr != stackBase)
{
// Pop one register.
PRUint32 r = *--stackPtr;
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
FastBitSet neighbors(interferenceMatrix.getRow(r), nRegisters);
if (vReg.getClass() == vrcStackSlot)
// Stack slots coloring.
{
usedStack.clear();
for (PRInt32 i = neighbors.firstOne(); i != -1; i = neighbors.nextOne(i))
usedStack.set(vRegManager.getVirtualRegister(i).getColor());
Int32 color = usedStack.firstZero();
vReg.colorRegister(color);
if (color > lastUsedSSR)
lastUsedSSR = color;
}
else
// Integer & Floating point register coloring.
{
usedRegisters.clear();
preColoredRegisters.clear();
for (PRInt32 i = neighbors.firstOne(); i != -1; i = neighbors.nextOne(i))
{
VirtualRegister& nvReg = vRegManager.getVirtualRegister(i);
usedRegisters.set(nvReg.getColor());
if (nvReg.isPreColored())
preColoredRegisters.set(nvReg.getPreColor());
}
if (vReg.hasSpecialInterference)
usedRegisters |= vReg.specialInterference;
PRInt8 c = -1;
PRInt8 maxColor = 0;
PRInt8 firstColor = 0;
switch (vReg.getClass())
{
case vrcInteger:
firstColor = FIRST_GREGISTER;
maxColor = LAST_GREGISTER;
break;
case vrcFloatingPoint:
case vrcFixedPoint:
firstColor = FIRST_FPREGISTER;
maxColor = LAST_FPREGISTER;
break;
default:
PR_ASSERT(false);
}
if (vReg.isPreColored())
{
c = vReg.getPreColor();
if (usedRegisters.test(c))
c = -1;
}
else
{
for (c = usedRegisters.nextZero(firstColor - 1); (c >= 0) && (c <= maxColor) && (preColoredRegisters.test(c));
c = usedRegisters.nextZero(c)) {}
}
if ((c >= 0) && (c <= maxColor))
{
vReg.colorRegister(c);
}
else
{
VirtualRegister& stackRegister = vRegManager.newVirtualRegister(vrcStackSlot);
vReg.equivalentRegister[vrcStackSlot] = &stackRegister;
vReg.spillInfo.willSpill = true;
success = false;
}
}
}
#ifdef DEBUG
if (success)
{
for (VirtualRegisterManager::iterator i = vRegManager.begin(); !vRegManager.done(i); i = vRegManager.advance(i))
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(i);
switch (vReg.getClass())
{
case vrcInteger:
if (vReg.getColor() > LAST_GREGISTER)
PR_ASSERT(false);
break;
case vrcFloatingPoint:
case vrcFixedPoint:
#if NUMBER_OF_FPREGISTERS != 0
if (vReg.getColor() > LAST_FPREGISTER)
PR_ASSERT(false);
#endif
break;
default:
break;
}
}
}
#endif
vRegManager.nUsedStackSlots = lastUsedSSR + 1;
return success;
}
#endif // NEW_LAURENTM_CODE

View File

@@ -0,0 +1,284 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "RegisterAllocator.h"
#include "VirtualRegister.h"
#include "InterferenceGraph.h"
#include "SparseSet.h"
#include "Spilling.h"
#include "Splits.h"
UT_EXTERN_LOG_MODULE(RegAlloc);
template <class RegisterPressure>
class Coloring
{
private:
static RegisterName* simplify(RegisterAllocator& registerAllocator, RegisterName* coloringStack);
static bool select(RegisterAllocator& registerAllocator, RegisterName* coloringStack, RegisterName* coloringStackPtr);
public:
static bool color(RegisterAllocator& registerAllocator);
static void finalColoring(RegisterAllocator& registerAllocator);
};
template <class RegisterPressure>
void Coloring<RegisterPressure>::finalColoring(RegisterAllocator& registerAllocator)
{
RegisterName* color = registerAllocator.color;
RegisterName* name2range = registerAllocator.name2range;
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
usePtr->setRegisterName(color[name2range[usePtr->getRegisterName()]]);
#ifdef DEBUG
RegisterID rid = usePtr->getRegisterID();
setColoredRegister(rid);
usePtr->setRegisterID(rid);
#endif // DEBUG
}
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
definePtr->setRegisterName(color[name2range[definePtr->getRegisterName()]]);
#ifdef DEBUG
RegisterID rid = definePtr->getRegisterID();
setColoredRegister(rid);
definePtr->setRegisterID(rid);
#endif // DEBUG
}
}
}
}
template <class RegisterPressure>
bool Coloring<RegisterPressure>::select(RegisterAllocator& registerAllocator, RegisterName* coloringStack, RegisterName* coloringStackPtr)
{
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* color = new RegisterName[rangeCount];
registerAllocator.color = color;
for (Uint32 r = 1; r < rangeCount; r++)
color[r] = RegisterName(6); // FIX;
// Color the preColored registers.
//
VirtualRegisterManager& vrManager = registerAllocator.vrManager;
RegisterName* name2range = registerAllocator.name2range;
PreColoredRegister* machineEnd = vrManager.getMachineRegistersEnd();
for (PreColoredRegister* machinePtr = vrManager.getMachineRegistersBegin(); machinePtr < machineEnd; machinePtr++)
if (machinePtr->id != invalidID) {
color[name2range[getName(machinePtr->id)]] = machinePtr->color;
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\twill preColor range %d as %d\n", name2range[getName(machinePtr->id)], machinePtr->color));
}
SpillCost* cost = registerAllocator.spillCost;
Pool& pool = registerAllocator.pool;
SparseSet& spill = *new(pool) SparseSet(pool, rangeCount);
registerAllocator.willSpill = &spill;
SparseSet neighborColors(pool, 6); // FIX
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
bool coloringFailed = false;
while (coloringStackPtr > coloringStack) {
RegisterName range = *--coloringStackPtr;
if (!cost[range].infinite && cost[range].cost < 0) {
coloringFailed = true;
spill.set(range);
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tfailed to color %d, will spill.\n", range));
} else {
neighborColors.clear();
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
for (Int32 i = vector->count - 1; i >= 0; --i) {
RegisterName neighborColor = color[vector->neighbors[i]];
if (neighborColor < 6) // FIX
neighborColors.set(neighborColor);
}
if (neighborColors.getSize() == 6) { // FIX
coloringFailed = true;
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tfailed to color %d, ", range));
if (!Splits<RegisterPressure>::findSplit(registerAllocator, color, range)) {
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("will spill.\n"));
spill.set(range);
} else
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("will split.\n"));
} else {
for (Uint32 i = 0; i < 6; i++) // FIX
if (!neighborColors.test(i)) {
fprintf(stdout, "\twill color %d as %d\n", range, i);
color[range] = RegisterName(i);
break;
}
}
}
}
#ifdef DEBUG_LOG
if (coloringFailed) {
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring failed:\n"));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\twill spill: "));
spill.printPretty(UT_LOG_MODULE(RegAlloc));
} else {
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring succeeded:\n"));
for (Uint32 i = 1; i < rangeCount; i++)
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\trange %d colored as %d\n", i, color[i]));
}
#endif
return !coloringFailed;
}
template <class RegisterPressure>
RegisterName* Coloring<RegisterPressure>::simplify(RegisterAllocator& registerAllocator, RegisterName* coloringStack)
{
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
SpillCost* spillCost = registerAllocator.spillCost;
Uint32 rangeCount = registerAllocator.rangeCount;
Uint32* degree = new Uint32[rangeCount];
for (RegisterName i = RegisterName(1); i < rangeCount; i = RegisterName(i + 1)) {
InterferenceVector* vector = iGraph.getInterferenceVector(i);
degree[i] = (vector != NULL) ? vector->count : 0;
}
Pool& pool = registerAllocator.pool;
SparseSet low(pool, rangeCount);
SparseSet high(pool, rangeCount);
SparseSet highInfinite(pool, rangeCount);
SparseSet preColored(pool, rangeCount);
// Get the precolored registers.
//
VirtualRegisterManager& vrManager = registerAllocator.vrManager;
RegisterName* name2range = registerAllocator.name2range;
PreColoredRegister* machineEnd = vrManager.getMachineRegistersEnd();
for (PreColoredRegister* machinePtr = vrManager.getMachineRegistersBegin(); machinePtr < machineEnd; machinePtr++)
if (machinePtr->id != invalidID)
preColored.set(name2range[getName(machinePtr->id)]);
// Insert the live ranges in the sets.
//
for (Uint32 range = 1; range < rangeCount; range++)
if (!preColored.test(range))
if (degree[range] < 6) // FIX
low.set(range);
else if (!spillCost[range].infinite)
high.set(range);
else
highInfinite.set(range);
#ifdef DEBUG_LOG
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring sets:\n\tlow = "));
low.printPretty(UT_LOG_MODULE(RegAlloc));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\thigh = "));
high.printPretty(UT_LOG_MODULE(RegAlloc));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\thighInfinite = "));
highInfinite.printPretty(UT_LOG_MODULE(RegAlloc));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tpreColored = "));
preColored.printPretty(UT_LOG_MODULE(RegAlloc));
#endif // DEBUG_LOG
RegisterName* coloringStackPtr = coloringStack;
while (low.getSize() != 0 || high.getSize() != 0) {
while (low.getSize() != 0) {
RegisterName range = RegisterName(low.getOne());
low.clear(range);
*coloringStackPtr++ = range;
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
for (Int32 i = (vector->count - 1); i >= 0; --i) {
RegisterName neighbor = vector->neighbors[i];
degree[neighbor]--;
if (degree[neighbor] < 6) // FIX
if (high.test(neighbor)) {
high.clear(neighbor);
low.set(neighbor);
} else if (highInfinite.test(neighbor)) {
highInfinite.clear(neighbor);
low.set(neighbor);
}
}
}
if (high.getSize() != 0) {
RegisterName best = RegisterName(high.getOne());
double bestCost = spillCost[best].cost;
double bestDegree = degree[best];
// Choose the next best candidate.
//
for (SparseSet::iterator i = high.begin(); !high.done(i); i = high.advance(i)) {
RegisterName range = RegisterName(high.get(i));
double thisCost = spillCost[range].cost;
double thisDegree = degree[range];
if (thisCost * bestDegree < bestCost * thisDegree) {
best = range;
bestCost = thisCost;
bestDegree = thisDegree;
}
}
high.clear(best);
low.set(best);
}
}
assert(highInfinite.getSize() == 0);
delete degree;
#ifdef DEBUG_LOG
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring stack:\n\t"));
for (RegisterName* sp = coloringStack; sp < coloringStackPtr; ++sp)
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("%d ", *sp));
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\n"));
#endif // DEBUG_LOG
return coloringStackPtr;
}
template <class RegisterPressure>
bool Coloring<RegisterPressure>::color(RegisterAllocator& registerAllocator)
{
RegisterName* coloringStack = new RegisterName[registerAllocator.rangeCount];
return select(registerAllocator, coloringStack, simplify(registerAllocator, coloringStack));
}

View File

@@ -0,0 +1,212 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include <string.h>
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "DominatorGraph.h"
DominatorGraph::DominatorGraph(ControlGraph& controlGraph) : controlGraph(controlGraph)
{
Uint32 nNodes = controlGraph.nNodes;
GtoV = new Uint32[nNodes + 1];
VtoG = new Uint32[nNodes + 1];
Uint32 v = 1;
for (Uint32 n = 0; n < nNodes; n++) {
VtoG[v] = n;
GtoV[n] = v++;
}
// Initialize all the 1-based arrays.
//
parent = new Uint32[v];
semi = new Uint32[v];
vertex = new Uint32[v];
label = new Uint32[v];
size = new Uint32[v];
ancestor = new Uint32[v];
child = new Uint32[v];
dom = new Uint32[v];
bucket = new DGLinkedList*[v];
memset(semi, '\0', v * sizeof(Uint32));
memset(bucket, '\0', v * sizeof(DGLinkedList*));
vCount = v;
build();
delete parent;
delete semi;
delete vertex;
delete label;
delete size;
delete ancestor;
delete child;
delete dom;
delete bucket;
}
Uint32 DominatorGraph::DFS(Uint32 vx, Uint32 n)
{
semi[vx] = ++n;
vertex[n] = label[vx] = vx;
ancestor[vx] = child[vx] = 0;
size[vx] = 1;
ControlNode& node = *controlGraph.dfsList[VtoG[vx]];
ControlEdge* successorEnd = node.getSuccessorsEnd();
for (ControlEdge* successorPtr = node.getSuccessorsBegin(); successorPtr < successorEnd; successorPtr++) {
Uint32 w = GtoV[successorPtr->getTarget().dfsNum];
if (semi[w] == 0) {
parent[w] = vx;
n = DFS(w, n);
}
}
return n;
}
void DominatorGraph::LINK(Uint32 vx, Uint32 w)
{
Uint32 s = w;
while (semi[label[w]] < semi[label[child[s]]]) {
if (size[s] + size[child[child[s]]] >= (size[child[s]] << 1)) {
ancestor[child[s]] = s;
child[s] = child[child[s]];
} else {
size[child[s]] = size[s];
s = ancestor[s] = child[s];
}
}
label[s] = label[w];
size[vx] += size[w];
if(size[vx] < (size[w] << 1)) {
Uint32 t = s;
s = child[vx];
child[vx] = t;
}
while( s != 0 ) {
ancestor[s] = vx;
s = child[s];
}
}
void DominatorGraph::COMPRESS(Uint32 vx)
{
if(ancestor[ancestor[vx]] != 0) {
COMPRESS(ancestor[vx]);
if(semi[label[ancestor[vx]]] < semi[label[vx]])
label[vx] = label[ancestor[vx]];
ancestor[vx] = ancestor[ancestor[vx]];
}
}
Uint32 DominatorGraph::EVAL(Uint32 vx)
{
if(ancestor[vx] == 0)
return label[vx];
COMPRESS(vx);
return (semi[label[ancestor[vx]]] >= semi[label[vx]]) ? label[vx] : label[ancestor[vx]];
}
void DominatorGraph::build()
{
Uint32 n = DFS(GtoV[0], 0);
size[0] = label[0] = semi[0];
for (Uint32 i = n; i >= 2; i--) {
Uint32 w = vertex[i];
ControlNode& node = *controlGraph.dfsList[VtoG[w]];
const DoublyLinkedList<ControlEdge>& predecessors = node.getPredecessors();
for (DoublyLinkedList<ControlEdge>::iterator p = predecessors.begin(); !predecessors.done(p); p = predecessors.advance(p)) {
Uint32 vx = GtoV[predecessors.get(p).getSource().dfsNum];
Uint32 u = EVAL(vx);
if(semi[u] < semi[w])
semi[w] = semi[u];
}
DGLinkedList* elem = new DGLinkedList();
elem->next = bucket[vertex[semi[w]]];
elem->index = w;
bucket[vertex[semi[w]]] = elem;
LINK(parent[w], w);
elem = bucket[parent[w]];
while(elem != NULL) {
Uint32 vx = elem->index;
Uint32 u = EVAL(vx);
dom[vx] = (semi[u] < semi[vx]) ? u : parent[w];
elem = elem->next;
}
}
memset(size, '\0', n * sizeof(Uint32));
Pool& pool = controlGraph.pool;
nodes = new(pool) DGNode[n];
for(Uint32 j = 2; j <= n; j++) {
Uint32 w = vertex[j];
Uint32 d = dom[w];
if(d != vertex[semi[w]]) {
d = dom[d];
dom[w] = d;
}
size[d]++;
}
dom[GtoV[0]] = 0;
for (Uint32 k = 1; k <= n; k++) {
DGNode& node = nodes[VtoG[k]];
Uint32 count = size[k];
node.successorsEnd = node.successorsBegin = (count) ? new(pool) Uint32[count] : (Uint32*) 0;
}
for (Uint32 l = 2; l <= n; l++)
*(nodes[VtoG[dom[l]]].successorsEnd)++ = VtoG[l];
}
#ifdef DEBUG_LOG
void DominatorGraph::printPretty(LogModuleObject log)
{
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Dominator Graph:\n"));
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 i = 0; i < nNodes; i++) {
DGNode& node = nodes[i];
if (node.successorsBegin != node.successorsEnd) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tN%d dominates ", i));
for (Uint32* successorsPtr = node.successorsBegin; successorsPtr < node.successorsEnd; successorsPtr++)
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("N%d ", *successorsPtr));
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
}
#endif // DEBUG_LOG

View File

@@ -0,0 +1,80 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _DOMINATOR_GRAPH_H_
#define _DOMINATOR_GRAPH_H_
#include "LogModule.h"
class ControlGraph;
struct DGNode
{
Uint32* successorsBegin;
Uint32* successorsEnd;
};
struct DGLinkedList
{
DGLinkedList* next;
Uint32 index;
};
class DominatorGraph
{
private:
ControlGraph& controlGraph;
Uint32 vCount;
Uint32* VtoG;
Uint32* GtoV;
Uint32* parent;
Uint32* semi;
Uint32* vertex;
Uint32* label;
Uint32* size;
Uint32* ancestor;
Uint32* child;
Uint32* dom;
DGLinkedList** bucket;
DGNode* nodes;
private:
void build();
Uint32 DFS(Uint32 vx, Uint32 n);
void LINK(Uint32 vx, Uint32 w);
void COMPRESS(Uint32 vx);
Uint32 EVAL(Uint32 vx);
public:
DominatorGraph(ControlGraph& controlGraph);
Uint32* getSuccessorsBegin(Uint32 n) const {return nodes[n].successorsBegin;}
Uint32* getSuccessorsEnd(Uint32 n) const {return nodes[n].successorsEnd;}
#ifdef DEBUG_LOG
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
#endif // _DOMINATOR_GRAPH_H_

View File

@@ -0,0 +1,20 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "HashSet.h"

View File

@@ -0,0 +1,97 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _HASH_SET_H_
#define _HASH_SET_H_
#include "Fundamentals.h"
#include "Pool.h"
#include <string.h>
struct HashSetElement
{
Uint32 index;
HashSetElement* next;
};
class HashSet
{
private:
static const hashSize = 64;
// Return the hash code for the given element index.
static Uint32 getHashCode(Uint32 index) {return index & (hashSize - 1);} // Could be better !
private:
Pool& allocationPool;
HashSetElement** bucket;
HashSetElement* free;
private:
// No copy constructor.
HashSet(const HashSet&);
// No copy operator.
void operator = (const HashSet&);
public:
// Create a new HashSet.
inline HashSet(Pool& pool, Uint32 universeSize);
// Clear the hashset.
void clear();
// Clear the element for the given index.
void clear(Uint32 index);
// Set the element for the given index.
void set(Uint32 index);
// Return true if the element at index is a member.
bool test(Uint32 index) const;
// Union with the given hashset.
inline void or(const HashSet& set);
// Intersection with the given hashset.
inline void and(const HashSet& set);
// Difference with the given hashset.
inline void difference(const HashSet& set);
// Logical operators.
HashSet& operator |= (const HashSet& set) {or(set); return *this;}
HashSet& operator &= (const HashSet& set) {and(set); return *this;}
HashSet& operator -= (const HashSet& set) {difference(set); return *this;}
// Iterator to conform with the set API.
typedef HashSetElement* iterator;
// Return the iterator for the first element of this set.
iterator begin() const;
// Return the next iterator.
iterator advance(iterator pos) const;
// Return true if the iterator is at the end of the set.
bool done(iterator pos) const {return pos == NULL;}
};
inline HashSet::HashSet(Pool& pool, Uint32 /*universeSize*/)
: allocationPool(pool), free(NULL)
{
bucket = new(pool) HashSetElement*[hashSize];
memset(bucket, '\0', sizeof(HashSetElement*));
}
#endif // _HASH_SET_H_

View File

@@ -0,0 +1,213 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _INDEXED_POOL_H_
#define _INDEXED_POOL_H_
#include "Fundamentals.h"
#include <string.h>
#include <stdlib.h>
//------------------------------------------------------------------------------
// IndexedPool<IndexedObjectSubclass> is an indexed pool of objects. The
// template parameter 'IndexedObjectSubclass' must be a subclass of the struct
// IndexedObject.
//
// When the indexed pool is ask to allocate and initialize a new object (using
// the operator new(anIndexedPool) it will zero the memory used to store the
// object and initialize the field 'index' of this object to its position in
// the pool.
//
// An object allocated by the indexed pool can be freed by calling the method
// IndexedPool::release(IndexedElement& objectIndex).
//
// example:
//
// IndexedPool<IndexedElement> elementPool;
//
// IndexedElement& element1 = *new(elementPool) IndexedElement();
// IndexedElement& element2 = *new(elementPool) IndexedElement();
//
// indexedPool.release(element1);
// IndexedElement& element3 = *new(elementPool) IndexedElement();
//
// At this point element1 is no longer a valid object, element2 is at
// index 2 and element3 is at index 1.
//
//------------------------------------------------------------------------------
// IndexedObject -
//
template<class Object>
struct IndexedObject
{
Uint32 index; // Index in the pool.
Object* next; // Used to link IndexedObject together.
Uint32 getIndex() {return index;}
};
//------------------------------------------------------------------------------
// IndexedPool<IndexedObject> -
//
template <class IndexedObject>
class IndexedPool
{
private:
static const blockSize = 4; // Size of one block.
Uint32 nBlocks; // Number of blocks in the pool.
IndexedObject** block; // Array of block pointers.
IndexedObject* freeObjects; // Chained list of free IndexedObjects.
Uint32 nextIndex; // Index of the next free object in the last block.
private:
void allocateAnotherBlock();
IndexedObject& newObject();
public:
IndexedPool() : nBlocks(0), block(NULL), freeObjects(NULL), nextIndex(1) {}
~IndexedPool();
IndexedObject& get(Uint32 index) const;
void release(IndexedObject& object);
void setSize(Uint32 size) {assert(size < nextIndex); nextIndex = size;}
// Return the universe size.
Uint32 getSize() {return nextIndex;}
friend void* operator new(size_t, IndexedPool<IndexedObject>& pool); // Needs to call newObject().
};
// Free all the memory allocated for this object.
//
template <class IndexedObject>
IndexedPool<IndexedObject>::~IndexedPool()
{
for (Uint32 n = 0; n < nBlocks; n++)
free(&((IndexedObject **) &block[n][n*blockSize])[-(n + 1)]);
}
// Release the given. This object will be iserted in the chained
// list of free IndexedObjects. To minimize the fragmentation the chained list
// is ordered by ascending indexes.
//
template <class IndexedObject>
void IndexedPool<IndexedObject>::release(IndexedObject& object)
{
Uint32 index = object.index;
IndexedObject* list = freeObjects;
assert(&object == &get(index)); // Make sure that object is owned by this pool.
if (list == NULL) { // The list is empty.
freeObjects = &object;
object.next = NULL;
} else { // The list contains at least 1 element.
if (index < list->index) { // insert as first element.
freeObjects = &object;
object.next = list;
} else { // Find this object's place.
while ((list->next) != NULL && (list->next->index < index))
list = list->next;
object.next = list->next;
list->next = &object;
}
}
#ifdef DEBUG
// Sanity check to be sure that the list is correctly ordered.
for (IndexedObject* obj = freeObjects; obj != NULL; obj = obj->next)
if (obj->next != NULL)
assert(obj->index < obj->next->index);
#endif
}
// Create a new block of IndexedObjects. We will allocate the memory to
// store IndexedPool::blockSize IndexedObject and the new Array of block
// pointers.
// The newly created IndexedObjects will not be initialized.
//
template <class IndexedObject>
void IndexedPool<IndexedObject>::allocateAnotherBlock()
{
void* memory = (void *) malloc((nBlocks + 1) * sizeof(Uint32) + blockSize * sizeof(IndexedObject));
memcpy(memory, block, nBlocks * sizeof(Uint32));
block = (IndexedObject **) memory;
IndexedObject* objects = (IndexedObject *) &block[nBlocks + 1];
block[nBlocks] = &objects[-(nBlocks * blockSize)];
nBlocks++;
}
// Return the IndexedObject at the position 'index' in the pool.
//
template <class IndexedObject>
IndexedObject& IndexedPool<IndexedObject>::get(Uint32 index) const
{
Uint32 blockIndex = index / blockSize;
assert(blockIndex < nBlocks);
return block[blockIndex][index];
}
// Return the reference of an unused object in the pool.
//
template <class IndexedObject>
IndexedObject& IndexedPool<IndexedObject>::newObject()
{
if (freeObjects != NULL) {
IndexedObject& newObject = *freeObjects;
freeObjects = newObject.next;
return newObject;
}
Uint32 nextIndex = this->nextIndex++;
Uint32 blockIndex = nextIndex / blockSize;
while (blockIndex >= nBlocks)
allocateAnotherBlock();
IndexedObject& newObject = block[blockIndex][nextIndex];
newObject.index = nextIndex;
return newObject;
}
// Return the address of the next unsused object in the given
// indexed pool. The field index of the newly allocated object
// will be initialized to the corresponding index of this object
// in the pool.
//
template <class IndexedObject>
void* operator new(size_t size, IndexedPool<IndexedObject>& pool)
{
assert(size == sizeof(IndexedObject));
return (void *) &pool.newObject();
}
#endif // _INDEXED_POOL_H_

View File

@@ -0,0 +1,258 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _INTERFERENCE_GRAPH_H_
#define _INTERFERENCE_GRAPH_H_
#include "Fundamentals.h"
#include "ControlGraph.h"
#include "Primitives.h"
#include "Instruction.h"
#include "VirtualRegister.h"
#include "RegisterPressure.h"
#include "SparseSet.h"
#include <string.h>
struct InterferenceVector
{
Uint32 count;
InterferenceVector* next;
RegisterName* neighbors;
InterferenceVector() : count(0), next(NULL) {}
};
class RegisterAllocator;
template <class RegisterPressure>
class InterferenceGraph
{
private:
RegisterAllocator& registerAllocator;
RegisterPressure::Set* interferences;
InterferenceVector** vector;
Uint32* offset;
Uint32 rangeCount;
private:
// No copy constructor.
InterferenceGraph(const InterferenceGraph&);
// No copy operator.
void operator = (const InterferenceGraph&);
// Check if reg is a member of the universe.
void checkMember(RegisterName name) {assert(name < rangeCount);}
// Return the edge index for the interference between name1 and name2.
Uint32 getEdgeIndex(RegisterName name1, RegisterName name2);
public:
InterferenceGraph(RegisterAllocator& registerAllocator) : registerAllocator(registerAllocator) {}
// Calculate the interferences.
void build();
// Return true if reg1 and reg2 interfere.
bool interfere(RegisterName name1, RegisterName name2);
// Return the interference vector for the given register or NULL if there is none.
InterferenceVector* getInterferenceVector(RegisterName name) {return vector[name];}
// Set the interference between name1 and name2.
void setInterference(RegisterName name1, RegisterName name2);
// Set the interference vector for the given register.
void setInterferenceVector(RegisterName name, InterferenceVector* v) {vector[name] = v;}
#ifdef DEBUG_LOG
// Print the interferences.
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
template <class RegisterPressure>
void InterferenceGraph<RegisterPressure>::build()
{
Pool& pool = registerAllocator.pool;
Uint32 rangeCount = registerAllocator.rangeCount;
this->rangeCount = rangeCount;
// Initialize the structures.
//
offset = new(pool) Uint32[rangeCount + 1];
vector = new(pool) InterferenceVector*[rangeCount];
memset(vector, '\0', sizeof(InterferenceVector*) * rangeCount);
Uint32 o = 0;
offset[0] = 0;
for (Uint32 i = 1; i <= rangeCount; ++i) {
offset[i] = o;
o += i;
}
interferences = new(pool) RegisterPressure::Set(pool, (rangeCount * rangeCount) / 2);
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
RegisterName* name2range = registerAllocator.name2range;
LivenessInfo<RegisterPressure> liveness = Liveness<RegisterPressure>::analysis(controlGraph, rangeCount, name2range);
registerAllocator.liveness = liveness;
SparseSet currentLive(pool, rangeCount);
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
currentLive = liveness.liveOut[n];
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
// Handle the copy instruction to avoid unnecessary interference between the 2 registers.
if ((instruction.getFlags() & ifCopy) != 0) {
assert(useBegin != useEnd && useBegin[0].isRegister());
currentLive.clear(name2range[useBegin[0].getRegisterName()]);
}
// Create the interferences.
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName define = name2range[definePtr->getRegisterName()];
for (SparseSet::iterator e = currentLive.begin(); !currentLive.done(e); e = currentLive.advance(e)) {
RegisterName live = RegisterName(currentLive.get(e));
if ((live != define) && !interfere(live, define) && registerAllocator.canInterfere(live, define)) {
if (vector[define] == NULL)
vector[define] = new(pool) InterferenceVector();
vector[define]->count++;
if (vector[live] == NULL)
vector[live] = new(pool) InterferenceVector();
vector[live]->count++;
setInterference(live, define);
}
}
}
// Now update the liveness.
//
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentLive.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
currentLive.set(name2range[usePtr->getRegisterName()]);
}
}
// Allocate the memory to store the interferences.
//
for (Uint32 e = 0; e < rangeCount; e++)
if (vector[e] != NULL) {
InterferenceVector& v = *vector[e];
v.neighbors = new(pool) RegisterName[v.count];
v.count = 0;
}
// Initialize the edges.
//
if (RegisterPressure::Set::isOrdered()) {
RegisterName name1 = RegisterName(0);
for (RegisterPressure::Set::iterator i = interferences->begin(); !interferences->done(i); i = interferences->advance(i)) {
Uint32 interferenceIndex = interferences->get(i);
while(interferenceIndex >= offset[name1 + 1])
name1 = RegisterName(name1 + 1);
assert((interferenceIndex >= offset[name1]) && (interferenceIndex < offset[name1 + 1]));
RegisterName name2 = RegisterName(interferenceIndex - offset[name1]);
assert(interfere(name1, name2));
InterferenceVector& vector1 = *vector[name1];
vector1.neighbors[vector1.count++] = name2;
InterferenceVector& vector2 = *vector[name2];
vector2.neighbors[vector2.count++] = name1;
}
} else {
trespass("not Implemented"); // FIX: need one more pass to initialize the vectors.
}
}
template <class RegisterPressure>
Uint32 InterferenceGraph<RegisterPressure>::getEdgeIndex(RegisterName name1, RegisterName name2)
{
checkMember(name1); checkMember(name2);
assert(name1 != name2); // This is not possible.
return (name1 < name2) ? offset[name2] + name1 : offset[name1] + name2;
}
template <class RegisterPressure>
void InterferenceGraph<RegisterPressure>::setInterference(RegisterName name1, RegisterName name2)
{
interferences->set(getEdgeIndex(name1, name2));
}
template <class RegisterPressure>
bool InterferenceGraph<RegisterPressure>::interfere(RegisterName name1, RegisterName name2)
{
return interferences->test(getEdgeIndex(name1, name2));
}
#ifdef DEBUG_LOG
template <class RegisterPressure>
void InterferenceGraph<RegisterPressure>::printPretty(LogModuleObject log)
{
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Interference Vectors:\n"));
for (Uint32 i = 1; i < rangeCount; i++) {
if (vector[i] != NULL) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tvr%d: (", i));
for (InterferenceVector* v = vector[i]; v != NULL; v = v->next)
for (Uint32 j = 0; j < v->count; j++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%d", v->neighbors[j]));
if (v->next != NULL || j != (v->count - 1))
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (","));
}
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (")\n"));
}
}
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Interference Matrix:\n"));
for (RegisterName name1 = RegisterName(1); name1 < rangeCount; name1 = RegisterName(name1 + 1)) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\t%d:\t", name1));
for (RegisterName name2 = RegisterName(1); name2 < rangeCount; name2 = RegisterName(name2 + 1))
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%c", ((name1 != name2) && interfere(name1, name2)) ? '1' : '0'));
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
#endif // DEBUG_LOG
#endif // _INTERFERENCE_GRAPH_H_

View File

@@ -0,0 +1,87 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _LIVE_RANGE_H_
#define _LIVE_RANGE_H_
#include "Fundamentals.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Primitives.h"
#include "Instruction.h"
#include "RegisterAllocator.h"
#include "RegisterAllocatorTools.h"
template <class RegisterPressure>
struct LiveRange
{
static void build(RegisterAllocator& registerAllocator);
};
template <class RegisterPressure>
void LiveRange<RegisterPressure>::build(RegisterAllocator& registerAllocator)
{
// Intialize the lookup table.
//
Uint32 nameCount = registerAllocator.nameCount;
RegisterName* nameTable = new(registerAllocator.pool) RegisterName[2*nameCount];
RegisterName* rangeName = &nameTable[nameCount];
init(rangeName, nameCount);
// Walk the graph.
//
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
SparseSet destination(registerAllocator.pool, nameCount);
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
destination.clear();
for (InstructionList::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
Instruction& phiNode = phiNodes.get(i);
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
destination.set(findRoot(phiNode.getInstructionDefineBegin()[0].getRegisterName(), rangeName));
}
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& phiNode = phiNodes.get(p);
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
RegisterName destinationName = phiNode.getInstructionDefineBegin()[0].getRegisterName();
RegisterName destinationRoot = findRoot(destinationName, rangeName);
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++) {
assert(usePtr->isRegister());
RegisterName sourceName = usePtr->getRegisterName();
RegisterName sourceRoot = findRoot(sourceName, rangeName);
if (sourceRoot != destinationRoot && !destination.test(sourceRoot))
rangeName[sourceRoot] = destinationRoot;
}
}
}
registerAllocator.rangeCount = compress(registerAllocator.name2range, rangeName, nameCount, nameCount);
}
#endif // _LIVE_RANGE_H_

View File

@@ -0,0 +1,163 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _LIVE_RANGE_GRAPH_
#define _LIVE_RANGE_GRAPH_
#include "Fundamentals.h"
#include "Pool.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "RegisterTypes.h"
class RegisterAllocator;
template <class RegisterPressure>
class LiveRangeGraph
{
private:
RegisterAllocator& registerAllocator;
RegisterPressure::Set* edges;
Uint32 rangeCount;
public:
//
//
LiveRangeGraph(RegisterAllocator& registerAllocator) : registerAllocator(registerAllocator) {}
//
//
void build();
//
//
void addEdge(RegisterName name1, RegisterName name2);
//
//
bool haveEdge(RegisterName name1, RegisterName name2);
#ifdef DEBUG_LOG
//
//
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
template <class RegisterPressure>
void LiveRangeGraph<RegisterPressure>::build()
{
Pool& pool = registerAllocator.pool;
Uint32 rangeCount = registerAllocator.rangeCount;
this->rangeCount = rangeCount;
edges = new(pool) RegisterPressure::Set(pool, rangeCount * rangeCount);
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
RegisterName* name2range = registerAllocator.name2range;
LivenessInfo<RegisterPressure>& liveness = registerAllocator.liveness;
SparseSet currentLive(pool, rangeCount);
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
currentLive = liveness.liveOut[n];
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
if ((instruction.getFlags() & ifCopy) != 0) {
assert(useBegin != useEnd && useBegin[0].isRegister());
currentLive.clear(name2range[useBegin[0].getRegisterName()]);
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName define = name2range[definePtr->getRegisterName()];
for (SparseSet::iterator l = currentLive.begin(); !currentLive.done(l); l = currentLive.advance(l)) {
RegisterName live = RegisterName(currentLive.get(l));
if (define != live && registerAllocator.canInterfere(define, live))
addEdge(define, live);
}
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentLive.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
currentLive.set(name2range[usePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName use = name2range[usePtr->getRegisterName()];
for (SparseSet::iterator l = currentLive.begin(); !currentLive.done(l); l = currentLive.advance(l)) {
RegisterName live = RegisterName(currentLive.get(l));
if (use != live && registerAllocator.canInterfere(use, live))
addEdge(use, live);
}
}
}
}
}
template <class RegisterPressure>
void LiveRangeGraph<RegisterPressure>::addEdge(RegisterName name1, RegisterName name2)
{
assert(name1 != name2);
edges->set(name1 * rangeCount + name2);
}
template <class RegisterPressure>
bool LiveRangeGraph<RegisterPressure>::haveEdge(RegisterName name1, RegisterName name2)
{
assert(name1 != name2);
return edges->test(name1 * rangeCount + name2);
}
#ifdef DEBUG_LOG
template <class RegisterPressure>
void LiveRangeGraph<RegisterPressure>::printPretty(LogModuleObject log)
{
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Live ranges graph:\n"));
for (RegisterName name1 = RegisterName(1); name1 < rangeCount; name1 = RegisterName(name1 + 1)) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\t%d:\t", name1));
for (RegisterName name2 = RegisterName(1); name2 < rangeCount; name2 = RegisterName(name2 + 1))
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%c", ((name1 != name2) && haveEdge(name1, name2)) ? '1' : '0'));
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
#endif // DEBUG_LOG
#endif // _LIVE_RANGE_GRAPH_

View File

@@ -0,0 +1,21 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "Liveness.h"

View File

@@ -0,0 +1,301 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _LIVENESS_H_
#define _LIVENESS_H_
#include "Fundamentals.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "RegisterTypes.h"
// ----------------------------------------------------------------------------
// LivenessInfo -
template <class RegisterPressure>
struct LivenessInfo
{
RegisterPressure::Set* liveIn;
RegisterPressure::Set* liveOut;
DEBUG_LOG_ONLY(Uint32 size);
#ifdef DEBUG_LOG
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
// ----------------------------------------------------------------------------
// Liveness
//
// The liveness is defined by the following data-flow equations:
//
// LiveIn(n) = LocalLive(n) U (LiveOut(n) - Killed(n)).
// LiveOut(n) = U LiveIn(s) (s a successor of n).
//
// where LocalLive(n) is the set of used registers in the block n, Killed(n)
// is the set of defined registers in the block n, LiveIn(n) is the set of
// live registers at the begining of the block n and LiveOut(n) is the set
// of live registers at the end of the block n.
//
//
// We will compute the liveness analysis in two stages:
//
// 1- Build LocalLive(n) (wich is an approximation of LiveIn(n)) and Killed(n)
// for each block n.
// 2- Perform a backward data-flow analysis to propagate the liveness information
// through the entire control-flow graph.
//
template <class RegisterPressure>
struct Liveness
{
static LivenessInfo<RegisterPressure> analysis(ControlGraph& controlGraph, Uint32 rangeCount, const RegisterName* name2range);
static LivenessInfo<RegisterPressure> analysis(ControlGraph& controlGraph, Uint32 nameCount);
};
template <class RegisterPressure>
LivenessInfo<RegisterPressure> Liveness<RegisterPressure>::analysis(ControlGraph& controlGraph, Uint32 rangeCount, const RegisterName* name2range)
{
Pool& pool = controlGraph.pool;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
// Allocate the temporary sets.
RegisterPressure::Set* killed = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
// Allocate the globals sets.
RegisterPressure::Set* liveIn = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
RegisterPressure::Set* liveOut = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
// First stage of the liveness analysis: Compute the sets LocalLive(stored in LiveIn) and Killed.
//
for (Uint32 n = 0; n < (nNodes - 1); n++) {
ControlNode& node = *nodes[n];
RegisterPressure::Set& currentLocalLive = liveIn[n];
RegisterPressure::Set& currentKilled = killed[n];
// Find the instructions contributions to the sets LocalLive and Killed.
//
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
// If a VirtualRegister is 'used' before being 'defined' then we add it to set LocalLive.
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
Uint32 index = name2range[usePtr->getRegisterName()];
if (!currentKilled.test(index))
currentLocalLive.set(index);
}
// If a Virtualregister is 'defined' then we add it to the set Killed.
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentKilled.set(name2range[definePtr->getRegisterName()]);
}
}
// Second stage of the liveness analysis: We propagate the LiveIn & LiveOut through the entire
// control-flow graph.
//
RegisterPressure::Set temp(pool, rangeCount);
bool changed;
do {
changed = false;
// For all nodes is this graph except the endNode.
for (Int32 n = (nNodes - 2); n >= 0; n--) {
ControlNode& node = *nodes[n];
RegisterPressure::Set& currentLiveIn = liveIn[n];
RegisterPressure::Set& currentLiveOut = liveOut[n];
// Compute temp = Union of LiveIn(s) (s a successor of this node) | usedByPhiNodes(n).
// temp will be the new LiveOut(n).
Uint32 nSuccessors = node.nSuccessors();
if (nSuccessors != 0) {
temp = liveIn[node.nthSuccessor(0).getTarget().dfsNum];
for (Uint32 s = 1; s < nSuccessors; s++)
temp |= liveIn[node.nthSuccessor(s).getTarget().dfsNum];
} else
temp.clear();
// If temp and LiveOut(n) differ then set LiveOut(n) = temp and recalculate the
// new LiveIn(n).
if (currentLiveOut != temp) {
currentLiveOut = temp;
temp -= killed[n]; // FIX: could be optimized with one call to unionDiff !
temp |= currentLiveIn;
if (currentLiveIn != temp) {
currentLiveIn = temp;
changed = true;
}
}
}
} while(changed);
LivenessInfo<RegisterPressure> liveness;
liveness.liveIn = liveIn;
liveness.liveOut = liveOut;
DEBUG_LOG_ONLY(liveness.size = nNodes);
return liveness;
}
template <class RegisterPressure>
LivenessInfo<RegisterPressure> Liveness<RegisterPressure>::analysis(ControlGraph& controlGraph, Uint32 nameCount)
{
Pool& pool = controlGraph.pool;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
// Allocate the temporary sets.
RegisterPressure::Set* killed = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
RegisterPressure::Set* usedByPhiNodes = NULL;
// Allocate the globals sets.
RegisterPressure::Set* liveIn = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
RegisterPressure::Set* liveOut = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
// First stage of the liveness analysis: Compute the sets LocalLive(stored in LiveIn) and Killed.
//
for (Uint32 n = 0; n < (nNodes - 1); n++) {
ControlNode& node = *nodes[n];
RegisterPressure::Set& currentLocalLive = liveIn[n];
RegisterPressure::Set& currentKilled = killed[n];
InstructionList& phiNodes = node.getPhiNodeInstructions();
if ((usedByPhiNodes == NULL) && !phiNodes.empty())
usedByPhiNodes = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& phiNode = phiNodes.get(p);
InstructionDefine& define = phiNode.getInstructionDefineBegin()[0];
currentKilled.set(define.getRegisterName());
typedef DoublyLinkedList<ControlEdge> ControlEdgeList;
const ControlEdgeList& predecessors = node.getPredecessors();
ControlEdgeList::iterator p = predecessors.begin();
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++, p = predecessors.advance(p))
if (usePtr->isRegister())
usedByPhiNodes[predecessors.get(p).getSource().dfsNum].set(usePtr->getRegisterName());
}
// Find the instructions contributions to the sets LocalLive and Killed.
//
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
// If a VirtualRegister is 'used' before being 'defined' then we add it to set LocalLive.
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
Uint32 index = usePtr->getRegisterName();
if (!currentKilled.test(index))
currentLocalLive.set(index);
}
// If a Virtualregister is 'defined' then we add it to the set Killed.
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentKilled.set(definePtr->getRegisterName());
}
}
// Second stage of the liveness analysis: We propagate the LiveIn & LiveOut through the entire
// control-flow graph.
//
RegisterPressure::Set temp(pool, nameCount);
bool changed;
do {
changed = false;
// For all nodes is this graph except the endNode.
for (Int32 n = (nNodes - 2); n >= 0; n--) {
ControlNode& node = *nodes[n];
RegisterPressure::Set& currentLiveIn = liveIn[n];
RegisterPressure::Set& currentLiveOut = liveOut[n];
// Compute temp = Union of LiveIn(s) (s a successor of this node) | usedByPhiNodes(n).
// temp will be the new LiveOut(n).
Uint32 nSuccessors = node.nSuccessors();
if (nSuccessors != 0) {
temp = liveIn[node.nthSuccessor(0).getTarget().dfsNum];
for (Uint32 s = 1; s < nSuccessors; s++)
temp |= liveIn[node.nthSuccessor(s).getTarget().dfsNum];
} else
temp.clear();
// Insert the phiNodes contribution.
if (usedByPhiNodes != NULL)
temp |= usedByPhiNodes[n];
// If temp and LiveOut(n) differ then set LiveOut(n) = temp and recalculate the
// new LiveIn(n).
if (currentLiveOut != temp) {
currentLiveOut = temp;
temp -= killed[n]; // FIX: could be optimized with one call to unionDiff !
temp |= currentLiveIn;
if (currentLiveIn != temp) {
currentLiveIn = temp;
changed = true;
}
}
}
} while(changed);
LivenessInfo<RegisterPressure> liveness;
liveness.liveIn = liveIn;
liveness.liveOut = liveOut;
DEBUG_LOG_ONLY(liveness.size = nNodes);
return liveness;
}
#ifdef DEBUG_LOG
template <class RegisterPressure>
void LivenessInfo<RegisterPressure>::printPretty(LogModuleObject log)
{
for (Uint32 n = 0; n < size; n++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Node N%d:\n\tliveIn = ", n));
liveIn[n].printPretty(log);
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tliveOut = "));
liveOut[n].printPretty(log);
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
#endif // DEBUG_LOG
#endif // _LIVENESS_H_

View File

@@ -0,0 +1,40 @@
#! gmake
DEPTH = ../..
MODULE_NAME = RegisterAllocator
include $(DEPTH)/config/config.mk
INCLUDES += \
-I$(DEPTH)/Utilities/General \
-I$(DEPTH)/Utilities/zlib \
-I$(DEPTH)/Runtime/ClassReader \
-I$(DEPTH)/Runtime/NativeMethods \
-I$(DEPTH)/Runtime/System \
-I$(DEPTH)/Runtime/ClassInfo \
-I$(DEPTH)/Runtime/FileReader \
-I$(DEPTH)/Compiler/PrimitiveGraph \
-I$(DEPTH)/Compiler/FrontEnd \
-I$(DEPTH)/Compiler/Optimizer \
-I$(DEPTH)/Compiler/CodeGenerator \
-I$(DEPTH)/Compiler/CodeGenerator/md \
-I$(DEPTH)/Compiler/CodeGenerator/md/$(CPU_ARCH) \
-I$(DEPTH)/Compiler/RegisterAllocator \
-I$(DEPTH)/Driver/StandAloneJava \
-I$(DEPTH)/Debugger \
$(NULL)
CXXSRCS = \
RegisterAllocator.cpp \
RegisterAllocatorTools.cpp \
DominatorGraph.cpp \
VirtualRegister.cpp \
BitSet.cpp \
SparseSet.cpp \
$(NULL)
include $(DEPTH)/config/rules.mk
libs:: $(MODULE)

View File

@@ -0,0 +1,392 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _PHI_NODE_REMOVER_H_
#define _PHI_NODE_REMOVER_H_
#include "Fundamentals.h"
#include "Pool.h"
#include "ControlGraph.h"
#include "DominatorGraph.h"
#include "VirtualRegister.h"
#include "RegisterPressure.h"
#include "Liveness.h"
#include "Instruction.h"
#include "InstructionEmitter.h"
#include "SparseSet.h"
#include <string.h>
//------------------------------------------------------------------------------
// RegisterNameNode -
struct RegisterNameNode
{
RegisterNameNode* next;
RegisterName newName;
Uint32 nextPushed;
};
//------------------------------------------------------------------------------
// CopyData -
struct CopyData
{
RegisterName source;
RegisterClassKind classKind;
Uint32 useCount;
bool isLiveOut;
RegisterName sourceNameToUse;
RegisterName temporaryName;
RegisterNameNode* newName;
};
//------------------------------------------------------------------------------
// PhiNodeRemover<RegisterPressure> -
template <class RegisterPressure>
struct PhiNodeRemover
{
// Replace the phi nodes by copy instructions.
static void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
};
// Split some of the critical edges and return true if there are still some
// in the graph after that.
//
static bool splitCriticalEdges(ControlGraph& /*cg*/)
{
// FIX: not implemented.
return true;
}
inline void pushName(Pool& pool, RegisterNameNode** stack, SparseSet& pushed, Uint32* nodeListPointer, RegisterName oldName, RegisterName newName)
{
RegisterNameNode& newNode = *new(pool) RegisterNameNode();
if (pushed.test(oldName))
(*stack)->newName = newName;
else {
newNode.newName = newName;
newNode.nextPushed = *nodeListPointer;
*nodeListPointer = oldName;
newNode.next = *stack;
*stack = &newNode;
pushed.set(oldName);
}
}
template <class RegisterPressure>
void PhiNodeRemover<RegisterPressure>::replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
{
Pool& pool = controlGraph.pool;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
// Initialize the local variables.
//
// When we insert the copies we will also need to create new VirtualRegisters for
// the insertion of temporaries. The maximum number of temporary register will not
// exceed the number of phiNodes in the primitive graph.
Uint32 nameCount = vrManager.getSize();
Uint32 maxNameCount = nameCount;
for (Uint32 n = 0; n < nNodes; n++)
maxNameCount += nodes[n]->getPhiNodes().length();
// If the CFG contains some critical edges (backward edge which source has more than one
// outgoing edge and destination has more than one incomimg edge) then we need the liveness
// information to be able to insert temporary copies.
RegisterPressure::Set* liveOut = NULL;
if (splitCriticalEdges(controlGraph))
liveOut = Liveness<LowRegisterPressure>::analysis(controlGraph, nameCount).liveOut;
DominatorGraph dGraph(controlGraph);
SparseSet pushed(pool, maxNameCount);
SparseSet destinationList(pool, maxNameCount);
SparseSet workList(pool, maxNameCount);
CopyData* copyStats = new(pool) CopyData[maxNameCount];
memset(copyStats, '\0', maxNameCount*sizeof(CopyData));
struct NodeStack {
Uint32* next;
Uint32* limit;
Uint32 pushedList;
};
// Allocate the node stack and initialize the node stack pointer.
NodeStack* nodeStack = new(pool) NodeStack[nNodes + 1];
NodeStack* nodeStackPtr = nodeStack;
// We start by the begin node.
Uint32 startNode = 0;
Uint32* next = &startNode;
Uint32* limit = &startNode + 1;
while (true) {
if (next == limit) {
// If there are no more node in the sibling, we have to pop the current
// frame from the stack and update the copyStats of the pushed nodes.
//
if (nodeStackPtr == nodeStack)
// We are at the bottom of the stack and there are no more nodes
// to look at. We are done !
break;
--nodeStackPtr;
// We are done with all the children of this node in the dominator tree.
// We need to update the copy information of all the new names pushed
// during the walk over this node.
Uint32 pushedList = nodeStackPtr->pushedList;
while (pushedList != 0) {
Uint32 nextName = copyStats[pushedList].newName->nextPushed;
copyStats[pushedList].newName = copyStats[pushedList].newName->next;
pushedList = nextName;
}
// restore the previous frame.
next = nodeStackPtr->next;
limit = nodeStackPtr->limit;
} else {
Uint32 currentNode = *next++;
Uint32 pushedList = 0;
// Initialize the sets.
pushed.clear();
destinationList.clear();
// STEP1:
// Walk the instruction list and to replace all the instruction uses with their new name.
// If the instruction is a phi node and its defined register is alive at the end of this
// block then we push the defined register into the stack.
//
ControlNode& node = *nodes[currentNode];
RegisterPressure::Set* currentLiveOut = (liveOut != NULL) ? &liveOut[currentNode] : (RegisterPressure::Set*) 0;
InstructionList& phiNodes = node.getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& phiNode = phiNodes.get(p);
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++) {
assert(usePtr->isRegister());
RegisterName name = usePtr->getRegisterName();
if (copyStats[name].newName != NULL && copyStats[name].newName->newName != name)
usePtr->setRegisterName(copyStats[name].newName->newName);
}
if (currentLiveOut != NULL) {
// This is a phi node and we have to push its defined name if it is live
// at the end of the node. We only need to do this if the CFG has critical edges.
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
RegisterName name = phiNode.getInstructionDefineBegin()[0].getRegisterName();
if (currentLiveOut->test(name))
pushName(pool, &(copyStats[name].newName), pushed, &pushedList, name, name);
}
}
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName name = usePtr->getRegisterName();
if (copyStats[name].newName != NULL && copyStats[name].newName->newName != name)
usePtr->setRegisterName(copyStats[name].newName->newName);
}
}
// STEP2:
// Look at this node's successors' phiNodes. We keep track of the number of time
// a VR will be used by another copy instruction and insert each definition into the
// destinationList. This is the only pass over this node's successors as we will
// get all the information we need in the CopyData structures.
//
ControlEdge* successorEdgeEnd = node.getSuccessorsEnd();
for (ControlEdge* successorEdgePtr = node.getSuccessorsBegin(); successorEdgePtr < successorEdgeEnd; successorEdgePtr++) {
Uint32 useIndex = successorEdgePtr->getIndex();
ControlNode& successor = successorEdgePtr->getTarget();
// Look at its phi nodes. The phi nodes are at the top of the instruction list. We exit
// as soon as we find an instruction which is not a phi node
InstructionList& phiNodes = successor.getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& phiNode = phiNodes.get(p);
assert((phiNode.getInstructionUseBegin() + useIndex) < phiNode.getInstructionUseEnd());
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd());
InstructionUse& source = phiNode.getInstructionUseBegin()[useIndex];
InstructionDefine& destination = phiNode.getInstructionDefineBegin()[0];
assert(source.isRegister() && destination.isRegister());
RegisterName sourceName = source.getRegisterName();
RegisterName destinationName = destination.getRegisterName();
// Get the correct name for the source.
if (copyStats[sourceName].newName != NULL)
sourceName = copyStats[sourceName].newName->newName;
// Update the CopyData structures.
if ((sourceName != rnInvalid) && (sourceName != destinationName)) {
copyStats[destinationName].source = sourceName;
copyStats[destinationName].classKind = destination.getRegisterClass();
copyStats[destinationName].isLiveOut = (currentLiveOut != NULL) ? currentLiveOut->test(destinationName) : false;
copyStats[destinationName].sourceNameToUse = destinationName;
copyStats[sourceName].sourceNameToUse = sourceName;
copyStats[sourceName].useCount++;
destinationList.set(destinationName);
}
}
}
// STEP3:
// Insert into the worklist only the destination registers that will be not used in
// another copy instruction in this block.
//
assert(workList.getSize() == 0);
for (SparseSet::iterator d = destinationList.begin(); !destinationList.done(d); d = destinationList.advance(d)) {
Uint32 dest = destinationList.get(d);
if (copyStats[dest].useCount == 0)
workList.set(dest);
}
// STEP4:
// Insert the copy instructions.
//
Uint32 destinationListSize = destinationList.getSize();
InstructionList::iterator endOfTheNode = instructions.end();
// Find the right place to insert the copy instructions.
if (destinationListSize != 0)
while (instructions.get(endOfTheNode).getFlags() & ifControl)
endOfTheNode = instructions.retreat(endOfTheNode);
while (destinationListSize != 0) {
while(workList.getSize()) {
RegisterName destinationName = RegisterName(workList.getOne());
RegisterName sourceName = copyStats[destinationName].source;
workList.clear(destinationName);
if (copyStats[destinationName].isLiveOut && !copyStats[destinationName].temporaryName) {
// Lost copy problem.
copyStats[destinationName].isLiveOut = false;
RegisterName sourceName = destinationName;
RegisterClassKind classKind = copyStats[sourceName].classKind;
RegisterName destinationName = getName(vrManager.newVirtualRegister(classKind));
assert(destinationName < maxNameCount);
copyStats[destinationName].classKind = classKind;
copyStats[sourceName].useCount = 0;
// We need to insert a copy to a temporary register to keep the
// source register valid at the end of the node defining it.
// This copy will be inserted right after the phi node defining it.
RegisterName from = copyStats[sourceName].sourceNameToUse;
Instruction* definingPhiNode = vrManager.getVirtualRegister(from).getDefiningInstruction();
assert(definingPhiNode && (definingPhiNode->getFlags() & ifPhiNode) != 0);
RegisterID fromID = buildRegisterID(from, classKind);
RegisterID toID = buildRegisterID(destinationName, classKind);
Instruction& copy = emitter.newCopy(*definingPhiNode->getPrimitive(), fromID, toID);
vrManager.getVirtualRegister(destinationName).setDefiningInstruction(copy);
definingPhiNode->getPrimitive()->getContainer()->getInstructions().addFirst(copy);
copyStats[sourceName].temporaryName = destinationName;
copyStats[sourceName].sourceNameToUse = destinationName;
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
}
// Insert the copy instruction at the end of the current node.
RegisterName from = copyStats[sourceName].sourceNameToUse;
RegisterClassKind classKind = copyStats[destinationName].classKind;
RegisterID fromID = buildRegisterID(from, classKind);
RegisterID toID = buildRegisterID(destinationName, classKind);
Instruction& copy = emitter.newCopy(*vrManager.getVirtualRegister(from).getDefiningInstruction()->getPrimitive(), fromID, toID);
instructions.insertAfter(copy, endOfTheNode);
endOfTheNode = instructions.advance(endOfTheNode);
copyStats[sourceName].useCount = 0;
if (destinationList.test(sourceName) && copyStats[sourceName].isLiveOut)
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
copyStats[sourceName].isLiveOut = false;
copyStats[sourceName].sourceNameToUse = destinationName;
if (destinationList.test(sourceName))
workList.set(sourceName);
destinationList.clear(destinationName);
}
destinationListSize = destinationList.getSize();
if (destinationListSize != 0) {
RegisterName sourceName = RegisterName(destinationList.getOne());
RegisterName destinationName;
if (!copyStats[sourceName].temporaryName) {
// Cycle problem.
RegisterClassKind classKind = copyStats[sourceName].classKind;
destinationName = getName(vrManager.newVirtualRegister(classKind));
assert(destinationName < maxNameCount);
copyStats[destinationName].classKind = classKind;
copyStats[sourceName].temporaryName = destinationName;
// Insert the copy instruction at the end of the current node.
RegisterName from = copyStats[sourceName].sourceNameToUse;
RegisterID fromID = buildRegisterID(from, classKind);
RegisterID toID = buildRegisterID(destinationName, classKind);
Instruction& copy = emitter.newCopy(*vrManager.getVirtualRegister(from).getDefiningInstruction()->getPrimitive(), fromID, toID);
vrManager.getVirtualRegister(destinationName).setDefiningInstruction(copy);
instructions.insertAfter(copy, endOfTheNode);
endOfTheNode = instructions.advance(endOfTheNode);
} else
destinationName = copyStats[sourceName].temporaryName;
copyStats[sourceName].useCount = 0;
copyStats[sourceName].isLiveOut = false;
copyStats[sourceName].sourceNameToUse = destinationName;
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
workList.set(sourceName);
}
}
nodeStackPtr->pushedList = pushedList;
nodeStackPtr->next = next;
nodeStackPtr->limit = limit;
++nodeStackPtr;
next = dGraph.getSuccessorsBegin(currentNode);
limit = dGraph.getSuccessorsEnd(currentNode);
}
}
}
#endif // _PHI_NODE_REMOVER_H_

View File

@@ -0,0 +1,155 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "LogModule.h"
#include "RegisterAllocator.h"
#include "RegisterPressure.h"
#include "RegisterAllocatorTools.h"
#include "PhiNodeRemover.h"
#include "LiveRange.h"
#include "Liveness.h"
#include "InterferenceGraph.h"
#include "LiveRangeGraph.h"
#include "Coalescing.h"
#include "Spilling.h"
#include "Coloring.h"
#include "Splits.h"
class Pool;
class ControlGraph;
class VirtualRegisterManager;
class InstructionEmitter;
UT_DEFINE_LOG_MODULE(RegAlloc);
void RegisterAllocator::allocateRegisters(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
{
// Insert the phi node instructions. We want to do this to have a single defined register per instruction.
// If we keep the PhiNode (as a DataNode) and a PhiNode is of DoubleWordKind then we have to execute
// some special code for the high word annotation.
//
RegisterAllocatorTools::insertPhiNodeInstructions(controlGraph, emitter);
// Perform some tests on the instruction graph.
//
DEBUG_ONLY(RegisterAllocatorTools::testTheInstructionGraph(controlGraph, vrManager));
// Replace the phi node instructions by their equivalent copy instructions.
//
PhiNodeRemover<LowRegisterPressure>::replacePhiNodes(controlGraph, vrManager, emitter);
// Do the register allocation.
//
RegisterAllocator registerAllocator(pool, controlGraph, vrManager, emitter);
registerAllocator.doGraphColoring();
}
void RegisterAllocator::doGraphColoring()
{
// Initialize the liverange map.
//
initLiveRanges();
// Build the live ranges. We do this to compress the number of RegisterNames
// used in the insterference graph.
//
LiveRange<LowRegisterPressure>::build(*this);
// Remove unnecessary copies.
//
RegisterAllocatorTools::removeUnnecessaryCopies(*this);
for (Uint8 loop = 0; loop < 10; loop++) {
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("********* RegisterAllocator loop %d *********\n", loop));
while(true) {
// Build the interference graph.
//
iGraph.build();
// Coalesce the copy instructions.
//
if (!Coalescing<LowRegisterPressure>::coalesce(*this))
break;
}
// Print the interference graph.
//
DEBUG_LOG_ONLY(iGraph.printPretty(UT_LOG_MODULE(RegAlloc)));
// Calculate the spill costs.
//
Spilling<LowRegisterPressure>::calculateSpillCosts(*this);
DEBUG_LOG_ONLY(RegisterAllocatorTools::printSpillCosts(*this));
// Calculate the split costs.
//
Splits<LowRegisterPressure>::calculateSplitCosts(*this);
DEBUG_LOG_ONLY(RegisterAllocatorTools::printSplitCosts(*this));
// Build the live range graph.
//
lGraph.build();
DEBUG_LOG_ONLY(lGraph.printPretty(UT_LOG_MODULE(RegAlloc)));
// Color the graph. If it succeeds then we're done with the
// register allocation.
//
if (Coloring<LowRegisterPressure>::color(*this)) {
// Write the final colors in the instruction graph.
//
Coloring<LowRegisterPressure>::finalColoring(*this);
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("********** RegisterAllocator done **********\n"));
DEBUG_LOG_ONLY(RegisterAllocatorTools::printInstructions(*this));
return;
}
// We need to spill some registers.
//
Spilling<LowRegisterPressure>::insertSpillCode(*this);
// Insert the split instructions.
//
Splits<LowRegisterPressure>::insertSplitCode(*this);
// Update the live ranges.
//
// FIX
}
#ifdef DEBUG_LOG
RegisterAllocatorTools::updateInstructionGraph(*this);
RegisterAllocatorTools::printInstructions(*this);
#endif
fprintf(stderr, "!!! Coloring failed after 10 loops !!!\n");
abort();
}
void RegisterAllocator::initLiveRanges()
{
Uint32 count = this->nameCount;
RegisterName* name2range = new(pool) RegisterName[nameCount];
for (RegisterName r = RegisterName(1); r < count; r = RegisterName(r + 1))
name2range[r] = r;
this->name2range = name2range;
rangeCount = count;
}

View File

@@ -0,0 +1,88 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_ALLOCATOR_H_
#define _REGISTER_ALLOCATOR_H_
class Pool;
class ControlGraph;
class InstructionEmitter;
struct SpillCost;
struct SplitCost;
#include "Liveness.h"
#include "VirtualRegister.h"
#include "RegisterPressure.h" // This should included by Backend.cpp
#include "InterferenceGraph.h"
#include "LiveRangeGraph.h"
//template <class RegisterPressure>
class RegisterAllocator
{
public:
Pool& pool; //
ControlGraph& controlGraph; //
VirtualRegisterManager& vrManager; //
InstructionEmitter& emitter; //
RegisterName* name2range; //
RegisterName* color; //
SpillCost* spillCost; //
SparseSet* willSpill; //
SplitCost* splitCost; //
NameLinkedList** splitAround; //
InterferenceGraph<LowRegisterPressure> iGraph; //
LiveRangeGraph<LowRegisterPressure> lGraph; //
LivenessInfo<LowRegisterPressure> liveness; //
Uint32 nameCount; //
Uint32 rangeCount; //
bool splitFound; //
private:
//
//
void doGraphColoring();
public:
//
//
inline RegisterAllocator(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
//
//
bool canInterfere(RegisterName /*name1*/, RegisterName /*name2*/) const {return true;}
//
//
void initLiveRanges();
//
//
static void allocateRegisters(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
};
//
//
inline RegisterAllocator::RegisterAllocator(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
: pool(pool), controlGraph(controlGraph), vrManager(vrManager), emitter(emitter), iGraph(*this), lGraph(*this), nameCount(vrManager.getSize()) {}
#endif // _REGISTER_ALLOCATOR_H_

View File

@@ -0,0 +1,355 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "LogModule.h"
#include "RegisterAllocatorTools.h"
#include "Pool.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Primitives.h"
#include "InstructionEmitter.h"
#include "Instruction.h"
#include "RegisterAllocator.h"
#include "Spilling.h"
#include "Splits.h"
#include "BitSet.h"
UT_EXTERN_LOG_MODULE(RegAlloc);
#ifdef DEBUG
void RegisterAllocatorTools::testTheInstructionGraph(ControlGraph& controlGraph, VirtualRegisterManager& vrManager)
{
// Test the declared VirtualRegisters. The register allocator tries to condense the register universe.
// Any gap in the VirtualRegister names will be a loss of efficiency !!!!
Uint32 nameCount = vrManager.getSize();
BitSet registerSeen(controlGraph.pool, nameCount);
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
registerSeen.set(usePtr->getRegisterName());
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
registerSeen.set(definePtr->getRegisterName());
}
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& instruction = phiNodes.get(p);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
registerSeen.set(usePtr->getRegisterName());
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
registerSeen.set(definePtr->getRegisterName());
}
}
bool renameRegisters = false;
for (BitSet::iterator i = registerSeen.nextZero(0); !registerSeen.done(i); i = registerSeen.nextZero(i)) {
renameRegisters = true;
fprintf(stderr,
"WARNING: The VirtualRegister vr%d has been allocated during CodeGeneration but\n"
" is never used nor defined by any instruction in the instruction graph\n"
" PLEASE FIX \n",
i);
}
if (renameRegisters) {
Instruction** definingInstruction = new Instruction*[nameCount];
memset(definingInstruction, '\0', nameCount * sizeof(Instruction*));
RegisterName* newName = new RegisterName[nameCount];
memset(newName, '\0', nameCount * sizeof(RegisterName));
RegisterName nextName = RegisterName(1);
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName name = usePtr->getRegisterName();
if (newName[name] == rnInvalid) {
newName[name] = nextName;
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
nextName = RegisterName(nextName + 1);
}
usePtr->setRegisterName(newName[name]);
}
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName name = definePtr->getRegisterName();
if (newName[name] == rnInvalid) {
newName[name] = nextName;
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
nextName = RegisterName(nextName + 1);
}
definePtr->setRegisterName(newName[name]);
}
}
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& instruction = phiNodes.get(p);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName name = usePtr->getRegisterName();
if (newName[name] == rnInvalid) {
newName[name] = nextName;
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
nextName = RegisterName(nextName + 1);
}
usePtr->setRegisterName(newName[name]);
}
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName name = definePtr->getRegisterName();
if (newName[name] == rnInvalid) {
newName[name] = nextName;
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
nextName = RegisterName(nextName + 1);
}
definePtr->setRegisterName(newName[name]);
}
}
}
vrManager.setSize(nextName);
for (RegisterName r = RegisterName(1); r < nextName; r = RegisterName(r + 1))
vrManager.getVirtualRegister(r).definingInstruction = definingInstruction[r];
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("RegisterMap:\n"));
for (Uint32 i = 1; i < nameCount; i++)
if (newName[i] != 0)
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tvr%d becomes vr%d.\n", i, newName[i]));
else
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tvr%d is dead.\n", i));
delete newName;
delete definingInstruction;
}
}
#endif // DEBUG
void RegisterAllocatorTools::removeUnnecessaryCopies(RegisterAllocator& registerAllocator)
{
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
RegisterName* name2range = registerAllocator.name2range;
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i);) {
Instruction& instruction = instructions.get(i);
i = instructions.advance(i);
if (instruction.getFlags() & ifCopy) {
assert(instruction.getInstructionUseBegin() != instruction.getInstructionUseEnd() && instruction.getInstructionUseBegin()[0].isRegister());
assert(instruction.getInstructionDefineBegin() != instruction.getInstructionDefineEnd() && instruction.getInstructionDefineBegin()[0].isRegister());
RegisterName source = name2range[instruction.getInstructionUseBegin()[0].getRegisterName()];
RegisterName destination = name2range[instruction.getInstructionDefineBegin()[0].getRegisterName()];
if (source == destination)
instruction.remove();
}
}
}
}
void RegisterAllocatorTools::updateInstructionGraph(RegisterAllocator& registerAllocator)
{
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
RegisterName* name2range = registerAllocator.name2range;
for (Uint32 n = 0; n < nNodes; n++) {
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
usePtr->setRegisterName(name2range[usePtr->getRegisterName()]);
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
definePtr->setRegisterName(name2range[definePtr->getRegisterName()]);
}
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
Instruction& instruction = phiNodes.get(p);
InstructionUse* useEnd = instruction.getInstructionUseEnd();
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
usePtr->setRegisterName(name2range[usePtr->getRegisterName()]);
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
definePtr->setRegisterName(name2range[definePtr->getRegisterName()]);
}
}
}
void RegisterAllocatorTools::insertPhiNodeInstructions(ControlGraph& controlGraph, InstructionEmitter& emitter)
{
Pool& pool = controlGraph.pool;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
DoublyLinkedList<PhiNode>& phiNodes = node.getPhiNodes();
if (!phiNodes.empty()) {
// Set the index of the incoming edges.
Uint32 index = 0;
const DoublyLinkedList<ControlEdge>& predecessors = node.getPredecessors();
for (DoublyLinkedList<ControlEdge>::iterator p = predecessors.begin(); !predecessors.done(p); p = predecessors.advance(p))
predecessors.get(p).setIndex(index++);
// Insert the phi node instruction in the instruction list.
for (DoublyLinkedList<PhiNode>::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
PhiNode& phiNode = phiNodes.get(i);
ValueKind kind = phiNode.getKind();
if (!isStorableKind(kind))
continue;
RegisterClassKind classKind = rckGeneral; // FIX: get class kind from phi node kind.
Uint32 nInputs = phiNode.nInputs();
PhiNodeInstruction& phiNodeInstruction = *new(pool) PhiNodeInstruction(&phiNode, pool, nInputs);
emitter.defineProducer(phiNode, phiNodeInstruction, 0, classKind, drLow);
for (Uint32 whichInput = 0; whichInput < nInputs; whichInput++)
emitter.useProducer(phiNode.nthInputVariable(whichInput), phiNodeInstruction, whichInput, classKind, drLow);
node.addPhiNodeInstruction(phiNodeInstruction);
if (isDoublewordKind(kind)) {
PhiNodeInstruction& phiNodeInstruction = *new(pool) PhiNodeInstruction(&phiNode, pool, nInputs);
emitter.defineProducer(phiNode, phiNodeInstruction, 0, classKind, drHigh);
for (Uint32 whichInput = 0; whichInput < nInputs; whichInput++)
emitter.useProducer(phiNode.nthInputVariable(whichInput), phiNodeInstruction, whichInput, classKind, drHigh);
node.addPhiNodeInstruction(phiNodeInstruction);
}
}
}
}
}
#ifdef DEBUG_LOG
void RegisterAllocatorTools::printSpillCosts(RegisterAllocator& registerAllocator)
{
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
Uint32 rangeCount = registerAllocator.rangeCount;
SpillCost* cost = registerAllocator.spillCost;
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Spill costs:\n"));
for (Uint32 i = 1; i < rangeCount; i++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\trange %d : ", i));
if (cost[i].infinite)
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("infinite\n"));
else
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%f\n", cost[i].cost));
}
}
void RegisterAllocatorTools::printSplitCosts(RegisterAllocator& registerAllocator)
{
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
Uint32 rangeCount = registerAllocator.rangeCount;
SplitCost* cost = registerAllocator.splitCost;
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Split costs:\n"));
for (Uint32 i = 1; i < rangeCount; i++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\trange %d : loads = %f stores = %f\n", i, cost[i].loads, cost[i].stores));
}
}
void RegisterAllocatorTools::printInstructions(RegisterAllocator& registerAllocator)
{
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
ControlNode** nodes = registerAllocator.controlGraph.dfsList;
Uint32 nNodes = registerAllocator.controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("N%d:\n", n));
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
InstructionList& instructions = nodes[n]->getInstructions();
if (!phiNodes.empty()) {
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" PhiNodes:\n", n));
for(InstructionList::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
phiNodes.get(i).printPretty(log);
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
if (!instructions.empty())
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" Instructions:\n", n));
}
for(InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
instructions.get(i).printPretty(log);
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
}
}
}
#endif // DEBUG_LOG

View File

@@ -0,0 +1,117 @@
// -*- mode:C++; tab-width:4; truncate-lines:t -*-
//
// CONFIDENTIAL AND PROPRIETARY SOURCE CODE OF
// NETSCAPE COMMUNICATIONS CORPORATION
// Copyright © 1996, 1997 Netscape Communications Corporation. All Rights
// Reserved. Use of this Source Code is subject to the terms of the
// applicable license agreement from Netscape Communications Corporation.
// The copyright notice(s) in this Source Code does not indicate actual or
// intended publication of this Source Code.
//
// $Id: RegisterAllocatorTools.h,v 1.1.2.1 1999-03-02 16:12:05 fur%netscape.com Exp $
//
#ifndef _REGISTER_ALLOCATOR_TOOLS_H_
#define _REGISTER_ALLOCATOR_TOOLS_H_
#include "LogModule.h"
#include "RegisterTypes.h"
#include <string.h>
class RegisterAllocator;
class ControlGraph;
class InstructionEmitter;
class VirtualRegisterManager;
struct RegisterAllocatorTools
{
//
//
static void insertPhiNodeInstructions(ControlGraph& controlGraph, InstructionEmitter& emitter);
//
//
static void updateInstructionGraph(RegisterAllocator& registerAllocator);
//
//
static void removeUnnecessaryCopies(RegisterAllocator& registerAllocator);
#ifdef DEBUG
//
//
static void testTheInstructionGraph(ControlGraph& controlGraph, VirtualRegisterManager& vrManager);
#endif // DEBUG
#ifdef DEBUG_LOG
//
//
static void printInstructions(RegisterAllocator& registerAllocator);
//
//
static void printSpillCosts(RegisterAllocator& registerAllocator);
//
//
static void printSplitCosts(RegisterAllocator& registerAllocator);
#endif // DEBUG_LOG
};
//
// FIX: this should go in a class (LookupTable ?)
//
inline RegisterName findRoot(RegisterName name, RegisterName* table)
{
RegisterName* stack = table;
RegisterName* stackPtr = stack;
RegisterName newName;
while((newName = table[name]) != name) {
*--stackPtr = name;
name = newName;
}
while (stackPtr != stack)
table[*stackPtr++] = name;
return name;
}
inline void init(RegisterName* table, Uint32 nameCount)
{
for (RegisterName r = RegisterName(0); r < nameCount; r = RegisterName(r + 1))
table[r] = r;
}
inline Uint32 compress(RegisterName* name2range, RegisterName* table, Uint32 nameCount, Uint32 tableSize)
{
RegisterName* liveRange = new RegisterName[tableSize];
memset(liveRange, '\0', tableSize * sizeof(RegisterName));
// Update the lookup table.
for (RegisterName r = RegisterName(1); r < tableSize; r = RegisterName(r + 1))
findRoot(r, table);
// Count the liveranges.
Uint32 liveRangeCount = 1;
for (RegisterName s = RegisterName(1); s < tableSize; s = RegisterName(s + 1))
if (table[s] == s)
liveRange[s] = RegisterName(liveRangeCount++);
for (RegisterName t = RegisterName(1); t < nameCount; t = RegisterName(t + 1))
name2range[t] = liveRange[table[name2range[t]]];
return liveRangeCount;
}
inline double doLog10(Uint32 power)
{
double log = 1.0;
while (power--)
log *= 10.0;
return log;
}
#endif // _REGISTER_ALLOCATOR_TOOLS_H_

View File

@@ -0,0 +1,38 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_ASSIGNER_H_
#define _REGISTER_ASSIGNER_H_
#include "Fundamentals.h"
#include "VirtualRegister.h"
class FastBitMatrix;
class RegisterAssigner
{
protected:
VirtualRegisterManager& vRegManager;
public:
RegisterAssigner(VirtualRegisterManager& vrMan) : vRegManager(vrMan) {}
virtual bool assignRegisters(FastBitMatrix& interferenceMatrix) = 0;
};
#endif /* _REGISTER_ASSIGNER_H_ */

View File

@@ -0,0 +1,25 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_CLASS_H_
#define _REGISTER_CLASS_H_
#include "Fundamentals.h"
#include "RegisterTypes.h"
#endif // _REGISTER_CLASS_H_

View File

@@ -0,0 +1,37 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_PRESSURE_H_
#define _REGISTER_PRESSURE_H_
#include "BitSet.h"
#include "HashSet.h"
struct LowRegisterPressure
{
typedef BitSet Set;
static const bool setIsOrdered = true;
};
struct HighRegisterPressure
{
typedef HashSet Set;
static const bool setIsOrdered = false;
};
#endif // _REGISTER_PRESSURE_H_

View File

@@ -0,0 +1,104 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _REGISTER_TYPES_H_
#define _REGISTER_TYPES_H_
#include "Fundamentals.h"
//------------------------------------------------------------------------------
// RegisterName -
//
enum RegisterName {
rnInvalid = 0,
};
//------------------------------------------------------------------------------
// RegisterClassKind -
//
enum RegisterClassKind {
rckInvalid = 0,
rckGeneral,
rckStackSlot,
nRegisterClassKind
};
//------------------------------------------------------------------------------
// RegisterID -
//
enum RegisterID {
invalidID = 0
};
//------------------------------------------------------------------------------
// RegisterKind -
//
enum RegisterKind {
rkCallerSave = 0,
rkCalleeSave,
};
struct NameLinkedList {
RegisterName name;
NameLinkedList* next;
};
#ifdef DEBUG
const registerNameMask = 0x03ffffff;
const coloredRegisterMask = 0x04000000;
const machineRegisterMask = 0x08000000;
const registerClassMask = 0xf0000000;
const registerNameShift = 0;
const coloredRegisterShift = 26;
const machineRegisterShift = 27;
const registerClassShift = 28;
#else // DEBUG
const registerNameMask = 0x0fffffff;
const registerClassMask = 0xf0000000;
const registerNameShift = 0;
const registerClassShift = 28;
#endif // DEBUG
inline RegisterClassKind getClass(RegisterID registerID) {return RegisterClassKind((registerID & registerClassMask) >> registerClassShift);}
inline RegisterName getName(RegisterID registerID) {return RegisterName((registerID & registerNameMask) >> registerNameShift);}
inline void setClass(RegisterID& registerID, RegisterClassKind classKind) {registerID = RegisterID((registerID & ~registerClassMask) | ((classKind << registerClassShift) & registerClassMask));}
inline void setName(RegisterID& registerID, RegisterName name) {assert((name & ~registerNameMask) == 0); registerID = RegisterID((registerID & ~registerNameMask) | ((name << registerNameShift) & registerNameMask));}
inline RegisterID buildRegisterID(RegisterName name, RegisterClassKind classKind) {return RegisterID(((classKind << registerClassShift) & registerClassMask) | ((name << registerNameShift) & registerNameMask));}
#ifdef DEBUG
inline bool isMachineRegister(RegisterID rid) {return (rid & machineRegisterMask) != 0;}
inline void setMachineRegister(RegisterID& rid) {rid = RegisterID(rid | machineRegisterMask);}
inline bool isColoredRegister(RegisterID rid) {return (rid & coloredRegisterMask) != 0;}
inline void setColoredRegister(RegisterID& rid) {rid = RegisterID(rid | coloredRegisterMask);}
#endif // DEBUG
#endif // _REGISTER_TYPES_H_

View File

@@ -0,0 +1,32 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "SSATools.h"
#include "ControlGraph.h"
#include "VirtualRegister.h"
#include "Liveness.h"
void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager)
{
if (!controlGraph.hasBackEdges)
return;
Liveness liveness(controlGraph.pool);
liveness.buildLivenessAnalysis(controlGraph, vrManager);
}

View File

@@ -0,0 +1,29 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _SSA_TOOLS_H_
#define _SSA_TOOLS_H_
#include "Fundamentals.h"
class ControlGraph;
class VirtualRegisterManager;
extern void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager);
#endif // _SSA_TOOLS_H_

View File

@@ -0,0 +1,37 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "SparseSet.h"
#include "BitSet.h"
#include "Pool.h"
#ifdef DEBUG_LOG
// Print the set.
//
void SparseSet::printPretty(LogModuleObject log)
{
Pool pool;
BitSet set(pool, universeSize);
for (Uint32 i = 0; i < count; i++)
set.set(node[i].element);
set.printPretty(log);
}
#endif // DEBUG_LOG

View File

@@ -0,0 +1,168 @@
// -*- mode:C++; tab-width:4; truncate-lines:t -*-
//
// CONFIDENTIAL AND PROPRIETARY SOURCE CODE OF
// NETSCAPE COMMUNICATIONS CORPORATION
// Copyright © 1996, 1997 Netscape Communications Corporation. All Rights
// Reserved. Use of this Source Code is subject to the terms of the
// applicable license agreement from Netscape Communications Corporation.
// The copyright notice(s) in this Source Code does not indicate actual or
// intended publication of this Source Code.
//
// $Id: SparseSet.h,v 1.1.2.1 1999-03-02 16:12:07 fur%netscape.com Exp $
//
#ifndef _SPARSE_SET_H_
#define _SPARSE_SET_H_
#include "Fundamentals.h"
#include "Pool.h"
#include "LogModule.h"
#include "BitSet.h"
class SparseSet
{
private:
struct Node {
Uint32 element;
Uint32 stackIndex;
};
Node* node;
Uint32 count;
Uint32 universeSize;
private:
// No copy constructor.
SparseSet(const SparseSet&);
// Check if the given set's universe is of the same size than this universe.
void checkUniverseCompatibility(const SparseSet& set) const {assert(set.universeSize == universeSize);}
// Check if pos is valid for this set's universe.
void checkMember(Int32 pos) const {assert(pos >=0 && Uint32(pos) < universeSize);}
public:
SparseSet(Pool& pool, Uint32 universeSize) : universeSize(universeSize) {node = new(pool) Node[universeSize]; clear();}
// Clear the sparse set.
void clear() {count = 0;}
// Clear the element at index.
inline void clear(Uint32 index);
// Set the element at index.
inline void set(Uint32 index);
// Return true if the element at index is set.
inline bool test(Uint32 index) const;
// Union with the given sparse set.
inline void or(const SparseSet& set);
// Intersection with the given sparse set.
inline void and(const SparseSet& set);
// Difference with the given sparse set.
inline void difference(const SparseSet& set);
// Copy set.
inline SparseSet& operator = (const SparseSet& set);
inline SparseSet& operator = (const BitSet& set);
// Return true if the sparse sets are identical.
friend bool operator == (const SparseSet& set1, const SparseSet& set2);
// Return true if the sparse sets are different.
friend bool operator != (const SparseSet& set1, const SparseSet& set2);
// Logical operators.
SparseSet& operator |= (const SparseSet& set) {or(set); return *this;}
SparseSet& operator &= (const SparseSet& set) {and(set); return *this;}
SparseSet& operator -= (const SparseSet& set) {difference(set); return *this;}
// Iterator to conform with the set API.
typedef Int32 iterator;
// Return the iterator for the first element of this set.
iterator begin() const {return count - 1;}
// Return the next iterator.
iterator advance(iterator pos) const {return --pos;}
// Return true if the iterator is at the end of the set.
bool done(iterator pos) const {return pos < 0;}
// Return the element for the given iterator;
Uint32 get(iterator pos) const {return node[pos].element;}
// Return one element of this set.
Uint32 getOne() const {assert(count > 0); return node[0].element;}
// Return the size of this set.
Uint32 getSize() const {return count;}
#ifdef DEBUG_LOG
// Print the set.
void printPretty(LogModuleObject log);
#endif // DEBUG_LOG
};
inline void SparseSet::clear(Uint32 element)
{
checkMember(element);
Uint32 count = this->count;
Node* node = this->node;
Uint32 stackIndex = node[element].stackIndex;
if ((stackIndex < count) && (node[stackIndex].element == element)) {
Uint32 stackTop = node[count - 1].element;
node[stackIndex].element = stackTop;
node[stackTop].stackIndex = stackIndex;
this->count = count - 1;
}
}
inline void SparseSet::set(Uint32 element)
{
checkMember(element);
Uint32 count = this->count;
Node* node = this->node;
Uint32 stackIndex = node[element].stackIndex;
if ((stackIndex >= count) || (node[stackIndex].element != element)) {
node[count].element = element;
node[element].stackIndex = count;
this->count = count + 1;
}
}
inline bool SparseSet::test(Uint32 element) const
{
checkMember(element);
Node* node = this->node;
Uint32 stackIndex = node[element].stackIndex;
return ((stackIndex < count) && (node[stackIndex].element == element));
}
inline SparseSet& SparseSet::operator = (const SparseSet& set)
{
checkUniverseCompatibility(set);
Uint32 sourceCount = set.getSize();
Node* node = this->node;
memcpy(node, set.node, sourceCount * sizeof(Node));
for (Uint32 i = 0; i < sourceCount; i++) {
Uint32 element = node[i].element;
node[element].stackIndex = i;
}
count = sourceCount;
return *this;
}
inline SparseSet& SparseSet::operator = (const BitSet& set)
{
// FIX: there's room for optimization here.
assert(universeSize == set.getSize());
clear();
for (Int32 i = set.firstOne(); i != -1; i = set.nextOne(i))
this->set(i);
return *this;
}
#endif // _SPARSE_SET_H_

View File

@@ -0,0 +1,270 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef NEW_LAURENTM_CODE
#define INCLUDE_EMITTER
#include "CpuInfo.h"
#include "Fundamentals.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "InstructionEmitter.h"
#include "Spilling.h"
void Spilling::
insertSpillCode(ControlNode** dfsList, Uint32 nNodes)
{
PRUint32 nVirtualRegisters = vRegManager.count();
FastBitSet currentLive(vRegManager.pool, nVirtualRegisters);
FastBitSet usedInThisInstruction(vRegManager.pool, nVirtualRegisters);
RegisterFifo grNeedLoad(nVirtualRegisters);
RegisterFifo fpNeedLoad(nVirtualRegisters);
for (PRInt32 n = nNodes - 1; n >= 0; n--)
{
PR_ASSERT(grNeedLoad.empty() & fpNeedLoad.empty());
ControlNode& node = *dfsList[n];
currentLive = node.liveAtEnd;
PRUint32 nGeneralAlive = 0;
PRUint32 nFloatingPointAlive = 0;
// Get the number of registers alive at the end of this node.
for (PRInt32 j = currentLive.firstOne(); j != -1; j = currentLive.nextOne(j))
{
VirtualRegister& vReg = vRegManager.getVirtualRegister(j);
if (vReg.spillInfo.willSpill)
{
currentLive.clear(j);
}
else
{
switch (vReg.getClass())
{
case vrcInteger:
nGeneralAlive++;
break;
case vrcFloatingPoint:
case vrcFixedPoint:
nFloatingPointAlive++;
break;
default:
break;
}
}
}
// if(node.dfsNum == 8) printf("\n________Begin Node %d________\n", node.dfsNum);
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i))
{
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defEnd = instruction.getInstructionDefineEnd();
InstructionDefine* defPtr;
// if(node.dfsNum == 8) { printf("\n");
// instruction.printPretty(stdout);
// printf("\n"); }
// Handle definitions
for (defPtr = defBegin; defPtr < defEnd; defPtr++)
if (defPtr->isVirtualRegister())
{
VirtualRegister& vReg = defPtr->getVirtualRegister();
currentLive.clear(vReg.getRegisterIndex());
switch (vReg.getClass())
{
case vrcInteger:
nGeneralAlive--;
break;
case vrcFloatingPoint:
case vrcFixedPoint:
nFloatingPointAlive--;
break;
default:
break;
}
}
// Check for deaths
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isVirtualRegister())
{
VirtualRegister& vReg = usePtr->getVirtualRegister();
if (!currentLive.test(vReg.getRegisterIndex()))
// This is the last use of this register.
{
currentLive.set(vReg.getRegisterIndex());
switch (vReg.getClass())
{
case vrcInteger:
nGeneralAlive++;
while (/*(nGeneralAlive > NUMBER_OF_GREGISTERS) &&*/ !grNeedLoad.empty())
{
PRUint32 toLoad = grNeedLoad.get();
currentLive.clear(toLoad);
nGeneralAlive--;
VirtualRegister& nReg = vRegManager.getVirtualRegister(toLoad);
Instruction& lastUsingInstruction = *nReg.spillInfo.lastUsingInstruction;
emitter.emitLoadAfter(*lastUsingInstruction.getPrimitive(), lastUsingInstruction.getLinks().prev,
nReg.getAlias(), *nReg.equivalentRegister[vrcStackSlot]);
nReg.releaseSelf();
}
break;
case vrcFloatingPoint:
case vrcFixedPoint:
nFloatingPointAlive++;
while (/*(nFloatingPointAlive > NUMBER_OF_FPREGISTERS) &&*/ !fpNeedLoad.empty())
{
PRUint32 toLoad = fpNeedLoad.get();
currentLive.clear(toLoad);
nFloatingPointAlive--;
VirtualRegister& nReg = vRegManager.getVirtualRegister(toLoad);
Instruction& lastUsingInstruction = *nReg.spillInfo.lastUsingInstruction;
emitter.emitLoadAfter(*lastUsingInstruction.getPrimitive(), lastUsingInstruction.getLinks().prev,
nReg.getAlias(), *nReg.equivalentRegister[vrcStackSlot]);
nReg.releaseSelf();
}
break;
default:
break;
}
}
}
// Handle uses
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isVirtualRegister())
{
VirtualRegister& vReg = usePtr->getVirtualRegister();
PRUint32 registerIndex = vReg.getRegisterIndex();
if (vReg.spillInfo.willSpill) {
#if defined(GENERATE_FOR_X86)
if (!instruction.switchUseToSpill((usePtr - useBegin), *vReg.equivalentRegister[vrcStackSlot]))
#endif
{
switch (vReg.getClass())
{
case vrcInteger:
if (!grNeedLoad.test(registerIndex))
{
grNeedLoad.put(registerIndex);
VirtualRegister& alias = vRegManager.newVirtualRegister(vrcInteger);
if (vReg.isPreColored())
alias.preColorRegister(vReg.getPreColor());
/* if (vReg.hasSpecialInterference) {
alias.specialInterference.sizeTo(NUMBER_OF_REGISTERS);
alias.specialInterference = vReg.specialInterference;
alias.hasSpecialInterference = true;
} */
vReg.setAlias(alias);
vReg.retainSelf();
}
break;
case vrcFloatingPoint:
case vrcFixedPoint:
if (!fpNeedLoad.test(registerIndex))
{
fpNeedLoad.put(registerIndex);
VirtualRegister& alias = vRegManager.newVirtualRegister(vReg.getClass());
if (vReg.isPreColored())
alias.preColorRegister(vReg.getPreColor());
/*if (vReg.hasSpecialInterference) {
alias.specialInterference.sizeTo(NUMBER_OF_REGISTERS);
alias.specialInterference = vReg.specialInterference;
alias.hasSpecialInterference = true;
} */
vReg.setAlias(alias);
vReg.retainSelf();
}
break;
default:
break;
}
usePtr->getVirtualRegisterPtr().initialize(vReg.getAlias());
usedInThisInstruction.set(registerIndex);
vReg.spillInfo.lastUsingInstruction = &instruction;
}
currentLive.clear(registerIndex);
} else { // will not spill
currentLive.set(registerIndex);
}
}
// Handle definitions
for (defPtr = defBegin; defPtr < defEnd; defPtr++)
if (defPtr->isVirtualRegister())
{
VirtualRegister& vReg = defPtr->getVirtualRegister();
if (vReg.spillInfo.willSpill)
#if defined(GENERATE_FOR_X86)
if (!instruction.switchDefineToSpill((defPtr - defBegin), *vReg.equivalentRegister[vrcStackSlot]))
#endif
{
if (usedInThisInstruction.test(vReg.getRegisterIndex()))
// this virtualRegister was used in this instruction and is also defined. We need to move
// this virtual register to its alias first and then save it to memory.
{
emitter.emitStoreAfter(*instruction.getPrimitive(), &instruction.getLinks(),
vReg.getAlias(), *vReg.equivalentRegister[vrcStackSlot]);
defPtr->getVirtualRegisterPtr().initialize(vReg.getAlias());
}
else
{
emitter.emitStoreAfter(*instruction.getPrimitive(), &instruction.getLinks(),
vReg, *vReg.equivalentRegister[vrcStackSlot]);
}
}
}
}
while (!grNeedLoad.empty())
{
PRUint32 nl = grNeedLoad.get();
VirtualRegister& nlReg = vRegManager.getVirtualRegister(nl);
Instruction& lastUse = *nlReg.spillInfo.lastUsingInstruction;
emitter.emitLoadAfter(*lastUse.getPrimitive(), lastUse.getLinks().prev,
nlReg.getAlias(), *nlReg.equivalentRegister[vrcStackSlot]);
nlReg.releaseSelf();
}
while (!fpNeedLoad.empty())
{
PRUint32 nl = fpNeedLoad.get();
VirtualRegister& nlReg = vRegManager.getVirtualRegister(nl);
Instruction& lastUse = *nlReg.spillInfo.lastUsingInstruction;
emitter.emitLoadAfter(*lastUse.getPrimitive(), lastUse.getLinks().prev,
nlReg.getAlias(), *nlReg.equivalentRegister[vrcStackSlot]);
nlReg.releaseSelf();
}
// if(node.dfsNum == 8) printf("\n________End Node %d________\n", node.dfsNum);
}
}
#endif

View File

@@ -0,0 +1,269 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _SPILLING_H_
#define _SPILLING_H_
#include "Fundamentals.h"
#include <string.h>
#include "RegisterAllocator.h"
#include "RegisterAllocatorTools.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "SparseSet.h"
template <class RegisterPressure>
class Spilling
{
private:
static void insertStoreAfter(Instruction& instruction, RegisterName name);
static void insertLoadBefore(Instruction& instruction, RegisterName name);
public:
static void calculateSpillCosts(RegisterAllocator& registerAllocator);
static void insertSpillCode(RegisterAllocator& registerAllocator);
};
struct SpillCost
{
double loads;
double stores;
double copies;
double cost;
bool infinite;
};
template <class RegisterPressure>
void Spilling<RegisterPressure>::insertSpillCode(RegisterAllocator& registerAllocator)
{
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* name2range = registerAllocator.name2range;
Pool& pool = registerAllocator.pool;
SparseSet currentLive(pool, rangeCount);
SparseSet needLoad(pool, rangeCount);
SparseSet mustSpill(pool, rangeCount);
SparseSet& willSpill = *registerAllocator.willSpill;
ControlGraph& controlGraph = registerAllocator.controlGraph;
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
needLoad.clear();
currentLive = liveOut[n];
mustSpill = currentLive;
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i);) {
Instruction& instruction = instructions.get(i);
i = instructions.retreat(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
bool foundLiveDefine = false;
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
if (currentLive.test(name2range[definePtr->getRegisterName()])) {
foundLiveDefine = true;
break;
}
} else {
foundLiveDefine = true;
break;
}
if (defineBegin != defineEnd && !foundLiveDefine) {
fprintf(stderr, "!!! Removed instruction because it was only defining unused registers !!!\n");
instruction.remove();
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName range = name2range[definePtr->getRegisterName()];
#ifdef DEBUG
if (needLoad.test(range))
if (!mustSpill.test(range) && registerAllocator.spillCost[range].infinite && willSpill.test(range)) {
fprintf(stderr, "Tried to spill a register with infinite spill cost\n");
abort();
}
#endif // DEBUG
if (willSpill.test(range))
insertStoreAfter(instruction, range);
needLoad.clear(range);
}
if (instruction.getFlags() & ifCopy)
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName range = name2range[usePtr->getRegisterName()];
if (!currentLive.test(range))
for (SparseSet::iterator r = needLoad.begin(); !needLoad.done(r); r = needLoad.advance(r)) {
RegisterName load = RegisterName(needLoad.get(r));
if (willSpill.test(load))
insertLoadBefore(instruction, load);
mustSpill.set(load);
}
needLoad.clear();
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
currentLive.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName range = name2range[usePtr->getRegisterName()];
currentLive.set(range);
needLoad.set(range);
}
}
for (SparseSet::iterator l = needLoad.begin(); !needLoad.done(l); l = needLoad.advance(l)) {
RegisterName load = RegisterName(needLoad.get(l));
if (willSpill.test(load))
insertLoadBefore(instructions.first(), load);
}
}
}
template <class RegisterPressure>
void Spilling<RegisterPressure>::insertLoadBefore(Instruction& /*instruction*/, RegisterName name)
{
fprintf(stdout, "will insert load for range %d\n", name);
}
template <class RegisterPressure>
void Spilling<RegisterPressure>::insertStoreAfter(Instruction& /*instruction*/, RegisterName name)
{
fprintf(stdout, "will insert store for range %d\n", name);
}
template <class RegisterPressure>
void Spilling<RegisterPressure>::calculateSpillCosts(RegisterAllocator& registerAllocator)
{
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* name2range = registerAllocator.name2range;
Pool& pool = registerAllocator.pool;
SparseSet live(pool, rangeCount);
SparseSet needLoad(pool, rangeCount);
SparseSet mustSpill(pool, rangeCount);
SparseSet alreadyStored(pool, rangeCount); // FIX: should get this from previous spilling.
SpillCost* cost = new SpillCost[rangeCount];
memset(cost, '\0', rangeCount * sizeof(SpillCost));
ControlGraph& controlGraph = registerAllocator.controlGraph;
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
double weight = doLog10(node.loopDepth);
needLoad.clear();
live = liveOut[n];
mustSpill = live;
InstructionList& instructions = nodes[n]->getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister()) {
RegisterName range = name2range[definePtr->getRegisterName()];
if (needLoad.test(range))
if (!mustSpill.test(range))
cost[range].infinite = true;
if ((false /* !rematerializable(range) */ || !needLoad.test(range)) && !alreadyStored.test(range))
cost[range].stores += weight;
needLoad.clear(range);
}
if (instruction.getFlags() & ifCopy)
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
if (!live.test(name2range[usePtr->getRegisterName()])) {
for (SparseSet::iterator l = needLoad.begin(); !needLoad.done(l); l = needLoad.advance(l)) {
Uint32 range = needLoad.get(l);
cost[range].loads += weight;
mustSpill.set(range);
}
needLoad.clear();
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
live.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName range = name2range[usePtr->getRegisterName()];
live.set(range);
needLoad.set(range);
}
if (instruction.getFlags() & ifCopy) {
assert(useBegin != useEnd && useBegin[0].isRegister());
assert(defineBegin != defineEnd && defineBegin[0].isRegister());
RegisterName source = name2range[useBegin[0].getRegisterName()];
RegisterName destination = name2range[defineBegin[0].getRegisterName()];
cost[source].copies += weight;
cost[destination].copies += weight;
}
}
for (SparseSet::iterator s = needLoad.begin(); !needLoad.done(s); s = needLoad.advance(s))
cost[needLoad.get(s)].loads += weight;
}
for (Uint32 r = 0; r < rangeCount; r++) {
SpillCost& c = cost[r];
c.cost = 2 * (c.loads + c.stores) - c.copies;
}
registerAllocator.spillCost = cost;
}
#endif // _SPILLING_H_

View File

@@ -0,0 +1,239 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _SPLITS_H_
#define _SPLITS_H_
#include "Fundamentals.h"
#include <string.h>
#include "Pool.h"
#include "ControlGraph.h"
#include "ControlNodes.h"
#include "Instruction.h"
#include "RegisterAllocator.h"
#include "RegisterAllocatorTools.h"
UT_EXTERN_LOG_MODULE(RegAlloc);
template <class RegisterPressure>
struct Splits
{
static void calculateSplitCosts(RegisterAllocator& registerAllocator);
static bool findSplit(RegisterAllocator& registerAllocator, RegisterName* color, RegisterName range);
static void insertSplitCode(RegisterAllocator& registerAllocator);
};
struct SplitCost
{
double loads;
double stores;
};
template <class RegisterPressure>
void Splits<RegisterPressure>::insertSplitCode(RegisterAllocator& /*registerAllocator*/)
{
// FIX
}
template <class RegisterPressure>
bool Splits<RegisterPressure>::findSplit(RegisterAllocator& registerAllocator, RegisterName* color, RegisterName range)
{
Pool& pool = registerAllocator.pool;
NameLinkedList** neighborsWithColor = new(pool) NameLinkedList*[6]; // FIX
memset(neighborsWithColor, '\0', 6 * sizeof(NameLinkedList*));
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
for (Int32 i = vector->count - 1; i >=0; --i) {
RegisterName neighbor = vector->neighbors[i];
RegisterName c = color[neighbor];
if (c < 6) { // FIX
NameLinkedList* node = new(pool) NameLinkedList();
node->name = neighbor;
node->next = neighborsWithColor[c];
neighborsWithColor[c] = node;
}
}
bool splitAroundName = true;
LiveRangeGraph<RegisterPressure>& lGraph = registerAllocator.lGraph;
RegisterName bestColor = RegisterName(6); // FIX
double bestCost = registerAllocator.spillCost[range].cost;
SplitCost* splitCost = registerAllocator.splitCost;
for (RegisterName i = RegisterName(0); i < 6; i = RegisterName(i + 1)) { // FIX
double splitAroundNameCost = 0.0;
bool canSplitAroundName = true;
SplitCost& sCost = splitCost[range];
double addedCost = 2.0 * (sCost.stores + sCost.loads);
for (NameLinkedList* node = neighborsWithColor[i]; node != NULL; node = node->next) {
RegisterName neighbor = node->name;
if (lGraph.haveEdge(neighbor, range)) {
canSplitAroundName = false;
break;
} else
splitAroundNameCost += addedCost;
}
if (canSplitAroundName && splitAroundNameCost < bestCost) {
bestCost = splitAroundNameCost;
bestColor = i;
splitAroundName = true;
}
double splitAroundColorCost = 0.0;
bool canSplitAroundColor = true;
for (NameLinkedList* node = neighborsWithColor[i]; node != NULL; node = node->next) {
RegisterName neighbor = node->name;
if (lGraph.haveEdge(range, neighbor)) {
canSplitAroundColor = false;
break;
} else {
SplitCost& sCost = splitCost[neighbor];
double addedCost = 2.0 * (sCost.stores + sCost.loads);
splitAroundColorCost += addedCost;
}
}
if (canSplitAroundColor && splitAroundColorCost < bestCost) {
bestCost = splitAroundColorCost;
bestColor = i;
splitAroundName = false;
}
}
if (bestColor < RegisterName(6)) {
color[range] = bestColor;
registerAllocator.splitFound = true;
NameLinkedList** splitAround = registerAllocator.splitAround;
if (splitAroundName)
for (NameLinkedList* node = neighborsWithColor[bestColor]; node != NULL; node = node->next) {
NameLinkedList* newNode = new(pool) NameLinkedList();
newNode->name = node->name;
newNode->next = splitAround[range];
splitAround[range] = newNode;
}
else
for (NameLinkedList* node = neighborsWithColor[bestColor]; node != NULL; node = node->next) {
NameLinkedList* newNode = new(pool) NameLinkedList();
RegisterName neighbor = node->name;
newNode->name = range;
newNode->next = splitAround[neighbor];
splitAround[neighbor] = newNode;
}
trespass("Found a split");
return true;
}
return false;
}
template <class RegisterPressure>
void Splits<RegisterPressure>::calculateSplitCosts(RegisterAllocator& registerAllocator)
{
Pool& pool = registerAllocator.pool;
Uint32 rangeCount = registerAllocator.rangeCount;
RegisterName* name2range = registerAllocator.name2range;
SplitCost* splitCost = new(pool) SplitCost[rangeCount];
memset(splitCost, '\0', rangeCount * sizeof(SplitCost));
SparseSet live(pool, rangeCount);
RegisterPressure::Set* liveIn = registerAllocator.liveness.liveIn;
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
ControlGraph& controlGraph = registerAllocator.controlGraph;
ControlNode** nodes = controlGraph.dfsList;
Uint32 nNodes = controlGraph.nNodes;
for (Uint32 n = 0; n < nNodes; n++) {
ControlNode& node = *nodes[n];
double weight = doLog10(node.loopDepth);
live = liveOut[n];
ControlEdge* successorsEnd = node.getSuccessorsEnd();
for (ControlEdge* successorsPtr = node.getSuccessorsBegin(); successorsPtr < successorsEnd; successorsPtr++) {
ControlNode& successor = successorsPtr->getTarget();
if (successor.getControlKind() != ckEnd) {
RegisterPressure::Set& successorLiveIn = liveIn[successor.dfsNum];
for (SparseSet::iterator i = live.begin(); !live.done(i); i = live.advance(i)) {
RegisterName name = RegisterName(live.get(i));
if (!successorLiveIn.test(name))
splitCost[name].loads += doLog10(successor.loopDepth);
}
}
}
InstructionList& instructions = node.getInstructions();
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
Instruction& instruction = instructions.get(i);
InstructionUse* useBegin = instruction.getInstructionUseBegin();
InstructionUse* useEnd = instruction.getInstructionUseEnd();
InstructionUse* usePtr;
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
InstructionDefine* definePtr;
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
splitCost[name2range[definePtr->getRegisterName()]].stores += weight;
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister()) {
RegisterName range = name2range[usePtr->getRegisterName()];
if (!live.test(range)) {
if (&instruction != &instructions.last())
splitCost[range].loads += weight;
else {
ControlEdge* successorsEnd = node.getSuccessorsEnd();
for (ControlEdge* successorsPtr = node.getSuccessorsBegin(); successorsPtr < successorsEnd; successorsPtr++)
splitCost[range].loads += doLog10(successorsPtr->getTarget().loopDepth);
}
}
}
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
if (definePtr->isRegister())
live.clear(name2range[definePtr->getRegisterName()]);
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
if (usePtr->isRegister())
live.set(name2range[usePtr->getRegisterName()]);
}
}
NameLinkedList** splitAround = new(pool) NameLinkedList*[rangeCount];
memset(splitAround, '\0', rangeCount * sizeof(NameLinkedList*));
registerAllocator.splitAround = splitAround;
registerAllocator.splitCost = splitCost;
registerAllocator.splitFound = false;
}
#endif // _SPLITS_H_

View File

@@ -0,0 +1,186 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "HashTable.h"
#include "Timer.h"
#include "Pool.h"
static Pool pool; // Pool for the Timer class.
static HashTable<TimerEntry*> timerEntries(pool); // Timers hashtable.
const nTimersInABlock = 128; // Number of timers in a block.
static PRTime *timers = new(pool) PRTime[nTimersInABlock]; // A block of timers.
static Uint8 nextTimer = 0; // nextAvailableTimer.
//
// Calibrate the call to PR_Now().
//
static PRTime calibrate()
{
PRTime t = PR_Now();
PRTime& a = *new(pool) PRTime();
// Call 10 times the PR_Now() function.
a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now();
a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now();
t = (PR_Now() - t + 9) / 10;
return t;
}
static PRTime adjust = calibrate();
//
// Return the named timer..
//
TimerEntry& Timer::getTimerEntry(const char* name)
{
if (!timerEntries.exists(name)) {
TimerEntry* newEntry = new(pool) TimerEntry();
newEntry->accumulator = 0;
newEntry->running = false;
timerEntries.add(name, newEntry);
}
return *timerEntries[name];
}
//
// Return a reference to a new timer.
//
PRTime& Timer::getNewTimer()
{
if (nextTimer >= nTimersInABlock) {
timers = new(pool) PRTime[nTimersInABlock];
nextTimer = 0;
}
return timers[nextTimer++];
}
static Uint32 timersAreFrozen = 0;
//
// Start the named timer.
//
void Timer::start(const char* name)
{
if (timersAreFrozen)
return;
freezeTimers();
TimerEntry& timer = getTimerEntry(name);
PR_ASSERT(!timer.running);
timer.accumulator = 0;
timer.running = true;
timer.done = false;
unfreezeTimers();
}
//
// Stop the named timer.
//
void Timer::stop(const char* name)
{
if (timersAreFrozen)
return;
freezeTimers();
TimerEntry& timer = getTimerEntry(name);
PR_ASSERT(timer.running);
timer.running = false;
timer.done = true;
unfreezeTimers();
}
//
// Freeze all the running timers.
//
void Timer::freezeTimers()
{
PRTime when = PR_Now() - adjust;
if (timersAreFrozen == 0) {
Vector<TimerEntry*> entries = timerEntries;
Uint32 count = entries.size();
for (Uint32 i = 0; i < count; i++) {
TimerEntry& entry = *entries[i];
if (entry.running) {
entry.accumulator += (when - *entry.startTime);
}
}
}
timersAreFrozen++;
}
//
// Unfreeze all the running timers.
//
void Timer::unfreezeTimers()
{
PR_ASSERT(timersAreFrozen != 0);
timersAreFrozen--;
if (timersAreFrozen == 0) {
Vector<TimerEntry *> entries = timerEntries;
Uint32 count = entries.size();
PRTime& newStart = getNewTimer();
for (Uint32 i = 0; i < count; i++) {
TimerEntry& entry = *entries[i];
if (entry.running) {
entry.startTime = &newStart;
}
}
newStart = PR_Now();
}
}
//
// Print the named timer in the file f.
//
void Timer::print(FILE* f, const char *name)
{
if (timersAreFrozen)
return;
freezeTimers();
TimerEntry& timer = getTimerEntry(name);
PR_ASSERT(timer.done);
PRTime elapsed = timer.accumulator;
if (elapsed >> 32) {
fprintf(f, "[timer %s out of range]\n", name);
} else {
fprintf(f, "[%dus in %s]\n", Uint32(elapsed), name);
}
fflush(f);
unfreezeTimers();
}

View File

@@ -0,0 +1,80 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _TIMER_H_
#define _TIMER_H_
#include "Fundamentals.h"
#include "HashTable.h"
#include "prtime.h"
//
// Naming convention:
// As the class Timer contains only static methods, the timer's name should start with the
// module name. Otherwise starting 2 timers with the same name will assert.
//
#ifndef NO_TIMER
struct TimerEntry
{
PRTime *startTime; // Current time when we start the timer.
PRTime accumulator; // Time spent in this timer.
bool running; // True if the timer is running.
bool done; // True if the timer was running and was stopped.
};
class Timer
{
private:
// Return the named timer.
static TimerEntry& getTimerEntry(const char* name);
// Return a reference to a new Timer.
static PRTime& getNewTimer();
public:
// Start the timer.
static void start(const char* name);
// Stop the timer.
static void stop(const char* name);
// Freeze all the running timers.
static void freezeTimers();
// Unfreeze all the running timers.
static void unfreezeTimers();
// Print the timer.
static void print(FILE* f, const char *name);
};
inline void startTimer(const char* name) {Timer::start(name);}
inline void stopTimer(const char* name) {Timer::stop(name); Timer::print(stdout, name);}
#define START_TIMER_SAFE Timer::freezeTimers();
#define END_TIMER_SAFE Timer::unfreezeTimers();
#define TIMER_SAFE(x) START_TIMER_SAFE x; END_TIMER_SAFE
#else /* NO_TIMER */
inline void startTimer(const char* /*name*/) {}
inline void stopTimer(const char* /*name*/) {}
#define START_TIMER_SAFE
#define END_TIMER_SAFE
#define TIMER_SAFE(x) x;
#endif /* NO_TIMER */
#endif /* _TIMER_H_ */

View File

@@ -0,0 +1,40 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#include "Fundamentals.h"
#include "VirtualRegister.h"
#include "Instruction.h"
//------------------------------------------------------------------------------
// VirtualRegister -
#ifdef MANUAL_TEMPLATES
template class IndexedPool<VirtualRegister>;
#endif
// Set the defining instruction.
//
void VirtualRegister::setDefiningInstruction(Instruction& instruction)
{
if (definingInstruction != NULL) {
if ((instruction.getFlags() & ifCopy) && (definingInstruction->getFlags() & ifPhiNode))
return;
}
definingInstruction = &instruction;
}

View File

@@ -0,0 +1,116 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
* Reserved.
*/
#ifndef _VIRTUAL_REGISTER_H_
#define _VIRTUAL_REGISTER_H_
#include "Fundamentals.h"
#include "IndexedPool.h"
#include <string.h>
#include "RegisterTypes.h"
#include "RegisterClass.h"
//------------------------------------------------------------------------------
// VirtualRegister - 24b
class Instruction;
class VirtualRegister : public IndexedObject<VirtualRegister>
{
public:
Instruction* definingInstruction; // Instruction defining this VR.
// Initialize a VR of the given classKind.
VirtualRegister(RegisterClassKind /*classKind*/) : definingInstruction(NULL) {}
// Return the defining instruction for this VR.
Instruction* getDefiningInstruction() const {return definingInstruction;}
// Set the defining instruction.
void setDefiningInstruction(Instruction& insn);
};
// Return true if the VirtualRegisters are equals. The only way 2 VRs can be equal is if
// they have the same index. If they have the same index then they are at the same
// address in the indexed pool.
//
inline bool operator == (const VirtualRegister& regA, const VirtualRegister& regB) {return &regA == &regB;}
//------------------------------------------------------------------------------
// VirtualRegisterManager -
struct PreColoredRegister
{
RegisterID id;
RegisterName color;
};
class VirtualRegisterManager
{
private:
IndexedPool<VirtualRegister> registerPool;
PreColoredRegister machineRegister[6];
public:
VirtualRegisterManager()
{
for (Uint32 i = 0; i < 6; i++)
machineRegister[i].id = invalidID;
}
// Return the VirtualRegister at the given index.
VirtualRegister& getVirtualRegister(RegisterName name) const {return registerPool.get(name);}
// Return a new VirtualRegister.
RegisterID newVirtualRegister(RegisterClassKind classKind)
{
VirtualRegister& vReg = *new(registerPool) VirtualRegister(classKind);
RegisterID rid;
setName(rid, RegisterName(vReg.getIndex()));
setClass(rid, classKind);
return rid;
}
RegisterID newMachineRegister(RegisterName name, RegisterClassKind classKind)
{
RegisterID rid = machineRegister[name].id;
if (rid == invalidID) {
rid = newVirtualRegister(classKind);
DEBUG_ONLY(setMachineRegister(rid));
machineRegister[name].id = rid;
machineRegister[name].color = name;
}
return rid;
}
PreColoredRegister* getMachineRegistersBegin() const {return (PreColoredRegister*) machineRegister;} // FIX
PreColoredRegister* getMachineRegistersEnd() const {return (PreColoredRegister*) &machineRegister[6];} // FIX
// Return the VirtualRegister universe size.
Uint32 getSize() {return registerPool.getSize();}
void setSize(Uint32 size) {registerPool.setSize(size);}
};
#endif // _VIRTUAL_REGISTER_H_

View File

@@ -1,31 +0,0 @@
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 2001 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = common daemon testmodule public src extensions build test
include $(topsrcdir)/config/rules.mk

View File

@@ -1,12 +0,0 @@
DAEMON ONLY DIRECTORIES:
daemon/
testmodule/
CLIENT ONLY DIRECTORIES:
public/
src/
build/
test/
SHARED CODE DIRECTORY:
common/

View File

@@ -1,76 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = ipc
LIBRARY_NAME = ipc
EXPORT_LIBRARY = 1
IS_COMPONENT = 1
MODULE_NAME = ipc
REQUIRES = xpcom \
string \
necko \
$(NULL)
CPPSRCS = ipcModule.cpp
EXPORTS = ipcCID.h
SHARED_LIBRARY_LIBS = \
$(DIST)/lib/$(LIB_PREFIX)ipc_s.$(LIB_SUFFIX) \
$(DIST)/lib/$(LIB_PREFIX)ipccom_s.$(LIB_SUFFIX) \
$(DIST)/lib/$(LIB_PREFIX)ipclock_s.$(LIB_SUFFIX) \
$(NULL)
LOCAL_INCLUDES = \
-I$(srcdir)/../src \
-I$(srcdir)/../common \
-I$(srcdir)/../extensions/lock/src \
$(NULL)
EXTRA_DSO_LDOPTS = \
$(LIBS_DIR) \
$(EXTRA_DSO_LIBS) \
$(MOZ_COMPONENT_LIBS) \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,69 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcCID_h__
#define ipcCID_h__
#define IPC_SERVICE_CLASSNAME \
"ipcService"
#define IPC_SERVICE_CONTRACTID \
"@mozilla.org/ipc/service;1"
#define IPC_SERVICE_CID \
{ /* 9f12676a-5168-4a08-beb8-edf8a593a1ca */ \
0x9f12676a, \
0x5168, \
0x4a08, \
{0xbe, 0xb8, 0xed, 0xf8, 0xa5, 0x93, 0xa1, 0xca} \
}
//-----------------------------------------------------------------------------
// extensions
// XXX replace CID with one from botbot
#define IPC_LOCKSERVICE_CLASSNAME \
"ipcLockService"
#define IPC_LOCKSERVICE_CONTRACTID \
"@mozilla.org/ipc/lock-service;1"
#define IPC_LOCKSERVICE_CID \
{ /* 7aaeaceb-b207-4b45-bbde-a13276401fc2 */ \
0x7aaeaceb, \
0xb207, \
0x4b45, \
{0xbb, 0xde, 0xa1, 0x32, 0x76, 0x40, 0x1f, 0xc2} \
}
#endif // !ipcCID_h__

View File

@@ -1,141 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsIServiceManager.h"
#include "nsIGenericFactory.h"
#include "nsICategoryManager.h"
#include "ipcService.h"
#include "ipcCID.h"
#include "ipcConfig.h"
//-----------------------------------------------------------------------------
// Define the contructor function for the objects
//
// NOTE: This creates an instance of objects by using the default constructor
//-----------------------------------------------------------------------------
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(ipcService, Init)
#if 0
NS_METHOD
ipcServiceRegisterProc(nsIComponentManager *aCompMgr,
nsIFile *aPath,
const char *registryLocation,
const char *componentType,
const nsModuleComponentInfo *info)
{
//
// add ipcService to the XPCOM startup category
//
nsCOMPtr<nsICategoryManager> catman(do_GetService(NS_CATEGORYMANAGER_CONTRACTID));
if (catman) {
nsXPIDLCString prevEntry;
catman->AddCategoryEntry(NS_XPCOM_STARTUP_OBSERVER_ID, "ipcService",
IPC_SERVICE_CONTRACTID, PR_TRUE, PR_TRUE,
getter_Copies(prevEntry));
}
return NS_OK;
}
NS_METHOD
ipcServiceUnregisterProc(nsIComponentManager *aCompMgr,
nsIFile *aPath,
const char *registryLocation,
const nsModuleComponentInfo *info)
{
nsCOMPtr<nsICategoryManager> catman(do_GetService(NS_CATEGORYMANAGER_CONTRACTID));
if (catman)
catman->DeleteCategoryEntry(NS_XPCOM_STARTUP_OBSERVER_ID,
IPC_SERVICE_CONTRACTID, PR_TRUE);
return NS_OK;
}
#endif
#ifdef XP_UNIX
#include "ipcSocketProviderUnix.h"
NS_GENERIC_FACTORY_CONSTRUCTOR(ipcSocketProviderUnix)
#define IPC_SOCKETPROVIDER_CLASSNAME \
"ipcSocketProvider"
#define IPC_SOCKETPROVIDER_CID \
{ /* b888f500-ab5d-459c-aab0-bc61e844a503 */ \
0xb888f500, \
0xab5d, \
0x459c, \
{0xaa, 0xb0, 0xbc, 0x61, 0xe8, 0x44, 0xa5, 0x03} \
}
#endif
//-----------------------------------------------------------------------------
// extensions
#include "ipcLockService.h"
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(ipcLockService, Init)
//-----------------------------------------------------------------------------
// Define a table of CIDs implemented by this module along with other
// information like the function to create an instance, contractid, and
// class name.
//-----------------------------------------------------------------------------
static const nsModuleComponentInfo components[] = {
{ IPC_SERVICE_CLASSNAME,
IPC_SERVICE_CID,
IPC_SERVICE_CONTRACTID,
ipcServiceConstructor },
/*
ipcServiceRegisterProc,
ipcServiceUnregisterProc },
*/
#ifdef XP_UNIX
{ IPC_SOCKETPROVIDER_CLASSNAME,
IPC_SOCKETPROVIDER_CID,
NS_NETWORK_SOCKET_CONTRACTID_PREFIX IPC_SOCKET_TYPE,
ipcSocketProviderUnixConstructor, },
#endif
//
// extensions go here:
//
{ IPC_LOCKSERVICE_CLASSNAME,
IPC_LOCKSERVICE_CID,
IPC_LOCKSERVICE_CONTRACTID,
ipcLockServiceConstructor },
};
//-----------------------------------------------------------------------------
// Implement the NSGetModule() exported function for your module
// and the entire implementation of the module object.
//-----------------------------------------------------------------------------
NS_IMPL_NSGETMODULE(ipcModule, components)

View File

@@ -1,70 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = ipc
LIBRARY_NAME = ipccom_s
EXPORT_LIBRARY = 1
FORCE_STATIC_LIB = 1
MODULE_NAME = ipc
REQUIRES = \
xpcom \
$(NULL)
CPPSRCS = \
ipcLog.cpp \
ipcConfig.cpp \
ipcMessage.cpp \
ipcMessagePrimitives.cpp \
ipcStringList.cpp \
ipcIDList.cpp \
ipcm.cpp
EXPORTS = \
ipcMessage.h \
ipcMessageQ.h \
ipcm.h \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,75 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifdef XP_WIN
#else
#include <string.h>
#include "ipcConfig.h"
#include "ipcLog.h"
#include "prenv.h"
#include "plstr.h"
static const char kDefaultSocketPrefix[] = "/tmp/.mozilla";
static const char kDefaultSocketSuffix[] = "-ipc/ipcd";
void IPC_GetDefaultSocketPath(char *buf, PRUint32 bufLen)
{
const char *logName;
int len;
PL_strncpyz(buf, kDefaultSocketPrefix, bufLen);
buf += (sizeof(kDefaultSocketPrefix) - 1);
bufLen -= (sizeof(kDefaultSocketPrefix) - 1);
logName = PR_GetEnv("LOGNAME");
if (!logName || !logName[0]) {
logName = PR_GetEnv("USER");
if (!logName || !logName[0]) {
LOG(("could not determine username from environment\n"));
goto end;
}
}
PL_strncpyz(buf, logName, bufLen);
len = strlen(logName);
buf += len;
bufLen -= len;
end:
PL_strncpyz(buf, kDefaultSocketSuffix, bufLen);
}
#endif

View File

@@ -1,81 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcProto_h__
#define ipcProto_h__
#if defined(XP_WIN)
//
// use WM_COPYDATA messages
//
#include "prprf.h"
#define IPC_WINDOW_CLASS "Mozilla:IPCWindowClass"
#define IPC_WINDOW_NAME "Mozilla:IPCWindow"
#define IPC_CLIENT_WINDOW_CLASS "Mozilla:IPCAppWindowClass"
#define IPC_CLIENT_WINDOW_NAME_PREFIX "Mozilla:IPCAppWindow:"
#define IPC_SYNC_EVENT_NAME "Local\\MozillaIPCSyncEvent"
#define IPC_DAEMON_APP_NAME "mozipcd.exe"
#define IPC_PATH_SEP_CHAR '\\'
#define IPC_MODULES_DIR "ipc\\modules"
#define IPC_CLIENT_WINDOW_NAME_MAXLEN (sizeof(IPC_CLIENT_WINDOW_NAME_PREFIX) + 20)
// writes client name into buf. buf must be at least
// IPC_CLIENT_WINDOW_NAME_MAXLEN bytes in length.
inline void IPC_GetClientWindowName(PRUint32 pid, char *buf)
{
PR_snprintf(buf, IPC_CLIENT_WINDOW_NAME_MAXLEN, "%s%u",
IPC_CLIENT_WINDOW_NAME_PREFIX, pid);
}
#else
#include "prtypes.h"
//
// use UNIX domain socket
//
#define IPC_PORT 0
#define IPC_SOCKET_TYPE "ipc"
#define IPC_DAEMON_APP_NAME "mozipcd"
#define IPC_PATH_SEP_CHAR '/'
#define IPC_MODULES_DIR "ipc/modules"
void IPC_GetDefaultSocketPath(char *buf, PRUint32 bufLen);
#endif
#endif // !ipcProto_h__

View File

@@ -1,62 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "ipcIDList.h"
ipcIDNode *
ipcIDList::FindNode(ipcIDNode *node, const nsID &id)
{
while (node) {
if (node->Equals(id))
return node;
node = node->mNext;
}
return NULL;
}
ipcIDNode *
ipcIDList::FindNodeBefore(ipcIDNode *node, const nsID &id)
{
ipcIDNode *prev = NULL;
while (node) {
if (node->Equals(id))
return prev;
prev = node;
node = node->mNext;
}
return NULL;
}

View File

@@ -1,102 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcIDList_h__
#define ipcIDList_h__
#include "nsID.h"
#include "ipcList.h"
//-----------------------------------------------------------------------------
// nsID node
//-----------------------------------------------------------------------------
class ipcIDNode
{
public:
ipcIDNode(const nsID &id)
: mID(id)
{ }
const nsID &Value() const { return mID; }
PRBool Equals(const nsID &id) const { return mID.Equals(id); }
class ipcIDNode *mNext;
private:
nsID mID;
};
//-----------------------------------------------------------------------------
// singly-linked list of nsIDs
//-----------------------------------------------------------------------------
class ipcIDList : public ipcList<ipcIDNode>
{
public:
typedef ipcList<ipcIDNode> Super;
void Prepend(const nsID &id)
{
Super::Prepend(new ipcIDNode(id));
}
void Append(const nsID &id)
{
Super::Append(new ipcIDNode(id));
}
const ipcIDNode *Find(const nsID &id) const
{
return FindNode(mHead, id);
}
void FindAndDelete(const nsID &id)
{
ipcIDNode *node = FindNodeBefore(mHead, id);
if (node)
DeleteAfter(node);
else
DeleteFirst();
}
private:
static ipcIDNode *FindNode (ipcIDNode *head, const nsID &id);
static ipcIDNode *FindNodeBefore(ipcIDNode *head, const nsID &id);
};
#endif // !ipcIDList_h__

View File

@@ -1,176 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcList_h__
#define ipcList_h__
#include "prtypes.h"
//-----------------------------------------------------------------------------
// simple list of singly-linked objects. class T must have the following
// structure:
//
// class T {
// ...
// public:
// T *mNext;
// };
//
// objects added to the list must be allocated with operator new.
//-----------------------------------------------------------------------------
template<class T>
class ipcList
{
public:
ipcList()
: mHead(NULL)
, mTail(NULL)
{ }
~ipcList() { DeleteAll(); }
//
// prepends obj at the beginning of the list.
//
void Prepend(T *obj)
{
obj->mNext = mHead;
mHead = obj;
if (!mTail)
mTail = mHead;
}
//
// appends obj to the end of the list.
//
void Append(T *obj)
{
obj->mNext = NULL;
if (mTail) {
mTail->mNext = obj;
mTail = obj;
}
else
mTail = mHead = obj;
}
//
// inserts b into the list after a.
//
void InsertAfter(T *a, T *b)
{
b->mNext = a->mNext;
a->mNext = b;
if (mTail == a)
mTail = b;
}
//
// removes first element w/o deleting it
//
void RemoveFirst()
{
if (mHead)
AdvanceHead();
}
//
// removes element after the given element w/o deleting it
//
void RemoveAfter(T *obj)
{
T *rej = obj->mNext;
if (rej) {
obj->mNext = rej->mNext;
if (rej == mTail)
mTail = obj;
}
}
//
// deletes first element
//
void DeleteFirst()
{
T *first = mHead;
if (first) {
AdvanceHead();
delete first;
}
}
//
// deletes element after the given element
//
void DeleteAfter(T *obj)
{
T *rej = obj->mNext;
if (rej) {
RemoveAfter(obj);
delete rej;
}
}
//
// deletes all elements
//
void DeleteAll()
{
while (mHead)
DeleteFirst();
}
const T *First() const { return mHead; }
T *First() { return mHead; }
const T *Last() const { return mTail; }
T *Last() { return mTail; }
PRBool IsEmpty() const { return mHead == NULL; }
protected:
void AdvanceHead()
{
mHead = mHead->mNext;
if (!mHead)
mTail = NULL;
}
T *mHead;
T *mTail;
};
#endif // !ipcList_h__

View File

@@ -1,115 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "ipcLog.h"
#ifdef IPC_LOGGING
#include <string.h>
#include "prenv.h"
#include "prprf.h"
#include "plstr.h"
PRBool ipcLogEnabled = PR_FALSE;
char ipcLogPrefix[10] = {0};
//-----------------------------------------------------------------------------
// UNIX
//-----------------------------------------------------------------------------
#ifdef XP_UNIX
#include <sys/types.h>
#include <unistd.h>
static inline PRUint32
WritePrefix(char *buf, PRUint32 bufLen)
{
return PR_snprintf(buf, bufLen, "[%u] %s ",
(unsigned) getpid(),
ipcLogPrefix);
}
#endif
//-----------------------------------------------------------------------------
// WIN32
//-----------------------------------------------------------------------------
#ifdef XP_WIN
#include <windows.h>
static inline PRUint32
WritePrefix(char *buf, PRUint32 bufLen)
{
return PR_snprintf(buf, bufLen, "[%u:%u] %s ",
GetCurrentProcessId(),
GetCurrentThreadId(),
ipcLogPrefix);
}
#endif
//-----------------------------------------------------------------------------
// logging API impl
//-----------------------------------------------------------------------------
void
IPC_InitLog(const char *prefix)
{
if (PR_GetEnv("IPC_LOG_ENABLE")) {
ipcLogEnabled = PR_TRUE;
PL_strncpyz(ipcLogPrefix, prefix, sizeof(ipcLogPrefix));
}
}
void
IPC_Log(const char *fmt, ... )
{
va_list ap;
va_start(ap, fmt);
PRUint32 nb = 0;
char buf[512];
if (ipcLogPrefix[0])
nb = WritePrefix(buf, sizeof(buf));
PR_vsnprintf(buf + nb, sizeof(buf) - nb, fmt, ap);
buf[sizeof(buf) - 1] = '\0';
fwrite(buf, strlen(buf), 1, stdout);
va_end(ap);
}
#endif

View File

@@ -1,65 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcLog_h__
#define ipcLog_h__
#include "prtypes.h"
#define IPC_LOGGING
#ifdef IPC_LOGGING
extern PRBool ipcLogEnabled;
extern void IPC_InitLog(const char *prefix);
extern void IPC_Log(const char *fmt, ...);
#define IPC_LOG(_args) \
PR_BEGIN_MACRO \
if (ipcLogEnabled) \
IPC_Log _args; \
PR_END_MACRO
#define LOG(args) IPC_LOG(args)
#define LOG_ENABLED() ipcLogEnabled
#else
#define IPC_InitLog(prefix)
#define LOG(args)
#define LOG_ENABLED() (0)
#endif
#endif // !ipcLog_h__

View File

@@ -1,245 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdlib.h>
#include <string.h>
#include "prlog.h"
#include "ipcMessage.h"
ipcMessage::~ipcMessage()
{
if (mMsgHdr)
free(mMsgHdr);
}
void
ipcMessage::Reset()
{
if (mMsgHdr) {
free(mMsgHdr);
mMsgHdr = NULL;
}
mMsgOffset = 0;
mMsgComplete = PR_FALSE;
}
ipcMessage *
ipcMessage::Clone() const
{
ipcMessage *clone = new ipcMessage();
if (!clone)
return NULL;
// copy buf if non-null
if (mMsgHdr) {
clone->mMsgHdr = (ipcMessageHeader *) malloc(mMsgHdr->mLen);
memcpy(clone->mMsgHdr, mMsgHdr, mMsgHdr->mLen);
}
else
clone->mMsgHdr = NULL;
clone->mMsgOffset = mMsgOffset;
clone->mMsgComplete = mMsgComplete;
return clone;
}
PRStatus
ipcMessage::Init(const nsID &target, const char *data, PRUint32 dataLen)
{
if (mMsgHdr)
free(mMsgHdr);
mMsgComplete = PR_FALSE;
// allocate message data
PRUint32 msgLen = IPC_MSG_HEADER_SIZE + dataLen;
mMsgHdr = (ipcMessageHeader *) malloc(msgLen);
if (!mMsgHdr) {
mMsgHdr = NULL;
return PR_FAILURE;
}
// fill in message data
mMsgHdr->mLen = msgLen;
mMsgHdr->mVersion = IPC_MSG_VERSION;
mMsgHdr->mFlags = 0;
mMsgHdr->mTarget = target;
if (data)
SetData(0, data, dataLen);
mMsgComplete = PR_TRUE;
return PR_SUCCESS;
}
PRStatus
ipcMessage::SetData(PRUint32 offset, const char *data, PRUint32 dataLen)
{
PR_ASSERT(mMsgHdr != NULL);
if (offset + dataLen > DataLen())
return PR_FAILURE;
memcpy((char *) Data() + offset, data, dataLen);
return PR_SUCCESS;
}
PRBool
ipcMessage::Equals(const nsID &target, const char *data, PRUint32 dataLen) const
{
return mMsgComplete &&
mMsgHdr->mTarget.Equals(target) &&
DataLen() == dataLen &&
memcmp(Data(), data, dataLen) == 0;
}
PRBool
ipcMessage::Equals(const ipcMessage *msg) const
{
PRUint32 msgLen = MsgLen();
return mMsgComplete && msg->mMsgComplete &&
msgLen == msg->MsgLen() &&
memcmp(MsgBuf(), msg->MsgBuf(), msgLen) == 0;
}
PRStatus
ipcMessage::WriteTo(char *buf,
PRUint32 bufLen,
PRUint32 *bytesWritten,
PRBool *complete)
{
if (!mMsgComplete)
return PR_FAILURE;
if (mMsgOffset == MsgLen()) {
*bytesWritten = 0;
*complete = PR_TRUE;
return PR_SUCCESS;
}
PRUint32 count = MsgLen() - mMsgOffset;
if (count > bufLen)
count = bufLen;
memcpy(buf, MsgBuf() + mMsgOffset, count);
mMsgOffset += count;
*bytesWritten = count;
*complete = (mMsgOffset == MsgLen());
return PR_SUCCESS;
}
PRStatus
ipcMessage::ReadFrom(const char *buf,
PRUint32 bufLen,
PRUint32 *bytesRead,
PRBool *complete)
{
*bytesRead = 0;
if (mMsgComplete) {
*complete = PR_TRUE;
return PR_SUCCESS;
}
if (mMsgHdr) {
// appending data to buffer
if (mMsgOffset < sizeof(PRUint32)) {
// we haven't learned the message length yet
if (mMsgOffset + bufLen < sizeof(PRUint32)) {
// we still don't know the length of the message!
memcpy((char *) mMsgHdr + mMsgOffset, buf, bufLen);
mMsgOffset += bufLen;
*bytesRead = bufLen;
*complete = PR_FALSE;
return PR_SUCCESS;
}
else {
// we now have enough data to determine the message length
PRUint32 count = sizeof(PRUint32) - mMsgOffset;
memcpy((char *) MsgBuf() + mMsgOffset, buf, count);
mMsgOffset += count;
buf += count;
bufLen -= count;
*bytesRead = count;
if (MsgLen() > IPC_MSG_GUESSED_SIZE) {
// realloc message buffer to the correct size
mMsgHdr = (ipcMessageHeader *) realloc(mMsgHdr, MsgLen());
}
}
}
}
else {
if (bufLen < sizeof(PRUint32)) {
// not enough data available in buffer to determine allocation size
// allocate a partial buffer
PRUint32 msgLen = IPC_MSG_GUESSED_SIZE;
mMsgHdr = (ipcMessageHeader *) malloc(msgLen);
if (!mMsgHdr)
return PR_FAILURE;
memcpy(mMsgHdr, buf, bufLen);
mMsgOffset = bufLen;
*bytesRead = bufLen;
*complete = PR_FALSE;
return PR_SUCCESS;
}
else {
PRUint32 msgLen = *(PRUint32 *) buf;
mMsgHdr = (ipcMessageHeader *) malloc(msgLen);
if (!mMsgHdr)
return PR_FAILURE;
mMsgHdr->mLen = msgLen;
mMsgOffset = 0;
}
}
// have mMsgHdr at this point
PRUint32 count = MsgLen() - mMsgOffset;
if (count > bufLen)
count = bufLen;
memcpy((char *) mMsgHdr + mMsgOffset, buf, count);
mMsgOffset += count;
*bytesRead += count;
*complete = mMsgComplete = (mMsgOffset == MsgLen());
return PR_SUCCESS;
}

View File

@@ -1,198 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcMessage_h__
#define ipcMessage_h__
#include "nsID.h"
//
// ipc message format:
//
// +------------------------------------+
// | DWORD : length |
// +------------------+-----------------+
// | WORD : version | WORD : flags |
// +------------------+-----------------+
// | nsID : target |
// +------------------------------------+
// | data |
// +------------------------------------+
//
// header is 24 bytes. flags are defined below. default value of flags is
// zero. protocol implementations should ignore unrecognized flags. target
// is a 16 byte UUID indicating the intended receiver of this message.
//
struct ipcMessageHeader
{
PRUint32 mLen;
PRUint16 mVersion;
PRUint16 mFlags;
nsID mTarget;
};
#define IPC_MSG_VERSION (0x1)
#define IPC_MSG_HEADER_SIZE (sizeof(ipcMessageHeader))
#define IPC_MSG_GUESSED_SIZE (IPC_MSG_HEADER_SIZE + 64)
//
// the IPC message protocol supports synchronous messages. these messages can
// only be sent from a client to the daemon. a daemon module cannot send a
// synchronous message. the client sets the SYNC_QUERY flag to indicate that
// it is expecting a response with the SYNC_REPLY flag set.
//
#define IPC_MSG_FLAG_SYNC_QUERY (0x1)
#define IPC_MSG_FLAG_SYNC_REPLY (0x2)
//-----------------------------------------------------------------------------
// ipcMessage
//-----------------------------------------------------------------------------
class ipcMessage
{
public:
ipcMessage()
: mNext(NULL)
, mMsgHdr(NULL)
, mMsgOffset(0)
, mMsgComplete(PR_FALSE)
{ }
ipcMessage(const nsID &target, const char *data, PRUint32 dataLen)
: mNext(NULL)
, mMsgHdr(NULL)
, mMsgOffset(0)
{ Init(target, data, dataLen); }
~ipcMessage();
//
// reset message to uninitialized state
//
void Reset();
//
// create a copy of this message
//
ipcMessage *Clone() const;
//
// initialize message
//
// param:
// topic - message topic string
// data - message data (may be null to leave data uninitialized)
// dataLen - message data len
//
PRStatus Init(const nsID &target, const char *data, PRUint32 dataLen);
//
// copy data into the message's data section, starting from offset. this
// function can be used to write only a portion of the message's data.
//
// param:
// offset - destination offset
// data - data to write
// dataLen - number of bytes to write
//
PRStatus SetData(PRUint32 offset, const char *data, PRUint32 dataLen);
//
// access message flags
//
void SetFlag(PRUint16 flag) { mMsgHdr->mFlags |= flag; }
void ClearFlag(PRUint16 flag) { mMsgHdr->mFlags &= ~flag; }
PRBool TestFlag(PRUint16 flag) const { return mMsgHdr->mFlags & flag; }
//
// if true, the message is complete and the members of the message
// can be accessed.
//
PRBool IsComplete() const { return mMsgComplete; }
//
// readonly accessors
//
const ipcMessageHeader *Header() const { return mMsgHdr; }
const nsID &Target() const { return mMsgHdr->mTarget; }
const char *Data() const { return (char *) mMsgHdr + IPC_MSG_HEADER_SIZE; }
PRUint32 DataLen() const { return mMsgHdr->mLen - IPC_MSG_HEADER_SIZE; }
const char *MsgBuf() const { return (char *) mMsgHdr; }
PRUint32 MsgLen() const { return mMsgHdr->mLen; }
//
// message comparison functions
//
// param:
// topic - message topic (may be null)
// data - message data (must not be null)
// dataLen - message data length
//
PRBool Equals(const nsID &target, const char *data, PRUint32 dataLen) const;
PRBool Equals(const ipcMessage *msg) const;
//
// write the message to a buffer segment; segment need not be large
// enough to hold entire message. called repeatedly.
//
PRStatus WriteTo(char *buf,
PRUint32 bufLen,
PRUint32 *bytesWritten,
PRBool *complete);
//
// read the message from a buffer segment; segment need not contain
// the entire messgae. called repeatedly.
//
PRStatus ReadFrom(const char *buf,
PRUint32 bufLen,
PRUint32 *bytesRead,
PRBool *complete);
//
// a message can be added to a singly-linked list.
//
class ipcMessage *mNext;
private:
ipcMessageHeader *mMsgHdr;
// XXX document me
PRUint32 mMsgOffset;
PRPackedBool mMsgComplete;
};
#endif // !ipcMessage_h__

View File

@@ -1,58 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <string.h>
#include "ipcMessagePrimitives.h"
ipcMessage_DWORD_STR::ipcMessage_DWORD_STR(const nsID &target,
PRUint32 first,
const char *second)
{
int sLen = strlen(second);
Init(target, NULL, sizeof(first) + sLen + 1);
SetData(0, (char *) &first, sizeof(first));
SetData(sizeof(first), second, sLen + 1);
}
ipcMessage_DWORD_ID::ipcMessage_DWORD_ID(const nsID &target,
PRUint32 first,
const nsID &second)
{
Init(target, NULL, sizeof(first) + sizeof(nsID));
SetData(0, (char *) &first, sizeof(first));
SetData(sizeof(first), (char *) &second, sizeof(nsID));
}

View File

@@ -1,109 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcMessagePrimitives_h__
#define ipcMessagePrimitives_h__
#include "ipcMessage.h"
class ipcMessage_DWORD : public ipcMessage
{
public:
ipcMessage_DWORD(const nsID &target, PRUint32 first)
{
Init(target, (char *) &first, sizeof(first));
}
PRUint32 First() const
{
return ((PRUint32 *) Data())[0];
}
};
class ipcMessage_DWORD_DWORD : public ipcMessage
{
public:
ipcMessage_DWORD_DWORD(const nsID &target, PRUint32 first, PRUint32 second)
{
PRUint32 data[2] = { first, second };
Init(target, (char *) data, sizeof(data));
}
PRUint32 First() const
{
return ((PRUint32 *) Data())[0];
}
PRUint32 Second() const
{
return ((PRUint32 *) Data())[1];
}
};
class ipcMessage_DWORD_STR : public ipcMessage
{
public:
ipcMessage_DWORD_STR(const nsID &target, PRUint32 first, const char *second);
PRUint32 First() const
{
return ((PRUint32 *) Data())[0];
}
const char *Second() const
{
return Data() + sizeof(PRUint32);
}
};
class ipcMessage_DWORD_ID : public ipcMessage
{
public:
ipcMessage_DWORD_ID(const nsID &target, PRUint32 first, const nsID &second);
PRUint32 First() const
{
return ((PRUint32 *) Data())[0];
}
const nsID &Second() const
{
return * (const nsID *) (Data() + sizeof(PRUint32));
}
};
#endif // !ipcMessagePrimitives_h__

View File

@@ -1,46 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcMessageQ_h__
#define ipcMessageQ_h__
#include "ipcMessage.h"
#include "ipcList.h"
typedef ipcList<ipcMessage> ipcMessageQ;
#endif // !ipcMessageQ_h__

View File

@@ -1,66 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcMessageUtils_h__
#define ipcMessageUtils_h__
class ipcMessage;
//
// given code like this:
//
// const ipcmMessageClientID *msg = (const ipcmMessageClientID *) rawMsg;
//
// we can write:
//
// ipcMessageCast<ipcmMessageClientID> msg(rawMsg);
//
// XXX ipcMessageCast is probably not the best name for this class.
//
template<class T>
class ipcMessageCast
{
public:
ipcMessageCast() : mPtr(NULL) {}
ipcMessageCast(const ipcMessage *ptr) : mPtr((const T *) ptr) {}
void operator=(const ipcMessage *ptr) { mPtr = (const T *) ptr; }
const T *operator->() { return mPtr; }
private:
const T *mPtr;
};
#endif // !ipcMessageUtils_h__

View File

@@ -1,80 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "ipcStringList.h"
void *
ipcStringNode::operator new(size_t size, const char *str) CPP_THROW_NEW
{
int len = strlen(str);
size += len;
ipcStringNode *node = (ipcStringNode *) ::operator new(size);
if (!node)
return NULL;
node->mNext = NULL;
memcpy(node->mData, str, len);
node->mData[len] = '\0';
return node;
}
ipcStringNode *
ipcStringList::FindNode(ipcStringNode *node, const char *str)
{
while (node) {
if (node->Equals(str))
return node;
node = node->mNext;
}
return NULL;
}
ipcStringNode *
ipcStringList::FindNodeBefore(ipcStringNode *node, const char *str)
{
ipcStringNode *prev = NULL;
while (node) {
if (node->Equals(str))
return prev;
prev = node;
node = node->mNext;
}
return NULL;
}

View File

@@ -1,107 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcStringList_h__
#define ipcStringList_h__
#include <string.h>
#include "plstr.h"
#include "ipcList.h"
//-----------------------------------------------------------------------------
// string node
//-----------------------------------------------------------------------------
class ipcStringNode
{
public:
ipcStringNode() {}
const char *Value() const { return mData; }
PRBool Equals(const char *val) const { return strcmp(mData, val) == 0; }
PRBool EqualsIgnoreCase(const char *val) const { return PL_strcasecmp(mData, val) == 0; }
class ipcStringNode *mNext;
private:
void *operator new(size_t size, const char *str) CPP_THROW_NEW;
// this is actually bigger
char mData[1];
friend class ipcStringList;
};
//-----------------------------------------------------------------------------
// singly-linked list of strings
//-----------------------------------------------------------------------------
class ipcStringList : public ipcList<ipcStringNode>
{
public:
typedef ipcList<ipcStringNode> Super;
void Prepend(const char *str)
{
Super::Prepend(new (str) ipcStringNode());
}
void Append(const char *str)
{
Super::Append(new (str) ipcStringNode());
}
const ipcStringNode *Find(const char *str) const
{
return FindNode(mHead, str);
}
void FindAndDelete(const char *str)
{
ipcStringNode *node = FindNodeBefore(mHead, str);
if (node)
DeleteAfter(node);
else
DeleteFirst();
}
private:
static ipcStringNode *FindNode (ipcStringNode *head, const char *str);
static ipcStringNode *FindNodeBefore(ipcStringNode *head, const char *str);
};
#endif // !ipcStringList_h__

View File

@@ -1,277 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <string.h>
#include "ipcm.h"
#include "prlog.h"
const nsID IPCM_TARGET =
{ /* 753ca8ff-c8c2-4601-b115-8c2944da1150 */
0x753ca8ff,
0xc8c2,
0x4601,
{0xb1, 0x15, 0x8c, 0x29, 0x44, 0xda, 0x11, 0x50}
};
//
// MSG_TYPE values
//
const PRUint32 ipcmMessagePing::MSG_TYPE = IPCM_MSG_TYPE_PING;
const PRUint32 ipcmMessageError::MSG_TYPE = IPCM_MSG_TYPE_ERROR;
const PRUint32 ipcmMessageClientHello::MSG_TYPE = IPCM_MSG_TYPE_CLIENT_HELLO;
const PRUint32 ipcmMessageClientID::MSG_TYPE = IPCM_MSG_TYPE_CLIENT_ID;
const PRUint32 ipcmMessageClientInfo::MSG_TYPE = IPCM_MSG_TYPE_CLIENT_INFO;
const PRUint32 ipcmMessageClientAddName::MSG_TYPE = IPCM_MSG_TYPE_CLIENT_ADD_NAME;
const PRUint32 ipcmMessageClientDelName::MSG_TYPE = IPCM_MSG_TYPE_CLIENT_DEL_NAME;
const PRUint32 ipcmMessageClientAddTarget::MSG_TYPE = IPCM_MSG_TYPE_CLIENT_ADD_TARGET;
const PRUint32 ipcmMessageClientDelTarget::MSG_TYPE = IPCM_MSG_TYPE_CLIENT_DEL_TARGET;
const PRUint32 ipcmMessageQueryClientByName::MSG_TYPE = IPCM_MSG_TYPE_QUERY_CLIENT_BY_NAME;
const PRUint32 ipcmMessageQueryClientInfo::MSG_TYPE = IPCM_MSG_TYPE_QUERY_CLIENT_INFO;
const PRUint32 ipcmMessageForward::MSG_TYPE = IPCM_MSG_TYPE_FORWARD;
//
// CLIENT_INFO message
//
// +-----------------------------------------+
// | DWORD : MSG_TYPE |
// +--------------------+--------------------+
// | DWORD : clientID |
// +--------------------+--------------------+
// | WORD : nameStart | WORD : nameCount |
// +--------------------+--------------------+
// | WORD : targetStart | WORD : targetCount |
// +--------------------+--------------------+
// | name[0] | (null byte) |
// +--------------------+--------------------+
// . . .
// . . .
// +--------------------+--------------------+
// | name[count - 1] | (null byte) |
// +--------------------+--------------------+
// | target[0] |
// +-----------------------------------------+
// . . .
// . . .
// +-----------------------------------------+
// | target[count - 1] |
// +-----------------------------------------+
//
struct ipcmClientInfoHeader
{
PRUint32 mType;
PRUint32 mID;
PRUint16 mNameStart;
PRUint16 mNameCount;
PRUint16 mTargetStart;
PRUint16 mTargetCount;
};
ipcmMessageClientInfo::ipcmMessageClientInfo(PRUint32 cID, const char *names[], const nsID *targets[])
{
ipcmClientInfoHeader hdr = {0};
hdr.mType = MSG_TYPE;
hdr.mID = cID;
hdr.mNameStart = sizeof(hdr);
PRUint32 i, namesLen = 0;
i = 0;
while (names[i]) {
namesLen += (strlen(names[i]) + 1);
++hdr.mNameCount;
++i;
}
i = 0;
while (targets[i]) {
++hdr.mTargetCount;
++i;
}
//
// compute target array starting offset
//
hdr.mTargetStart = hdr.mNameStart + namesLen;
//
// compute message length
//
PRUint32 dataLen = sizeof(hdr) + namesLen + hdr.mTargetCount * sizeof(nsID);
Init(IPCM_TARGET, NULL, dataLen);
//
// write message data
//
SetData(0, (const char *) &hdr, sizeof(hdr));
PRUint32 offset = sizeof(hdr);
for (i = 0; names[i]; ++i) {
PRUint32 len = strlen(names[i]) + 1;
SetData(offset, names[i], len);
offset += len;
}
for (i = 0; targets[i]; ++i) {
PRUint32 len = sizeof(nsID);
SetData(offset, (const char *) targets[i], len);
offset += len;
}
}
PRUint32
ipcmMessageClientInfo::ClientID() const
{
ipcmClientInfoHeader *hdr = (ipcmClientInfoHeader *) Data();
return hdr->mID;
}
PRUint32
ipcmMessageClientInfo::NameCount() const
{
ipcmClientInfoHeader *hdr = (ipcmClientInfoHeader *) Data();
return hdr->mNameCount;
}
PRUint32
ipcmMessageClientInfo::TargetCount() const
{
ipcmClientInfoHeader *hdr = (ipcmClientInfoHeader *) Data();
return hdr->mTargetCount;
}
const char *
ipcmMessageClientInfo::NextName(const char *name) const
{
ipcmClientInfoHeader *hdr = (ipcmClientInfoHeader *) Data();
if (!name)
return (const char *) hdr + hdr->mNameStart;
name += strlen(name) + 1;
if (name == (const char *) hdr + hdr->mTargetStart)
name = NULL;
return name;
}
const nsID *
ipcmMessageClientInfo::NextTarget(const nsID *target) const
{
ipcmClientInfoHeader *hdr = (ipcmClientInfoHeader *) Data();
if (!target)
return (const nsID *) (Data() + hdr->mTargetStart);
if (++target == (const nsID *) (MsgBuf() + MsgLen()))
target = NULL;
return target;
}
//
// FORWARD message
//
// +-------------------------+
// | DWORD : MSG_TYPE |
// +-------------------------+
// | clientID |
// +-------------------------+
// | innerMsgHeader |
// +-------------------------+
// | innerMsgData |
// +-------------------------+
//
ipcmMessageForward::ipcmMessageForward(PRUint32 cID,
const nsID &target,
const char *data,
PRUint32 dataLen)
{
int len = sizeof(MSG_TYPE) + // MSG_TYPE
sizeof(cID) + // cID
IPC_MSG_HEADER_SIZE + // innerMsgHeader
dataLen; // innerMsgData
Init(IPCM_TARGET, NULL, len);
SetData(0, (char *) &MSG_TYPE, sizeof(MSG_TYPE));
SetData(4, (char *) &cID, sizeof(cID));
ipcMessageHeader hdr;
hdr.mLen = IPC_MSG_HEADER_SIZE + dataLen;
hdr.mVersion = IPC_MSG_VERSION;
hdr.mFlags = 0;
hdr.mTarget = target;
SetData(8, (char *) &hdr, IPC_MSG_HEADER_SIZE);
if (data)
SetInnerData(0, data, dataLen);
}
void
ipcmMessageForward::SetInnerData(PRUint32 offset, const char *data, PRUint32 dataLen)
{
SetData(8 + IPC_MSG_HEADER_SIZE + offset, data, dataLen);
}
PRUint32
ipcmMessageForward::DestClientID() const
{
return ((PRUint32 *) Data())[1];
}
const nsID &
ipcmMessageForward::InnerTarget() const
{
ipcMessageHeader *hdr = (ipcMessageHeader *) (Data() + 8);
return hdr->mTarget;
}
const char *
ipcmMessageForward::InnerData() const
{
return Data() + 8 + IPC_MSG_HEADER_SIZE;
}
PRUint32
ipcmMessageForward::InnerDataLen() const
{
ipcMessageHeader *hdr = (ipcMessageHeader *) (Data() + 8);
return hdr->mLen - IPC_MSG_HEADER_SIZE;
}

View File

@@ -1,322 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcm_h__
#define ipcm_h__
#include "ipcMessage.h"
#include "ipcMessagePrimitives.h"
//
// IPCM (IPC Manager) protocol support
//
extern const nsID IPCM_TARGET;
enum {
IPCM_MSG_TYPE_PING,
IPCM_MSG_TYPE_ERROR,
IPCM_MSG_TYPE_CLIENT_HELLO,
IPCM_MSG_TYPE_CLIENT_ID,
IPCM_MSG_TYPE_CLIENT_INFO,
IPCM_MSG_TYPE_CLIENT_ADD_NAME,
IPCM_MSG_TYPE_CLIENT_DEL_NAME,
IPCM_MSG_TYPE_CLIENT_ADD_TARGET,
IPCM_MSG_TYPE_CLIENT_DEL_TARGET,
IPCM_MSG_TYPE_QUERY_CLIENT_BY_NAME,
IPCM_MSG_TYPE_QUERY_CLIENT_INFO,
// IPCM_MSG_TYPE_QUERY_MODULE, // check if module exists
IPCM_MSG_TYPE_FORWARD,
IPCM_MSG_TYPE_UNKNOWN // unknown message type
};
//
// returns IPCM message type.
//
static inline int
IPCM_GetMsgType(const ipcMessage *msg)
{
return ((const ipcMessage_DWORD *) msg)->First();
}
//
// NOTE: this file declares some helper classes that simplify construction
// and parsing of IPCM messages. each class subclasses ipcMessage, but
// adds no additional member variables. operator new should be used
// to allocate one of the IPCM helper classes, e.g.:
//
// ipcMessage *msg = new ipcmMessageClientHello("foo");
//
// given an arbitrary ipcMessage, it can be parsed using logic similar
// to the following:
//
// void func(const ipcMessage *unknown)
// {
// if (unknown->Topic().Equals(IPCM_TARGET)) {
// if (IPCM_GetMsgType(unknown) == IPCM_MSG_TYPE_CLIENT_ID) {
// ipcMessageCast<ipcmMessageClientID> msg(unknown);
// printf("Client ID: %u\n", msg->ClientID());
// }
// }
// }
//
// in other words, these classes are very very lightweight.
//
//
// IPCM_MSG_TYPE_PING
//
// this message may be sent from either the client or the daemon.
// if the daemon receives this message, then it will respond by
// sending back a PING to the client.
//
class ipcmMessagePing : public ipcMessage_DWORD
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessagePing()
: ipcMessage_DWORD(IPCM_TARGET, MSG_TYPE) {}
};
//
// IPCM_MSG_TYPE_ERROR
//
// this message may be sent from the daemon in place of an expected
// result. e.g., if a query fails, the daemon will send an error
// message to indicate the failure.
//
class ipcmMessageError : public ipcMessage_DWORD_DWORD
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageError(PRUint32 reason)
: ipcMessage_DWORD_DWORD(IPCM_TARGET, MSG_TYPE, reason) {}
PRUint32 Reason() const { return Second(); }
};
enum {
IPCM_ERROR_CLIENT_NOT_FOUND = 1
};
//
// IPCM_MSG_TYPE_CLIENT_HELLO
//
// this message is always the first message sent from a client to register
// itself with the daemon. the daemon responds to this message by sending
// the client a CLIENT_ID message informing the client of its client ID.
//
// XXX may want to pass other information here.
//
class ipcmMessageClientHello : public ipcMessage_DWORD
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageClientHello()
: ipcMessage_DWORD(IPCM_TARGET, MSG_TYPE) {}
};
//
// IPCM_MSG_TYPE_CLIENT_ID
//
// this message is sent from the daemon to identify a client's ID.
//
class ipcmMessageClientID : public ipcMessage_DWORD_DWORD
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageClientID(PRUint32 clientID)
: ipcMessage_DWORD_DWORD(IPCM_TARGET, MSG_TYPE, clientID) {}
PRUint32 ClientID() const { return Second(); }
};
//
// IPCM_MSG_TYPE_CLIENT_INFO
//
// this message is sent from the daemon to provide the list of names
// and targets for a particular client.
//
class ipcmMessageClientInfo : public ipcMessage
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageClientInfo(PRUint32 clientID, const char **names, const nsID **targets);
PRUint32 ClientID() const;
PRUint32 NameCount() const;
PRUint32 TargetCount() const;
const char *NextName(const char *name) const;
const nsID *NextTarget(const nsID *target) const;
};
//
// IPCM_MSG_TYPE_CLIENT_ADD_NAME
//
class ipcmMessageClientAddName : public ipcMessage_DWORD_STR
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageClientAddName(const char *name)
: ipcMessage_DWORD_STR(IPCM_TARGET, MSG_TYPE, name) {}
const char *Name() const { return Second(); }
};
//
// IPCM_MSG_TYPE_CLIENT_DEL_NAME
//
class ipcmMessageClientDelName : public ipcMessage_DWORD_STR
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageClientDelName(const char *name)
: ipcMessage_DWORD_STR(IPCM_TARGET, MSG_TYPE, name) {}
const char *Name() const { return Second(); }
};
//
// IPCM_MSG_TYPE_CLIENT_ADD_TARGET
//
class ipcmMessageClientAddTarget : public ipcMessage_DWORD_ID
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageClientAddTarget(const nsID &target)
: ipcMessage_DWORD_ID(IPCM_TARGET, MSG_TYPE, target) {}
const nsID &Target() const { return Second(); }
};
//
// IPCM_MSG_TYPE_CLIENT_DEL_TARGET
//
class ipcmMessageClientDelTarget : public ipcMessage_DWORD_ID
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageClientDelTarget(const nsID &target)
: ipcMessage_DWORD_ID(IPCM_TARGET, MSG_TYPE, target) {}
const nsID &Target() const { return Second(); }
};
//
// IPCM_MSG_TYPE_QUERY_CLIENT_BY_NAME
//
// this message is sent from a client to the daemon to request the ID of the
// client corresponding to the given name. in response the daemon will either
// send a CLIENT_ID or ERROR message.
//
class ipcmMessageQueryClientByName : public ipcMessage_DWORD_STR
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageQueryClientByName(const char *name)
: ipcMessage_DWORD_STR(IPCM_TARGET, MSG_TYPE, name) {}
const char *Name() const { return Second(); }
};
//
// IPCM_MSG_TYPE_QUERY_CLIENT_INFO
//
// thie message is sent from a client to the daemon to request complete
// information about the client corresponding to the given client ID. in
// response the daemon will either send a CLIENT_INFO or ERROR message.
//
class ipcmMessageQueryClientInfo : public ipcMessage_DWORD_DWORD
{
public:
static const PRUint32 MSG_TYPE;
ipcmMessageQueryClientInfo(PRUint32 clientID)
: ipcMessage_DWORD_DWORD(IPCM_TARGET, MSG_TYPE, clientID) {}
PRUint32 ClientID() const { return Second(); }
};
//
// IPCM_MSG_TYPE_FORWARD
//
// this message is only sent from the client to the daemon. the daemon
// will forward the contained message to the specified client. there
// is no guarantee that the message will be forwarded, and no error will
// be sent to the sender on failure.
//
class ipcmMessageForward : public ipcMessage
{
public:
static const PRUint32 MSG_TYPE;
//
// params:
// clientID - the client to which the message should be forwarded
// target - the message target
// data - the message data
// dataLen - the message data length
//
ipcmMessageForward(PRUint32 clientID,
const nsID &target,
const char *data,
PRUint32 dataLen);
//
// set inner message data, constrained to the data length passed
// to this class's constructor.
//
void SetInnerData(PRUint32 offset, const char *data, PRUint32 dataLen);
PRUint32 DestClientID() const;
const nsID &InnerTarget() const;
const char *InnerData() const;
PRUint32 InnerDataLen() const;
};
#endif // !ipcm_h__

View File

@@ -1,86 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = ipc
REQUIRES = \
xpcom \
$(NULL)
CPPSRCS = \
ipcd.cpp \
ipcClient.cpp \
ipcModuleReg.cpp \
ipcCommandModule.cpp
ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
CPPSRCS += ipcdWin.cpp
else
CPPSRCS += ipcdUnix.cpp
endif
PROGRAM = mozipcd$(BIN_SUFFIX)
EXPORTS = \
ipcModule.h \
ipcModuleUtil.h \
$(NULL)
LOCAL_INCLUDES = \
-I$(srcdir)/../common \
$(NULL)
include $(topsrcdir)/config/config.mk
LIBS = \
$(EXTRA_DSO_LIBS) \
$(NSPR_LIBS) \
$(DIST)/lib/$(LIB_PREFIX)ipccom_s.$(LIB_SUFFIX) \
$(NULL)
include $(topsrcdir)/config/rules.mk
# For fruncate
ifeq ($(OS_ARCH),Linux)
DEFINES += -D_BSD_SOURCE
endif

View File

@@ -1,233 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "ipcLog.h"
#include "ipcClient.h"
#include "ipcMessage.h"
#include "ipcModuleReg.h"
#include "ipcd.h"
#include "ipcm.h"
#ifdef XP_UNIX
#include "prio.h"
#endif
PRUint32 ipcClient::gLastID = 0;
//
// called to initialize this client context
//
// assumptions:
// - object's memory has already been zero'd out.
//
void
ipcClient::Init()
{
mID = ++gLastID;
// every client must be able to handle IPCM messages.
mTargets.Append(IPCM_TARGET);
// although it is tempting to fire off the NotifyClientUp event at this
// time, we must wait until the client sends us a CLIENT_HELLO event.
// see ipcCommandModule::OnClientHello.
}
//
// called when this client context is going away
//
void
ipcClient::Finalize()
{
IPC_NotifyClientDown(this);
mNames.DeleteAll();
mTargets.DeleteAll();
#ifdef XP_UNIX
mInMsg.Reset();
mOutMsgQ.DeleteAll();
#endif
}
void
ipcClient::AddName(const char *name)
{
LOG(("adding client name: %s\n", name));
if (HasName(name))
return;
mNames.Append(name);
}
void
ipcClient::DelName(const char *name)
{
LOG(("deleting client name: %s\n", name));
mNames.FindAndDelete(name);
}
void
ipcClient::AddTarget(const nsID &target)
{
LOG(("adding client target\n"));
if (HasTarget(target))
return;
mTargets.Append(target);
}
void
ipcClient::DelTarget(const nsID &target)
{
LOG(("deleting client target\n"));
//
// cannot remove the IPCM target
//
if (!target.Equals(IPCM_TARGET))
mTargets.FindAndDelete(target);
}
#ifdef XP_UNIX
//
// called to process a client socket
//
// params:
// fd - the client socket
// poll_flags - the state of the client socket
//
// return:
// 0 - to end session with this client
// PR_POLL_READ - to wait for the client socket to become readable
// PR_POLL_WRITE - to wait for the client socket to become writable
//
int
ipcClient::Process(PRFileDesc *fd, int inFlags)
{
if (inFlags & (PR_POLL_ERR | PR_POLL_HUP |
PR_POLL_EXCEPT | PR_POLL_NVAL)) {
LOG(("client socket appears to have closed\n"));
return 0;
}
// expect to wait for more data
int outFlags = PR_POLL_READ;
if (inFlags & PR_POLL_READ) {
LOG(("client socket is now readable\n"));
char buf[1024]; // XXX make this larger?
PRInt32 n;
// find out how much data is available for reading...
// n = PR_Available(fd);
n = PR_Read(fd, buf, sizeof(buf));
if (n <= 0)
return 0; // cancel connection
const char *ptr = buf;
while (n) {
PRUint32 nread;
PRBool complete;
if (mInMsg.ReadFrom(ptr, PRUint32(n), &nread, &complete) == PR_FAILURE) {
LOG(("message appears to be malformed; dropping client connection\n"));
return 0;
}
if (complete) {
IPC_DispatchMsg(this, &mInMsg);
mInMsg.Reset();
}
n -= nread;
ptr += nread;
}
}
if (inFlags & PR_POLL_WRITE) {
LOG(("client socket is now writable\n"));
if (mOutMsgQ.First())
WriteMsgs(fd);
}
if (mOutMsgQ.First())
outFlags |= PR_POLL_WRITE;
return outFlags;
}
//
// called to write out any messages from the outgoing queue.
//
int
ipcClient::WriteMsgs(PRFileDesc *fd)
{
while (mOutMsgQ.First()) {
const char *buf = (const char *) mOutMsgQ.First()->MsgBuf();
PRInt32 bufLen = (PRInt32) mOutMsgQ.First()->MsgLen();
if (mSendOffset) {
buf += mSendOffset;
bufLen -= mSendOffset;
}
PRInt32 nw = PR_Write(fd, buf, bufLen);
if (nw <= 0)
break;
LOG(("wrote %d bytes\n", nw));
if (nw == bufLen) {
mOutMsgQ.DeleteFirst();
mSendOffset = 0;
}
else
mSendOffset += nw;
}
return 0;
}
#endif

View File

@@ -1,144 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcClientUnix_h__
#define ipcClientUnix_h__
#include "prio.h"
#include "ipcMessageQ.h"
#include "ipcStringList.h"
#include "ipcIDList.h"
#ifdef XP_WIN
#include <windows.h>
#endif
//-----------------------------------------------------------------------------
// ipcClient
//
// NOTE: this class is an implementation detail of the IPC daemon. IPC daemon
// modules (other than the built-in IPCM module) must not access methods on
// this class directly. use the API provided via ipcd.h instead.
//-----------------------------------------------------------------------------
class ipcClient
{
public:
void Init();
void Finalize();
PRUint32 ID() const { return mID; }
void AddName(const char *name);
void DelName(const char *name);
PRBool HasName(const char *name) const { return mNames.Find(name) != NULL; }
void AddTarget(const nsID &target);
void DelTarget(const nsID &target);
PRBool HasTarget(const nsID &target) const { return mTargets.Find(target) != NULL; }
// list iterators
const ipcStringNode *Names() const { return mNames.First(); }
const ipcIDNode *Targets() const { return mTargets.First(); }
// returns primary client name (the one specified in the "client hello" message)
const char *PrimaryName() const { return mNames.First() ? mNames.First()->Value() : NULL; }
void SetExpectsSyncReply(PRBool val) { mExpectsSyncReply = val; }
PRBool GetExpectsSyncReply() const { return mExpectsSyncReply; }
#ifdef XP_WIN
PRUint32 PID() const { return mPID; }
void SetPID(PRUint32 pid) { mPID = pid; }
HWND Hwnd() const { return mHwnd; }
void SetHwnd(HWND hwnd) { mHwnd = hwnd; }
#endif
#ifdef XP_UNIX
//
// called to process a client file descriptor. the value of pollFlags
// indicates the state of the socket.
//
// returns:
// 0 - to cancel client connection
// PR_POLL_READ - to poll for a readable socket
// PR_POLL_WRITE - to poll for a writable socket
// (both flags) - to poll for either a readable or writable socket
//
// the socket is non-blocking.
//
int Process(PRFileDesc *sockFD, int pollFlags);
//
// on success or failure, this function takes ownership of |msg| and will
// delete it when appropriate.
//
void EnqueueOutboundMsg(ipcMessage *msg) { mOutMsgQ.Append(msg); }
#endif
private:
static PRUint32 gLastID;
PRUint32 mID;
ipcStringList mNames;
ipcIDList mTargets;
PRBool mExpectsSyncReply;
#ifdef XP_WIN
// on windows, we store the PID of the client process to help us determine
// the client from which a message originated. each message has the PID
// encoded in it.
PRUint32 mPID;
// the hwnd of the client's message window.
HWND mHwnd;
#endif
#ifdef XP_UNIX
ipcMessage mInMsg; // buffer for incoming message
ipcMessageQ mOutMsgQ; // outgoing message queue
// keep track of the amount of the first message sent
PRUint32 mSendOffset;
// utility function for writing out messages.
int WriteMsgs(PRFileDesc *fd);
#endif
};
#endif // !ipcClientUnix_h__

View File

@@ -1,257 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdlib.h>
#include <string.h>
#include "ipcLog.h"
#include "ipcCommandModule.h"
#include "ipcModule.h"
#include "ipcClient.h"
#include "ipcMessage.h"
#include "ipcMessageUtils.h"
#include "ipcModuleReg.h"
#include "ipcd.h"
#include "ipcm.h"
struct ipcCommandModule
{
typedef void (* MsgHandler)(ipcClient *, const ipcMessage *);
//
// helpers
//
static char **
BuildStringArray(const ipcStringNode *nodes)
{
size_t count = 0;
const ipcStringNode *node;
for (node = nodes; node; node = node->mNext)
count++;
char **strs = (char **) calloc(count + 1, sizeof(char *));
if (!strs)
return NULL;
count = 0;
for (node = nodes; node; node = node->mNext, ++count)
strs[count] = (char *) node->Value();
return strs;
}
static nsID **
BuildIDArray(const ipcIDNode *nodes)
{
size_t count = 0;
const ipcIDNode *node;
for (node = nodes; node; node = node->mNext)
count++;
nsID **ids = (nsID **) calloc(count + 1, sizeof(nsID *));
if (!ids)
return NULL;
count = 0;
for (node = nodes; node; node = node->mNext, ++count)
ids[count] = (nsID *) &node->Value();
return ids;
}
//
// message handlers
//
static void
OnPing(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got PING\n"));
IPC_SendMsg(client, new ipcmMessagePing());
}
static void
OnClientHello(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got CLIENT_HELLO\n"));
IPC_SendMsg(client, new ipcmMessageClientID(client->ID()));
//
// NOTE: it would almost make sense for this notification to live
// in the transport layer code. however, clients expect to receive
// a CLIENT_ID as the first message following a CLIENT_HELLO, so we
// must not allow modules to see a client until after we have sent
// the CLIENT_ID message.
//
IPC_NotifyClientUp(client);
}
static void
OnClientAddName(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got CLIENT_ADD_NAME\n"));
ipcMessageCast<ipcmMessageClientAddName> msg(rawMsg);
const char *name = msg->Name();
if (name)
client->AddName(name);
}
static void
OnClientDelName(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got CLIENT_DEL_NAME\n"));
ipcMessageCast<ipcmMessageClientDelName> msg(rawMsg);
const char *name = msg->Name();
if (name)
client->DelName(name);
}
static void
OnClientAddTarget(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got CLIENT_ADD_TARGET\n"));
ipcMessageCast<ipcmMessageClientAddTarget> msg(rawMsg);
client->AddTarget(msg->Target());
}
static void
OnClientDelTarget(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got CLIENT_DEL_TARGET\n"));
ipcMessageCast<ipcmMessageClientDelTarget> msg(rawMsg);
client->DelTarget(msg->Target());
}
static void
OnQueryClientByName(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got QUERY_CLIENT_BY_NAME\n"));
ipcMessageCast<ipcmMessageQueryClientByName> msg(rawMsg);
ipcClient *result = IPC_GetClientByName(msg->Name());
if (result) {
LOG((" client exists w/ ID = %u\n", result->ID()));
IPC_SendMsg(client, new ipcmMessageClientID(result->ID()));
}
else {
LOG((" client does not exist\n"));
IPC_SendMsg(client, new ipcmMessageError(IPCM_ERROR_CLIENT_NOT_FOUND));
}
}
static void
OnQueryClientInfo(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got QUERY_CLIENT_INFO\n"));
ipcMessageCast<ipcmMessageQueryClientInfo> msg(rawMsg);
ipcClient *result = IPC_GetClientByID(msg->ClientID());
if (result) {
char **names = BuildStringArray(result->Names());
nsID **targets = BuildIDArray(result->Targets());
IPC_SendMsg(client, new ipcmMessageClientInfo(result->ID(),
(const char **) names,
(const nsID **) targets));
free(names);
free(targets);
}
else {
LOG((" client does not exist\n"));
IPC_SendMsg(client, new ipcmMessageError(IPCM_ERROR_CLIENT_NOT_FOUND));
}
}
static void
OnForward(ipcClient *client, const ipcMessage *rawMsg)
{
LOG(("got FORWARD\n"));
ipcMessageCast<ipcmMessageForward> msg(rawMsg);
ipcClient *dest = IPC_GetClientByID(msg->DestClientID());
if (!dest) {
LOG((" destination client not found!\n"));
return;
}
ipcMessage *newMsg = new ipcMessage(msg->InnerTarget(),
msg->InnerData(),
msg->InnerDataLen());
IPC_SendMsg(dest, newMsg);
}
};
void
IPCM_HandleMsg(ipcClient *client, const ipcMessage *rawMsg)
{
static ipcCommandModule::MsgHandler handlers[] =
{
ipcCommandModule::OnPing,
NULL, // ERROR
ipcCommandModule::OnClientHello,
NULL, // CLIENT_ID
NULL, // CLIENT_INFO
ipcCommandModule::OnClientAddName,
ipcCommandModule::OnClientDelName,
ipcCommandModule::OnClientAddTarget,
ipcCommandModule::OnClientDelTarget,
ipcCommandModule::OnQueryClientByName,
ipcCommandModule::OnQueryClientInfo,
ipcCommandModule::OnForward,
};
int type = IPCM_GetMsgType(rawMsg);
LOG(("IPCM_HandleMsg [type=%d]\n", type));
if (type < IPCM_MSG_TYPE_UNKNOWN) {
if (handlers[type]) {
ipcCommandModule::MsgHandler handler = handlers[type];
handler(client, rawMsg);
}
}
}

View File

@@ -1,48 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcCommandModule_h__
#define ipcCommandModule_h__
#include "ipcm.h" // for IPCM_TARGET
class ipcClient;
class ipcMessage;
void IPCM_HandleMsg(ipcClient *, const ipcMessage *);
#endif // !ipcCommandModule_h__

View File

@@ -1,242 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcModule_h__
#define ipcModule_h__
#include "nsID.h"
class ipcMessage;
//
// a client handle is used to efficiently reference a client instance object
// used by the daemon to represent a connection with a particular client app.
//
// modules should treat it as an opaque type.
//
typedef class ipcClient *ipcClientHandle;
//-----------------------------------------------------------------------------
// interface implemented by the module:
//-----------------------------------------------------------------------------
//
// the version of ipcModuleMethods data structure.
//
#define IPC_MODULE_METHODS_VERSION (1<<16) // 1.0
//
// each module defines the following structure:
//
struct ipcModuleMethods
{
//
// this field holds the version of the data structure, which is always the
// value of IPC_MODULE_METHODS_VERSION against which the module was built.
//
PRUint32 version;
//
// called after this module is registered.
//
void (* init) (void);
//
// called when this module will no longer be accessed.
//
void (* shutdown) (void);
//
// called when a new message arrives for this module.
//
// params:
// client - an opaque "handle" to an object representing the client that
// sent the message. modules should not store the value of this
// beyond the duration fo this function call. (e.g., the handle
// may be invalid after this function call returns.) modules
// wishing to hold onto a reference to a "client" should store
// the client's ID (see IPC_GetClientID).
// target - message target
// data - message data
// dataLen - message data length
//
void (* handleMsg) (ipcClientHandle client,
const nsID &target,
const void *data,
PRUint32 dataLen);
//
// called when a new client connects to the IPC daemon.
//
void (* clientUp) (ipcClientHandle client);
//
// called when a client disconnects from the IPC daemon.
//
void (* clientDown) (ipcClientHandle client);
};
//-----------------------------------------------------------------------------
// interface implemented by the daemon:
//-----------------------------------------------------------------------------
//
// the version of ipcDaemonMethods data structure.
//
#define IPC_DAEMON_METHODS_VERSION (1<<16) // 1.0
//
// enumeration functions may return FALSE to stop enumeration.
//
typedef PRBool (* ipcClientEnumFunc) (void *closure, ipcClientHandle client, PRUint32 clientID);
typedef PRBool (* ipcClientNameEnumFunc) (void *closure, ipcClientHandle client, const char *name);
typedef PRBool (* ipcClientTargetEnumFunc) (void *closure, ipcClientHandle client, const nsID &target);
//
// the daemon provides the following structure:
//
struct ipcDaemonMethods
{
PRUint32 version;
//
// called to send a message to another module.
//
// params:
// client - identifies the client from which this message originated.
// target - message target
// data - message data
// dataLen - message data length
//
// returns:
// PR_SUCCESS if message was dispatched.
// PR_FAILURE if message could not be dispatched (possibly because
// no module is registered for the given message target).
//
PRStatus (* dispatchMsg) (ipcClientHandle client,
const nsID &target,
const void *data,
PRUint32 dataLen);
//
// called to send a message to a particular client or to broadcast a
// message to all clients.
//
// params:
// client - if null, then broadcast message to all clients. otherwise,
// send message to the client specified.
// target - message target
// data - message data
// dataLen - message data length
//
// returns:
// PR_SUCCESS if message was sent (or queued up to be sent later).
// PR_FAILURE if message could not be sent (possibly because the client
// does not have a registered observer for the msg's target).
//
PRStatus (* sendMsg) (ipcClientHandle client,
const nsID &target,
const void *data,
PRUint32 dataLen);
//
// called to lookup a client handle given its client ID. each client has
// a unique ID.
//
ipcClientHandle (* getClientByID) (PRUint32 clientID);
//
// called to lookup a client by name or alias. names are not necessary
// unique to individual clients. this function returns the client first
// registered under the given name.
//
ipcClientHandle (* getClientByName) (const char *name);
//
// called to enumerate all clients.
//
void (* enumClients) (ipcClientEnumFunc func, void *closure);
//
// returns the client ID of the specified client.
//
PRUint32 (* getClientID) (ipcClientHandle client);
//
// functions for inspecting the names and targets defined for a particular
// client instance.
//
PRBool (* clientHasName) (ipcClientHandle client, const char *name);
PRBool (* clientHasTarget) (ipcClientHandle client, const nsID &target);
void (* enumClientNames) (ipcClientHandle client, ipcClientNameEnumFunc func, void *closure);
void (* enumClientTargets) (ipcClientHandle client, ipcClientTargetEnumFunc func, void *closure);
};
//-----------------------------------------------------------------------------
// interface exported by a DSO implementing one or more modules:
//-----------------------------------------------------------------------------
struct ipcModuleEntry
{
//
// identifies the message target of this module.
//
nsID target;
//
// module methods
//
ipcModuleMethods *methods;
};
//-----------------------------------------------------------------------------
#define IPC_EXPORT extern "C" NS_EXPORT
//
// IPC_EXPORT int IPC_GetModules(const ipcDaemonMethods *, const ipcModuleEntry **);
//
// params:
// methods - the daemon's methods
// entries - the module entries defined by the DSO
//
// returns:
// length of the |entries| array.
//
typedef int (* ipcGetModulesFunc) (const ipcDaemonMethods *methods, const ipcModuleEntry **entries);
#endif // !ipcModule_h__

View File

@@ -1,244 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <string.h>
#include <stdlib.h>
#include "prlink.h"
#include "prio.h"
#include "prlog.h"
#include "plstr.h"
#include "ipcConfig.h"
#include "ipcLog.h"
#include "ipcModuleReg.h"
#include "ipcModule.h"
#include "ipcCommandModule.h"
#include "ipcd.h"
//-----------------------------------------------------------------------------
struct ipcModuleRegEntry
{
nsID target;
ipcModuleMethods *methods;
PRLibrary *lib;
};
#define IPC_MAX_MODULE_COUNT 64
static ipcModuleRegEntry ipcModules[IPC_MAX_MODULE_COUNT];
static int ipcModuleCount = 0;
//-----------------------------------------------------------------------------
static PRStatus
AddModule(const nsID &target, ipcModuleMethods *methods, const char *libPath)
{
if (ipcModuleCount == IPC_MAX_MODULE_COUNT) {
LOG(("too many modules!\n"));
return PR_FAILURE;
}
if (!methods) {
PR_NOT_REACHED("null module methods");
return PR_FAILURE;
}
//
// each ipcModuleRegEntry holds a reference to a PRLibrary, and on
// shutdown, each PRLibrary reference will be released. this ensures
// that the library will not be unloaded until all of the modules in
// that library are shutdown.
//
ipcModules[ipcModuleCount].target = target;
ipcModules[ipcModuleCount].methods = methods;
ipcModules[ipcModuleCount].lib = PR_LoadLibrary(libPath);
++ipcModuleCount;
return PR_SUCCESS;
}
static void
InitModuleFromLib(const char *modulesDir, const char *fileName)
{
LOG(("InitModuleFromLib [%s]\n", fileName));
static const ipcDaemonMethods gDaemonMethods =
{
IPC_DAEMON_METHODS_VERSION,
IPC_DispatchMsg,
IPC_SendMsg,
IPC_GetClientByID,
IPC_GetClientByName,
IPC_EnumClients,
IPC_GetClientID,
IPC_ClientHasName,
IPC_ClientHasTarget,
IPC_EnumClientNames,
IPC_EnumClientTargets
};
int dLen = strlen(modulesDir);
int fLen = strlen(fileName);
char *buf = (char *) malloc(dLen + 1 + fLen + 1);
memcpy(buf, modulesDir, dLen);
buf[dLen] = IPC_PATH_SEP_CHAR;
memcpy(buf + dLen + 1, fileName, fLen);
buf[dLen + 1 + fLen] = '\0';
PRLibrary *lib = PR_LoadLibrary(buf);
if (lib) {
ipcGetModulesFunc func =
(ipcGetModulesFunc) PR_FindFunctionSymbol(lib, "IPC_GetModules");
LOG((" func=%p\n", (void*) func));
if (func) {
const ipcModuleEntry *entries = NULL;
int count = func(&gDaemonMethods, &entries);
for (int i=0; i<count; ++i) {
if (AddModule(entries[i].target, entries[i].methods, buf) == PR_SUCCESS) {
if (entries[i].methods->init)
entries[i].methods->init();
}
}
}
PR_UnloadLibrary(lib);
}
free(buf);
}
//-----------------------------------------------------------------------------
// ipcModuleReg API
//-----------------------------------------------------------------------------
void
IPC_InitModuleReg(const char *exePath)
{
if (!(exePath && *exePath))
return;
//
// register plug-in modules
//
char *p = PL_strrchr(exePath, IPC_PATH_SEP_CHAR);
if (p == NULL) {
LOG(("unexpected exe path\n"));
return;
}
int baseLen = p - exePath;
int finalLen = baseLen + 1 + sizeof(IPC_MODULES_DIR);
// build full path to ipc modules
char *modulesDir = (char*) malloc(finalLen);
memcpy(modulesDir, exePath, baseLen);
modulesDir[baseLen] = IPC_PATH_SEP_CHAR;
memcpy(modulesDir + baseLen + 1, IPC_MODULES_DIR, sizeof(IPC_MODULES_DIR));
LOG(("loading libraries in %s\n", modulesDir));
//
// scan directory for IPC modules
//
PRDir *dir = PR_OpenDir(modulesDir);
if (dir) {
PRDirEntry *ent;
while ((ent = PR_ReadDir(dir, PR_SKIP_BOTH)) != NULL) {
//
// locate extension, and check if dynamic library
//
char *p = strrchr(ent->name, '.');
if (p && PL_strcasecmp(p, MOZ_DLL_SUFFIX) == 0)
InitModuleFromLib(modulesDir, ent->name);
}
PR_CloseDir(dir);
}
free(modulesDir);
}
void
IPC_ShutdownModuleReg()
{
//
// shutdown modules in reverse order
//
while (ipcModuleCount) {
ipcModuleRegEntry &entry = ipcModules[--ipcModuleCount];
if (entry.methods->shutdown)
entry.methods->shutdown();
if (entry.lib)
PR_UnloadLibrary(entry.lib);
}
}
void
IPC_NotifyClientUp(ipcClient *client)
{
for (int i = 0; i < ipcModuleCount; ++i) {
ipcModuleRegEntry &entry = ipcModules[i];
if (entry.methods->clientUp)
entry.methods->clientUp(client);
}
}
void
IPC_NotifyClientDown(ipcClient *client)
{
for (int i = 0; i < ipcModuleCount; ++i) {
ipcModuleRegEntry &entry = ipcModules[i];
if (entry.methods->clientDown)
entry.methods->clientDown(client);
}
}
PRStatus
IPC_DispatchMsg(ipcClient *client, const nsID &target, const void *data, PRUint32 dataLen)
{
// dispatch message to every module registered under the given target.
for (int i=0; i<ipcModuleCount; ++i) {
ipcModuleRegEntry &entry = ipcModules[i];
if (entry.target.Equals(target)) {
if (entry.methods->handleMsg)
entry.methods->handleMsg(client, target, data, dataLen);
}
}
return PR_SUCCESS;
}

View File

@@ -1,70 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcModuleReg_h__
#define ipcModuleReg_h__
#include "ipcModule.h"
//
// called to init the module registry. this may only be called once at
// startup or once after calling IPC_ShutdownModuleReg.
//
// params:
// exePath - path to the daemon executable. modules are loaded from a
// directory relative to the daemon executable.
//
void IPC_InitModuleReg(const char *exePath);
//
// called to shutdown the module registry. this may be called more than
// once and need not follow a call to IPC_InitModuleReg.
//
void IPC_ShutdownModuleReg();
//
// returns the ipcModuleMethods for the given target.
//
ipcModuleMethods *IPC_GetModuleByTarget(const nsID &target);
//
// notifies all modules of client connect/disconnect
//
void IPC_NotifyClientUp(ipcClient *);
void IPC_NotifyClientDown(ipcClient *);
#endif // !ipcModuleReg_h__

View File

@@ -1,151 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcModuleUtil_h__
#define ipcModuleUtil_h__
#include "prlog.h"
#include "ipcModule.h"
extern const ipcDaemonMethods *gIPCDaemonMethods;
//-----------------------------------------------------------------------------
// inline wrapper functions
//
// these functions may only be called by a module that uses the
// IPC_IMPL_GETMODULES macro.
//-----------------------------------------------------------------------------
inline PRStatus
IPC_DispatchMsg(ipcClientHandle client, const nsID &target, const void *data, PRUint32 dataLen)
{
PR_ASSERT(gIPCDaemonMethods);
return gIPCDaemonMethods->dispatchMsg(client, target, data, dataLen);
}
inline PRStatus
IPC_SendMsg(ipcClientHandle client, const nsID &target, const void *data, PRUint32 dataLen)
{
PR_ASSERT(gIPCDaemonMethods);
return gIPCDaemonMethods->sendMsg(client, target, data, dataLen);
}
inline ipcClientHandle
IPC_GetClientByID(PRUint32 id)
{
PR_ASSERT(gIPCDaemonMethods);
return gIPCDaemonMethods->getClientByID(id);
}
inline ipcClientHandle
IPC_GetClientByName(const char *name)
{
PR_ASSERT(gIPCDaemonMethods);
return gIPCDaemonMethods->getClientByName(name);
}
inline void
IPC_EnumClients(ipcClientEnumFunc func, void *closure)
{
PR_ASSERT(gIPCDaemonMethods);
gIPCDaemonMethods->enumClients(func, closure);
}
inline PRUint32
IPC_GetClientID(ipcClientHandle client)
{
PR_ASSERT(gIPCDaemonMethods);
return gIPCDaemonMethods->getClientID(client);
}
inline PRBool
IPC_ClientHasName(ipcClientHandle client, const char *name)
{
PR_ASSERT(gIPCDaemonMethods);
return gIPCDaemonMethods->clientHasName(client, name);
}
inline PRBool
IPC_ClientHasTarget(ipcClientHandle client, const nsID &target)
{
PR_ASSERT(gIPCDaemonMethods);
return gIPCDaemonMethods->clientHasTarget(client, target);
}
inline void
IPC_EnumClientNames(ipcClientHandle client, ipcClientNameEnumFunc func, void *closure)
{
PR_ASSERT(gIPCDaemonMethods);
gIPCDaemonMethods->enumClientNames(client, func, closure);
}
inline void
IPC_EnumClientTargets(ipcClientHandle client, ipcClientTargetEnumFunc func, void *closure)
{
PR_ASSERT(gIPCDaemonMethods);
gIPCDaemonMethods->enumClientTargets(client, func, closure);
}
//-----------------------------------------------------------------------------
// inline composite functions
//-----------------------------------------------------------------------------
inline PRStatus
IPC_SendMsg(PRUint32 clientID, const nsID &target, const void *data, PRUint32 dataLen)
{
ipcClient *client = IPC_GetClientByID(clientID);
if (!client)
return PR_FAILURE;
return IPC_SendMsg(client, target, data, dataLen);
}
//-----------------------------------------------------------------------------
// module factory macros
//-----------------------------------------------------------------------------
#define IPC_IMPL_GETMODULES(_modName, _modEntries) \
const ipcDaemonMethods *gIPCDaemonMethods; \
IPC_EXPORT int \
IPC_GetModules(const ipcDaemonMethods *dmeths, \
const ipcModuleEntry **ents) { \
/* XXX do version checking */ \
gIPCDaemonMethods = dmeths; \
*ents = _modEntries; \
return sizeof(_modEntries) / sizeof(ipcModuleEntry); \
}
#endif // !ipcModuleUtil_h__

View File

@@ -1,187 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "prlog.h"
#include "ipcConfig.h"
#include "ipcLog.h"
#include "ipcMessage.h"
#include "ipcClient.h"
#include "ipcModuleReg.h"
#include "ipcModule.h"
#include "ipcCommandModule.h"
#include "ipcdPrivate.h"
#include "ipcd.h"
PRStatus
IPC_DispatchMsg(ipcClient *client, const ipcMessage *msg)
{
PR_ASSERT(client);
PR_ASSERT(msg);
// remember if client is expecting SYNC_REPLY. we'll add that flag to the
// next message sent to the client.
if (msg->TestFlag(IPC_MSG_FLAG_SYNC_QUERY)) {
PR_ASSERT(client->GetExpectsSyncReply() == PR_FALSE);
client->SetExpectsSyncReply(PR_TRUE);
}
if (msg->Target().Equals(IPCM_TARGET)) {
IPCM_HandleMsg(client, msg);
return PR_SUCCESS;
}
return IPC_DispatchMsg(client, msg->Target(), msg->Data(), msg->DataLen());
}
PRStatus
IPC_SendMsg(ipcClient *client, ipcMessage *msg)
{
PR_ASSERT(msg);
if (client == NULL) {
//
// broadcast
//
for (int i=0; i<ipcClientCount; ++i)
IPC_SendMsg(&ipcClients[i], msg->Clone());
delete msg;
return PR_SUCCESS;
}
// add SYNC_REPLY flag to message if client is expecting...
if (client->GetExpectsSyncReply()) {
msg->SetFlag(IPC_MSG_FLAG_SYNC_REPLY);
client->SetExpectsSyncReply(PR_FALSE);
}
if (client->HasTarget(msg->Target()))
return IPC_PlatformSendMsg(client, msg);
LOG((" no registered message handler\n"));
return PR_FAILURE;
}
//-----------------------------------------------------------------------------
// IPC daemon methods
//-----------------------------------------------------------------------------
PRStatus
IPC_SendMsg(ipcClient *client, const nsID &target, const void *data, PRUint32 dataLen)
{
return IPC_SendMsg(client, new ipcMessage(target, (const char *) data, dataLen));
}
ipcClient *
IPC_GetClientByID(PRUint32 clientID)
{
// linear search OK since number of clients should be small
for (int i = 0; i < ipcClientCount; ++i) {
if (ipcClients[i].ID() == clientID)
return &ipcClients[i];
}
return NULL;
}
ipcClient *
IPC_GetClientByName(const char *name)
{
// linear search OK since number of clients should be small
for (int i = 0; i < ipcClientCount; ++i) {
if (ipcClients[i].HasName(name))
return &ipcClients[i];
}
return NULL;
}
void
IPC_EnumClients(ipcClientEnumFunc func, void *closure)
{
PR_ASSERT(func);
for (int i = 0; i < ipcClientCount; ++i) {
if (func(closure, &ipcClients[i], ipcClients[i].ID()) == PR_FALSE)
break;
}
}
PRUint32
IPC_GetClientID(ipcClient *client)
{
PR_ASSERT(client);
return client->ID();
}
PRBool
IPC_ClientHasName(ipcClient *client, const char *name)
{
PR_ASSERT(client);
PR_ASSERT(name);
return client->HasName(name);
}
PRBool
IPC_ClientHasTarget(ipcClient *client, const nsID &target)
{
PR_ASSERT(client);
return client->HasTarget(target);
}
void
IPC_EnumClientNames(ipcClient *client, ipcClientNameEnumFunc func, void *closure)
{
PR_ASSERT(client);
PR_ASSERT(func);
const ipcStringNode *node = client->Names();
while (node) {
if (func(closure, client, node->Value()) == PR_FALSE)
break;
node = node->mNext;
}
}
void
IPC_EnumClientTargets(ipcClient *client, ipcClientTargetEnumFunc func, void *closure)
{
PR_ASSERT(client);
PR_ASSERT(func);
const ipcIDNode *node = client->Targets();
while (node) {
if (func(closure, client, node->Value()) == PR_FALSE)
break;
node = node->mNext;
}
}

View File

@@ -1,76 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef IPCD_H__
#define IPCD_H__
#include "ipcModule.h"
#include "ipcMessage.h"
//-----------------------------------------------------------------------------
// IPC daemon methods (see struct ipcDaemonMethods)
//
// these functions may only be called directly from within the daemon. plug-in
// modules must access these through the ipcDaemonMethods structure.
//-----------------------------------------------------------------------------
PRStatus IPC_DispatchMsg (ipcClientHandle client, const nsID &target, const void *data, PRUint32 dataLen);
PRStatus IPC_SendMsg (ipcClientHandle client, const nsID &target, const void *data, PRUint32 dataLen);
ipcClientHandle IPC_GetClientByID (PRUint32 id);
ipcClientHandle IPC_GetClientByName (const char *name);
void IPC_EnumClients (ipcClientEnumFunc func, void *closure);
PRUint32 IPC_GetClientID (ipcClientHandle client);
PRBool IPC_ClientHasName (ipcClientHandle client, const char *name);
PRBool IPC_ClientHasTarget (ipcClientHandle client, const nsID &target);
void IPC_EnumClientNames (ipcClientHandle client, ipcClientNameEnumFunc func, void *closure);
void IPC_EnumClientTargets (ipcClientHandle client, ipcClientTargetEnumFunc func, void *closure);
//-----------------------------------------------------------------------------
// other internal IPCD methods
//-----------------------------------------------------------------------------
//
// dispatch message
//
PRStatus IPC_DispatchMsg(ipcClientHandle client, const ipcMessage *msg);
//
// send message, takes ownership of |msg|.
//
PRStatus IPC_SendMsg(ipcClientHandle client, ipcMessage *msg);
#endif // !IPCD_H__

View File

@@ -1,23 +0,0 @@
#ifndef ipcdPrivate_h__
#define ipcdPrivate_h__
class ipcClient;
//
// upper limit on the number of active connections
// XXX may want to make this more dynamic
//
#define IPC_MAX_CLIENTS 100
//
// array of connected clients
//
extern ipcClient *ipcClients;
extern int ipcClientCount;
//
// platform specific send message function, takes ownership of |msg|.
//
PRStatus IPC_PlatformSendMsg(ipcClient *client, ipcMessage *msg);
#endif // !ipcdPrivate_h__

View File

@@ -1,439 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "prio.h"
#include "prerror.h"
#include "prthread.h"
#include "prinrval.h"
#include "plstr.h"
#include "prprf.h"
#include "ipcConfig.h"
#include "ipcLog.h"
#include "ipcMessage.h"
#include "ipcClient.h"
#include "ipcModuleReg.h"
#include "ipcdPrivate.h"
#include "ipcd.h"
void
IPC_Sleep(int seconds)
{
while (seconds > 0) {
LOG(("\rsleeping for %d seconds...", seconds));
PR_Sleep(PR_SecondsToInterval(1));
--seconds;
}
LOG(("\ndone sleeping\n"));
}
//-----------------------------------------------------------------------------
// ipc directory and locking...
//-----------------------------------------------------------------------------
static int ipcLockFD = 0;
static PRBool AcquireDaemonLock(const char *baseDir)
{
const char lockName[] = "lock";
int dirLen = strlen(baseDir);
int len = dirLen // baseDir
+ 1 // "/"
+ sizeof(lockName); // "lock"
char *lockFile = (char *) malloc(len);
memcpy(lockFile, baseDir, dirLen);
lockFile[dirLen] = '/';
memcpy(lockFile + dirLen + 1, lockName, sizeof(lockName));
//
// open lock file. it remains open until we shutdown.
//
ipcLockFD = open(lockFile, O_WRONLY|O_CREAT, S_IWUSR|S_IRUSR);
free(lockFile);
if (ipcLockFD == -1)
return PR_FALSE;
//
// we use fcntl for locking. assumption: filesystem should be local.
// this API is nice because the lock will be automatically released
// when the process dies. it will also be released when the file
// descriptor is closed.
//
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_start = 0;
lock.l_len = 0;
lock.l_whence = SEEK_SET;
if (fcntl(ipcLockFD, F_SETLK, &lock) == -1)
return PR_FALSE;
//
// truncate lock file once we have exclusive access to it.
//
ftruncate(ipcLockFD, 0);
//
// write our PID into the lock file (this just seems like a good idea...
// no real purpose otherwise).
//
char buf[32];
int nb = PR_snprintf(buf, sizeof(buf), "%u\n", (unsigned long) getpid());
write(ipcLockFD, buf, nb);
return PR_TRUE;
}
static PRBool InitDaemonDir(const char *socketPath)
{
LOG(("InitDaemonDir [sock=%s]\n", socketPath));
char *baseDir = PL_strdup(socketPath);
//
// make sure IPC directory exists (XXX this should be recursive)
//
char *p = strrchr(baseDir, '/');
if (p)
p[0] = '\0';
mkdir(baseDir, 0700);
//
// if we can't acquire the daemon lock, then another daemon
// must be active, so bail.
//
PRBool haveLock = AcquireDaemonLock(baseDir);
PL_strfree(baseDir);
if (haveLock) {
// delete an existing socket to prevent bind from failing.
unlink(socketPath);
}
return haveLock;
}
static void ShutdownDaemonDir()
{
LOG(("ShutdownDaemonDir\n"));
// deleting directory and files underneath it allows another process
// to think it has exclusive access. better to just leave the hidden
// directory in /tmp and let the OS clean it up via the usual tmpdir
// cleanup cron job.
// this removes the advisory lock, allowing other processes to acquire it.
if (ipcLockFD) {
close(ipcLockFD);
ipcLockFD = 0;
}
}
//-----------------------------------------------------------------------------
// poll list
//-----------------------------------------------------------------------------
//
// declared in ipcdPrivate.h
//
ipcClient *ipcClients = NULL;
int ipcClientCount = 0;
//
// the first element of this array is always zero; this is done so that the
// k'th element of ipcClientArray corresponds to the k'th element of
// ipcPollList.
//
static ipcClient ipcClientArray[IPC_MAX_CLIENTS + 1];
//
// element 0 contains the "server socket"
//
static PRPollDesc ipcPollList[IPC_MAX_CLIENTS + 1];
//-----------------------------------------------------------------------------
static int AddClient(PRFileDesc *fd)
{
if (ipcClientCount == IPC_MAX_CLIENTS) {
LOG(("reached maximum client limit\n"));
return -1;
}
int pollCount = ipcClientCount + 1;
ipcClientArray[pollCount].Init();
ipcPollList[pollCount].fd = fd;
ipcPollList[pollCount].in_flags = PR_POLL_READ;
ipcPollList[pollCount].out_flags = 0;
++ipcClientCount;
return 0;
}
static int RemoveClient(int clientIndex)
{
PRPollDesc *pd = &ipcPollList[clientIndex];
PR_Close(pd->fd);
ipcClientArray[clientIndex].Finalize();
//
// keep the clients and poll_fds contiguous; move the last one into
// the spot held by the one that is going away.
//
int toIndex = clientIndex;
int fromIndex = ipcClientCount;
if (fromIndex != toIndex) {
memcpy(&ipcClientArray[toIndex], &ipcClientArray[fromIndex], sizeof(ipcClient));
memcpy(&ipcPollList[toIndex], &ipcPollList[fromIndex], sizeof(PRPollDesc));
}
//
// zero out the old entries.
//
memset(&ipcClientArray[fromIndex], 0, sizeof(ipcClient));
memset(&ipcPollList[fromIndex], 0, sizeof(PRPollDesc));
--ipcClientCount;
return 0;
}
//-----------------------------------------------------------------------------
static void PollLoop(PRFileDesc *listenFD)
{
// the first element of ipcClientArray is unused.
memset(ipcClientArray, 0, sizeof(ipcClientArray));
ipcClients = ipcClientArray + 1;
ipcClientCount = 0;
ipcPollList[0].fd = listenFD;
ipcPollList[0].in_flags = PR_POLL_EXCEPT | PR_POLL_READ;
while (1) {
PRInt32 rv;
PRIntn i;
int pollCount = ipcClientCount + 1;
ipcPollList[0].out_flags = 0;
//
// poll
//
// timeout after 5 minutes. if no connections after timeout, then
// exit. this timeout ensures that we don't stay resident when no
// clients are interested in connecting after spawning the daemon.
//
// XXX add #define for timeout value
//
rv = PR_Poll(ipcPollList, pollCount, PR_SecondsToInterval(60 * 5));
if (rv == -1) {
LOG(("PR_Poll failed [%d]\n", PR_GetError()));
return;
}
if (rv > 0) {
//
// process clients that are ready
//
for (i = 1; i < pollCount; ++i) {
if (ipcPollList[i].out_flags != 0) {
ipcPollList[i].in_flags =
ipcClientArray[i].Process(ipcPollList[i].fd,
ipcPollList[i].out_flags);
ipcPollList[i].out_flags = 0;
}
}
//
// cleanup any dead clients (indicated by a zero in_flags)
//
for (i = pollCount - 1; i >= 1; --i) {
if (ipcPollList[i].in_flags == 0)
RemoveClient(i);
}
//
// check for new connection
//
if (ipcPollList[0].out_flags & PR_POLL_READ) {
LOG(("got new connection\n"));
PRNetAddr clientAddr;
memset(&clientAddr, 0, sizeof(clientAddr));
PRFileDesc *clientFD;
clientFD = PR_Accept(listenFD, &clientAddr, PR_INTERVAL_NO_WAIT);
if (clientFD == NULL) {
// ignore this error... perhaps the client disconnected.
LOG(("PR_Accept failed [%d]\n", PR_GetError()));
}
else {
// make socket non-blocking
PRSocketOptionData opt;
opt.option = PR_SockOpt_Nonblocking;
opt.value.non_blocking = PR_TRUE;
PR_SetSocketOption(clientFD, &opt);
if (AddClient(clientFD) != 0)
PR_Close(clientFD);
}
}
}
//
// shutdown if no clients
//
if (ipcClientCount == 0) {
LOG(("shutting down\n"));
break;
}
}
}
//-----------------------------------------------------------------------------
PRStatus
IPC_PlatformSendMsg(ipcClient *client, ipcMessage *msg)
{
LOG(("IPC_PlatformSendMsg\n"));
//
// must copy message onto send queue.
//
client->EnqueueOutboundMsg(msg);
//
// since our Process method may have already been called, we must ensure
// that the PR_POLL_WRITE flag is set.
//
int clientIndex = client - ipcClientArray;
ipcPollList[clientIndex].in_flags |= PR_POLL_WRITE;
return PR_SUCCESS;
}
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
PRFileDesc *listenFD = NULL;
PRNetAddr addr;
//
// ignore SIGINT so <ctrl-c> from terminal only kills the client
// which spawned this daemon.
//
signal(SIGINT, SIG_IGN);
// XXX block others? check cartman
// ensure strict file permissions
umask(0077);
IPC_InitLog("###");
LOG(("daemon started...\n"));
//XXX uncomment these lines to test slow starting daemon
//LOG(("sleeping for 2 seconds...\n"));
//PR_Sleep(PR_SecondsToInterval(2));
// set socket address
addr.local.family = PR_AF_LOCAL;
if (argc < 2)
IPC_GetDefaultSocketPath(addr.local.path, sizeof(addr.local.path));
else
PL_strncpyz(addr.local.path, argv[1], sizeof(addr.local.path));
if (!InitDaemonDir(addr.local.path)) {
LOG(("InitDaemonDir failed\n"));
goto end;
}
listenFD = PR_OpenTCPSocket(PR_AF_LOCAL);
if (!listenFD) {
LOG(("PR_OpenUDPSocket failed [%d]\n", PR_GetError()));
goto end;
}
if (PR_Bind(listenFD, &addr) != PR_SUCCESS) {
LOG(("PR_Bind failed [%d]\n", PR_GetError()));
goto end;
}
IPC_InitModuleReg(argv[0]);
if (PR_Listen(listenFD, 5) != PR_SUCCESS) {
LOG(("PR_Listen failed [%d]\n", PR_GetError()));
goto end;
}
PollLoop(listenFD);
end:
IPC_ShutdownModuleReg();
//IPC_Sleep(5);
// it is critical that we release the lock before closing the socket,
// otherwise, a client might launch another daemon that would be unable
// to acquire the lock and would then leave the client without a daemon.
ShutdownDaemonDir();
if (listenFD) {
LOG(("closing socket\n"));
PR_Close(listenFD);
}
return 0;
}

View File

@@ -1,392 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <windows.h>
#include "prthread.h"
#include "ipcConfig.h"
#include "ipcLog.h"
#include "ipcMessage.h"
#include "ipcClient.h"
#include "ipcModuleReg.h"
#include "ipcdPrivate.h"
#include "ipcd.h"
#include "ipcm.h"
//
// declared in ipcdPrivate.h
//
ipcClient *ipcClients = NULL;
int ipcClientCount = 0;
static ipcClient ipcClientArray[IPC_MAX_CLIENTS];
static HWND ipcHwnd = NULL;
static PRBool ipcShutdown = PR_FALSE;
#define IPC_PURGE_TIMER_ID 1
#define IPC_WM_SENDMSG (WM_USER + 1)
#define IPC_WM_SHUTDOWN (WM_USER + 2)
//-----------------------------------------------------------------------------
// client array manipulation
//-----------------------------------------------------------------------------
static void
RemoveClient(ipcClient *client)
{
LOG(("RemoveClient\n"));
int clientIndex = client - ipcClientArray;
client->Finalize();
//
// move last ipcClient object down into the spot occupied by this client.
//
int fromIndex = ipcClientCount - 1;
int toIndex = clientIndex;
if (toIndex != fromIndex)
memcpy(&ipcClientArray[toIndex], &ipcClientArray[fromIndex], sizeof(ipcClient));
memset(&ipcClientArray[fromIndex], 0, sizeof(ipcClient));
--ipcClientCount;
LOG((" num clients = %u\n", ipcClientCount));
if (ipcClientCount == 0) {
LOG((" shutting down...\n"));
KillTimer(ipcHwnd, IPC_PURGE_TIMER_ID);
PostQuitMessage(0);
ipcShutdown = PR_TRUE;
}
}
static void
PurgeStaleClients()
{
if (ipcClientCount == 0)
return;
LOG(("PurgeStaleClients [num-clients=%u]\n", ipcClientCount));
//
// walk the list of supposedly active clients, and verify the existance of
// their respective message windows.
//
char wName[IPC_CLIENT_WINDOW_NAME_MAXLEN];
for (int i=ipcClientCount-1; i>=0; --i) {
ipcClient *client = &ipcClientArray[i];
LOG((" checking client at index %u [client-id=%u pid=%u]\n",
i, client->ID(), client->PID()));
IPC_GetClientWindowName(client->PID(), wName);
// XXX dougt has ideas about how to make this better
HWND hwnd = FindWindow(IPC_CLIENT_WINDOW_CLASS, wName);
if (!hwnd) {
LOG((" client window not found; removing client!\n"));
RemoveClient(client);
}
}
}
static ipcClient *
AddClient(HWND hwnd, PRUint32 pid)
{
LOG(("AddClient\n"));
//
// before adding a new client, verify that all existing clients are
// still up and running. remove any stale clients.
//
PurgeStaleClients();
if (ipcClientCount == IPC_MAX_CLIENTS) {
LOG((" reached maximum client count!\n"));
return NULL;
}
ipcClient *client = &ipcClientArray[ipcClientCount];
client->Init();
client->SetHwnd(hwnd);
client->SetPID(pid); // XXX one function instead of 3
++ipcClientCount;
LOG((" num clients = %u\n", ipcClientCount));
if (ipcClientCount == 1)
SetTimer(ipcHwnd, IPC_PURGE_TIMER_ID, 1000, NULL);
return client;
}
static ipcClient *
GetClientByPID(PRUint32 pid)
{
for (int i=0; i<ipcClientCount; ++i) {
if (ipcClientArray[i].PID() == pid)
return &ipcClientArray[i];
}
return NULL;
}
//-----------------------------------------------------------------------------
// message processing
//-----------------------------------------------------------------------------
static void
ProcessMsg(HWND hwnd, PRUint32 pid, const ipcMessage *msg)
{
LOG(("ProcessMsg [pid=%u len=%u]\n", pid, msg->MsgLen()));
ipcClient *client = GetClientByPID(pid);
if (client) {
//
// if this is an IPCM "client hello" message, then reset the client
// instance object.
//
if (msg->Target().Equals(IPCM_TARGET) &&
IPCM_GetMsgType(msg) == IPCM_MSG_TYPE_CLIENT_HELLO) {
RemoveClient(client);
client = NULL;
}
}
if (client == NULL) {
client = AddClient(hwnd, pid);
if (!client)
return;
}
IPC_DispatchMsg(client, msg);
}
//-----------------------------------------------------------------------------
PRStatus
IPC_PlatformSendMsg(ipcClient *client, ipcMessage *msg)
{
LOG(("IPC_PlatformSendMsg [clientID=%u clientPID=%u]\n",
client->ID(), client->PID()));
// use PostMessage to make this asynchronous; otherwise we might get
// some wierd SendMessage recursion between processes.
WPARAM wParam = (WPARAM) client->Hwnd();
LPARAM lParam = (LPARAM) msg;
if (!PostMessage(ipcHwnd, IPC_WM_SENDMSG, wParam, lParam)) {
LOG(("PostMessage failed\n"));
delete msg;
return PR_FAILURE;
}
return PR_SUCCESS;
}
//-----------------------------------------------------------------------------
// windows message loop
//-----------------------------------------------------------------------------
static LRESULT CALLBACK
WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LOG(("got message [msg=%x wparam=%x lparam=%x]\n", uMsg, wParam, lParam));
if (uMsg == WM_COPYDATA) {
if (ipcShutdown) {
LOG(("ignoring message b/c daemon is shutting down\n"));
return TRUE;
}
COPYDATASTRUCT *cd = (COPYDATASTRUCT *) lParam;
if (cd && cd->lpData) {
ipcMessage msg;
PRUint32 bytesRead;
PRBool complete;
// XXX avoid extra malloc
PRStatus rv = msg.ReadFrom((const char *) cd->lpData, cd->cbData,
&bytesRead, &complete);
if (rv == PR_SUCCESS && complete) {
//
// grab client PID and hwnd.
//
ProcessMsg((HWND) wParam, (PRUint32) cd->dwData, &msg);
}
else
LOG(("ignoring malformed message\n"));
}
return TRUE;
}
if (uMsg == IPC_WM_SENDMSG) {
HWND hWndDest = (HWND) wParam;
ipcMessage *msg = (ipcMessage *) lParam;
COPYDATASTRUCT cd;
cd.dwData = GetCurrentProcessId();
cd.cbData = (DWORD) msg->MsgLen();
cd.lpData = (PVOID) msg->MsgBuf();
LOG(("calling SendMessage...\n"));
SendMessage(hWndDest, WM_COPYDATA, (WPARAM) hWnd, (LPARAM) &cd);
LOG((" done.\n"));
delete msg;
return 0;
}
if (uMsg == WM_TIMER) {
PurgeStaleClients();
return 0;
}
#if 0
if (uMsg == IPC_WM_SHUTDOWN) {
//
// since this message is handled asynchronously, it is possible
// that other clients may have come online since this was issued.
// in which case, we need to ignore this message.
//
if (ipcClientCount == 0) {
ipcShutdown = PR_TRUE;
PostQuitMessage(0);
}
return 0;
}
#endif
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
//-----------------------------------------------------------------------------
// daemon startup synchronization
//-----------------------------------------------------------------------------
static HANDLE ipcSyncEvent;
static PRBool
AcquireLock()
{
ipcSyncEvent = CreateEvent(NULL, FALSE, FALSE,
IPC_SYNC_EVENT_NAME);
if (!ipcSyncEvent) {
LOG(("CreateEvent failed [%u]\n", GetLastError()));
return PR_FALSE;
}
// check to see if event already existed prior to this call.
if (GetLastError() == ERROR_ALREADY_EXISTS) {
LOG((" lock already set; exiting...\n"));
return PR_FALSE;
}
LOG((" acquired lock\n"));
return PR_TRUE;
}
static void
ReleaseLock()
{
if (ipcSyncEvent) {
LOG(("releasing lock...\n"));
CloseHandle(ipcSyncEvent);
ipcSyncEvent = NULL;
}
}
//-----------------------------------------------------------------------------
// main
//-----------------------------------------------------------------------------
int
main(int argc, char **argv)
{
IPC_InitLog("###");
LOG(("daemon started...\n"));
if (!AcquireLock())
return 0;
// initialize global data
memset(ipcClientArray, 0, sizeof(ipcClientArray));
ipcClients = ipcClientArray;
ipcClientCount = 0;
// create message window up front...
WNDCLASS wc;
memset(&wc, 0, sizeof(wc));
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = IPC_WINDOW_CLASS;
RegisterClass(&wc);
ipcHwnd = CreateWindow(IPC_WINDOW_CLASS, IPC_WINDOW_NAME,
0, 0, 0, 10, 10, NULL, NULL, NULL, NULL);
if (!ipcHwnd)
return -1;
// load modules
IPC_InitModuleReg(argv[0]);
LOG(("entering message loop...\n"));
MSG msg;
while (GetMessage(&msg, ipcHwnd, 0, 0))
DispatchMessage(&msg);
// unload modules
IPC_ShutdownModuleReg();
//
// we release the daemon lock before destroying the window because the
// absence of our window is what will cause clients to try to spawn the
// daemon.
//
ReleaseLock();
//LOG(("sleeping 5 seconds...\n"));
//PR_Sleep(PR_SecondsToInterval(5));
LOG(("destroying message window...\n"));
DestroyWindow(ipcHwnd);
ipcHwnd = NULL;
LOG(("exiting\n"));
return 0;
}

View File

@@ -1,47 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = lock
include $(topsrcdir)/config/rules.mk

View File

@@ -1,47 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = public src
include $(topsrcdir)/config/rules.mk

View File

@@ -1,52 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = ipc
XPIDLSRCS = \
ipcILockService.idl \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,91 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsISupports.idl"
interface ipcILockNotify;
/**
* This service provides named interprocess locking with either synchronous
* or asynchronous waiting.
*/
[scriptable, uuid(9f6dbe15-d851-4b00-912a-5ac0be88a409)]
interface ipcILockService : nsISupports
{
/**
* Call this method to acquire a named lock. Pass a notification handler
* to be notified asynchronously when the lock is acquired. Otherwise,
* this function will block until the lock is acquired.
*
* @param aLockName
* specifies the name of the lock
* @param aNotify
* notification callback (NULL to synchronously acquire lock)
* @param aWaitIfBusy
* wait for the lock to become available; otherwise, fail if lock
* is already held by some other process.
*/
void acquireLock(in string aLockName,
in ipcILockNotify aNotify,
in boolean aWaitIfBusy);
/**
* Call this method to release a named lock. This method can be called
* before OnAcquireLockComplete has been called, which will effectively
* cancel the request to acquire the named lock. OnAcquireLockComplete
* will not be called after a call to ReleaseLock.
*
* @param aLockName
* specifies the name of the lock
*/
void releaseLock(in string aLockName);
};
[scriptable, uuid(b4ac1160-98a4-4030-aecc-01137a05c94b)]
interface ipcILockNotify : nsISupports
{
/**
* Called to complete a call to AcquireLock.
*
* @status aLockName
* specifies the name of the lock
* @status aStatus
* NS_OK if lock has been acquired; reason for failure otherwise.
*/
void onAcquireLockComplete(in string aLockName,
in nsresult aStatus);
};

View File

@@ -1,70 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
DIRS = module
MODULE = ipc
LIBRARY_NAME = ipclock_s
EXPORT_LIBRARY = 1
FORCE_STATIC_LIB = 1
MODULE_NAME = ipc
REQUIRES = \
xpcom \
string \
$(NULL)
CPPSRCS = \
ipcLockProtocol.cpp \
ipcLockService.cpp \
$(NULL)
LOCAL_INCLUDES = \
-I$(srcdir)/../../../common \
$(NULL)
EXPORTS = \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,50 +0,0 @@
#include <stdlib.h>
#include <string.h>
#include "prlog.h"
#include "ipcLockProtocol.h"
//-----------------------------------------------------------------------------
static inline PRUint8 get_opcode(const PRUint8 *buf)
{
return (buf[0] & 0x0f);
}
static inline PRUint8 get_flags(const PRUint8 *buf)
{
return (buf[0] & 0xf0) >> 4;
}
static inline const char *get_key(const PRUint8 *buf)
{
return ((const char *) buf) + 1;
}
//-----------------------------------------------------------------------------
PRUint8 *
IPC_FlattenLockMsg(const ipcLockMsg *msg, PRUint32 *bufLen)
{
PRUint32 len = 1 // header byte
+ strlen(msg->key) // key
+ 1; // null terminator
PRUint8 *buf = (PRUint8 *) malloc(len);
if (!buf)
return NULL;
buf[0] = (msg->opcode | (msg->flags << 4));
memcpy(&buf[1], msg->key, len - 1);
*bufLen = len;
return buf;
}
void
IPC_UnflattenLockMsg(const PRUint8 *buf, PRUint32 bufLen, ipcLockMsg *msg)
{
PR_ASSERT(bufLen > 2); // malformed buffer otherwise
msg->opcode = get_opcode(buf);
msg->flags = get_flags(buf);
msg->key = get_key(buf);
}

View File

@@ -1,60 +0,0 @@
#ifndef ipcLockProtocol_h__
#define ipcLockProtocol_h__
#include "prtypes.h"
//
// ipc lock message format:
//
// +----------------------------------+
// | opcode : 4 bits |
// +----------------------------------+
// | flags : 4 bits |
// +----------------------------------+
// | key : null terminated string |
// +----------------------------------+
//
// lock opcodes
#define IPC_LOCK_OP_ACQUIRE 1
#define IPC_LOCK_OP_RELEASE 2
#define IPC_LOCK_OP_STATUS_ACQUIRED 3
#define IPC_LOCK_OP_STATUS_FAILED 4
#define IPC_LOCK_OP_STATUS_BUSY 5
// lock flags
#define IPC_LOCK_FL_NONBLOCKING 1
// data structure for representing lock request message
struct ipcLockMsg
{
PRUint8 opcode;
PRUint8 flags;
const char * key;
};
//
// flatten a lock message
//
// returns a malloc'd buffer containing the flattened message. on return,
// bufLen contains the length of the flattened message.
//
PRUint8 *IPC_FlattenLockMsg(const ipcLockMsg *msg, PRUint32 *bufLen);
//
// unflatten a lock message
//
void IPC_UnflattenLockMsg(const PRUint8 *buf, PRUint32 bufLen, ipcLockMsg *msg);
//
// TargetID for message passing
//
#define IPC_LOCK_TARGETID \
{ /* 703ada8a-2d38-4d5d-9d39-03d1ccceb567 */ \
0x703ada8a, \
0x2d38, \
0x4d5d, \
{0x9d, 0x39, 0x03, 0xd1, 0xcc, 0xce, 0xb5, 0x67} \
}
#endif // !ipcLockProtocol_h__

View File

@@ -1,117 +0,0 @@
#include <stdlib.h>
#include "nsIServiceManager.h"
#include "ipcLockService.h"
#include "ipcLockProtocol.h"
#include "ipcCID.h"
#include "ipcLog.h"
static NS_DEFINE_IID(kIPCServiceCID, IPC_SERVICE_CID);
static const nsID kLockTargetID = IPC_LOCK_TARGETID;
ipcLockService::ipcLockService()
{
}
ipcLockService::~ipcLockService()
{
}
nsresult
ipcLockService::Init()
{
nsresult rv;
mIPCService = do_GetService(kIPCServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
return mIPCService->SetMessageObserver(kLockTargetID, this);
}
NS_IMPL_ISUPPORTS1(ipcLockService, ipcILockService)
NS_IMETHODIMP
ipcLockService::AcquireLock(const char *lockName, ipcILockNotify *notify, PRBool waitIfBusy)
{
LOG(("ipcLockService::AcquireLock [lock=%s sync=%u wait=%u]\n",
lockName, notify == nsnull, waitIfBusy));
ipcLockMsg msg;
msg.opcode = IPC_LOCK_OP_ACQUIRE;
msg.flags = (waitIfBusy ? 0 : IPC_LOCK_FL_NONBLOCKING);
msg.key = lockName;
PRUint32 bufLen;
PRUint8 *buf = IPC_FlattenLockMsg(&msg, &bufLen);
if (!buf)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = mIPCService->SendMessage(0, kLockTargetID, buf, bufLen, (notify == nsnull));
free(buf);
if (NS_FAILED(rv)) {
LOG((" SendMessage failed [rv=%x]\n", rv));
return rv;
}
if (notify) {
nsCStringKey hashKey(lockName);
mPendingTable.Put(&hashKey, notify);
}
return NS_OK;
}
NS_IMETHODIMP
ipcLockService::ReleaseLock(const char *lockName)
{
LOG(("ipcLockService::ReleaseLock [lock=%s]\n", lockName));
ipcLockMsg msg;
msg.opcode = IPC_LOCK_OP_RELEASE;
msg.flags = 0;
msg.key = lockName;
PRUint32 bufLen;
PRUint8 *buf = IPC_FlattenLockMsg(&msg, &bufLen);
if (!buf)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = mIPCService->SendMessage(0, kLockTargetID, buf, bufLen, PR_FALSE);
free(buf);
if (NS_FAILED(rv)) return rv;
nsCStringKey hashKey(lockName);
mPendingTable.Remove(&hashKey);
return NS_OK;
}
NS_IMETHODIMP
ipcLockService::OnMessageAvailable(const nsID &target, const PRUint8 *data, PRUint32 dataLen)
{
ipcLockMsg msg;
IPC_UnflattenLockMsg(data, dataLen, &msg);
LOG(("ipcLockService::OnMessageAvailable [lock=%s opcode=%u]\n", msg.key, msg.opcode));
nsresult status;
if (msg.opcode == IPC_LOCK_OP_STATUS_ACQUIRED)
status = NS_OK;
else
status = NS_ERROR_FAILURE;
NotifyComplete(msg.key, status);
return NS_OK;
}
void
ipcLockService::NotifyComplete(const char *lockName, nsresult status)
{
nsCStringKey hashKey(lockName);
nsISupports *obj = mPendingTable.Get(&hashKey); // ADDREFS
if (obj) {
nsCOMPtr<ipcILockNotify> notify = do_QueryInterface(obj);
NS_RELEASE(obj);
if (notify)
notify->OnAcquireLockComplete(lockName, status);
}
}

View File

@@ -1,32 +0,0 @@
#ifndef ipcLockService_h__
#define ipcLockService_h__
#include "ipcILockService.h"
#include "ipcIService.h"
#include "ipcList.h"
#include "nsCOMPtr.h"
#include "nsHashtable.h"
class ipcLockService : public ipcILockService
, public ipcIMessageObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_IPCILOCKSERVICE
NS_DECL_IPCIMESSAGEOBSERVER
ipcLockService();
virtual ~ipcLockService();
nsresult Init();
private:
void NotifyComplete(const char *lockName, nsresult status);
nsCOMPtr<ipcIService> mIPCService;
// map from lockname to locknotify for pending notifications
nsSupportsHashtable mPendingTable;
};
#endif // !ipcLockService_h__

View File

@@ -1,77 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = ipc
LIBRARY_NAME = lockmodule
EXPORT_LIBRARY = 1
MODULE_NAME = ipc
REQUIRES = xpcom \
$(NULL)
CPPSRCS = ipcLockModule.cpp
LOCAL_INCLUDES = \
-I$(srcdir)/.. \
$(NULL)
EXTRA_OBJS = ../ipcLockProtocol.$(OBJ_SUFFIX)
EXTRA_DSO_LDOPTS = \
$(LIBS_DIR) \
$(NSPR_LIBS) \
$(EXTRA_DSO_LIBS) \
$(EXTRA_OBJS) \
$(NULL)
include $(topsrcdir)/config/rules.mk
_IPC_FILES = \
$(LIB_PREFIX)$(LIBRARY_NAME)$(DLL_SUFFIX) \
$(NULL)
libs:: $(_IPC_FILES)
$(INSTALL) $^ $(DIST)/bin/ipc/modules
install:: $(_IPC_FILES)
$(SYSINSTALL) $(IFLAGS1) $^ $(DESTDIR)$(mozappdir)/ipc/modules

View File

@@ -1,238 +0,0 @@
#include <stdlib.h>
#include <stdio.h>
#include "ipcModuleUtil.h"
#include "ipcLockProtocol.h"
#include "plhash.h"
static const nsID kLockTargetID = IPC_LOCK_TARGETID;
static void
ipcLockModule_Send(PRUint32 cid, const char *key, PRUint8 opcode)
{
ipcLockMsg msg = { opcode, 0, key };
PRUint32 bufLen;
PRUint8 *buf = IPC_FlattenLockMsg(&msg, &bufLen);
if (!buf)
return;
IPC_SendMsg(cid, kLockTargetID, buf, bufLen);
free(buf);
}
//-----------------------------------------------------------------------------
//
// gLockTable stores mapping from lock name to ipcLockContext
//
static PLHashTable *gLockTable = NULL;
//-----------------------------------------------------------------------------
struct ipcLockContext
{
PRUint32 mOwnerID; // client ID of this lock's owner
struct ipcLockContext *mNextPending; // pointer to client next in line to
// acquire this lock.
ipcLockContext(PRUint32 ownerID)
: mOwnerID(ownerID)
, mNextPending(NULL) {}
};
static void
ipcLockModule_AcquireLock(PRUint32 cid, PRUint8 flags, const char *key)
{
printf("$$$ acquiring lock [key=%s]\n", key);
if (!gLockTable)
return;
ipcLockContext *ctx;
ctx = (ipcLockContext *) PL_HashTableLookup(gLockTable, key);
if (ctx) {
//
// lock is already acquired, add this client to the queue. make
// sure this client doesn't already own the lock or live on the queue.
//
while (ctx->mOwnerID != cid && ctx->mNextPending)
ctx = ctx->mNextPending;
if (ctx->mOwnerID != cid) {
//
// if nonblocking, then send busy status message. otherwise,
// proceed to add this client to the pending queue.
//
if (flags & IPC_LOCK_FL_NONBLOCKING)
ipcLockModule_Send(cid, key, IPC_LOCK_OP_STATUS_BUSY);
else
ctx->mNextPending = new ipcLockContext(cid);
}
}
else {
//
// ok, add this lock to the table, and notify client that it now owns
// the lock!
//
ctx = new ipcLockContext(cid);
if (!ctx)
return;
PL_HashTableAdd(gLockTable, key, ctx);
ipcLockModule_Send(cid, key, IPC_LOCK_OP_STATUS_ACQUIRED);
}
}
static void
ipcLockModule_ReleaseLock(PRUint32 cid, const char *key)
{
printf("$$$ releasing lock [key=%s]\n", key);
if (!gLockTable)
return;
ipcLockContext *ctx;
ctx = (ipcLockContext *) PL_HashTableLookup(gLockTable, key);
if (ctx) {
//
// lock is already acquired _or_ maybe client is on the pending list.
//
if (ctx->mOwnerID == cid) {
if (ctx->mNextPending) {
//
// remove this element from the list. since this is the
// first element in the list, instead of removing it we
// shift the data from the next context into this one and
// delete the next context.
//
ipcLockContext *next = ctx->mNextPending;
ctx->mOwnerID = next->mOwnerID;
ctx->mNextPending = next->mNextPending;
delete next;
//
// notify client that it now owns the lock
//
ipcLockModule_Send(ctx->mOwnerID, key, IPC_LOCK_OP_STATUS_ACQUIRED);
}
else {
delete ctx;
PL_HashTableRemove(gLockTable, key);
}
}
else {
ipcLockContext *prev;
for (;;) {
prev = ctx;
ctx = ctx->mNextPending;
if (!ctx)
break;
if (ctx->mOwnerID == cid) {
// remove ctx from list
prev->mNextPending = ctx->mNextPending;
delete ctx;
break;
}
}
}
}
}
PR_STATIC_CALLBACK(PRIntn)
ipcLockModule_ReleaseByCID(PLHashEntry *he, PRIntn i, void *arg)
{
PRUint32 cid = *(PRUint32 *) arg;
ipcLockModule_ReleaseLock(cid, (const char *) he->key);
return HT_ENUMERATE_NEXT;
}
//-----------------------------------------------------------------------------
static void
ipcLockModule_Init()
{
printf("$$$ ipcLockModule_Init\n");
gLockTable = PL_NewHashTable(32,
PL_HashString,
PL_CompareStrings,
PL_CompareValues,
NULL,
NULL);
}
static void
ipcLockModule_Shutdown()
{
printf("$$$ ipcLockModule_Shutdown\n");
if (gLockTable) {
// XXX walk table destroying all ipcLockContext objects
PL_HashTableDestroy(gLockTable);
gLockTable = NULL;
}
}
static void
ipcLockModule_HandleMsg(ipcClientHandle client,
const nsID &target,
const void *data,
PRUint32 dataLen)
{
PRUint32 cid = IPC_GetClientID(client);
printf("$$$ ipcLockModule_HandleMsg [cid=%u]\n", cid);
ipcLockMsg msg;
IPC_UnflattenLockMsg((const PRUint8 *) data, dataLen, &msg);
switch (msg.opcode) {
case IPC_LOCK_OP_ACQUIRE:
ipcLockModule_AcquireLock(cid, msg.flags, msg.key);
break;
case IPC_LOCK_OP_RELEASE:
ipcLockModule_ReleaseLock(cid, msg.key);
break;
default:
PR_NOT_REACHED("invalid opcode");
}
}
static void
ipcLockModule_ClientUp(ipcClientHandle client)
{
printf("$$$ ipcLockModule_ClientUp [%u]\n", IPC_GetClientID(client));
}
static void
ipcLockModule_ClientDown(ipcClientHandle client)
{
PRUint32 cid = IPC_GetClientID(client);
printf("$$$ ipcLockModule_ClientDown [%u]\n", cid);
//
// enumerate lock table, release any locks held by this client.
//
PL_HashTableEnumerateEntries(gLockTable, ipcLockModule_ReleaseByCID, &cid);
}
//-----------------------------------------------------------------------------
static ipcModuleMethods gLockMethods =
{
IPC_MODULE_METHODS_VERSION,
ipcLockModule_Init,
ipcLockModule_Shutdown,
ipcLockModule_HandleMsg,
ipcLockModule_ClientUp,
ipcLockModule_ClientDown
};
static ipcModuleEntry gLockModuleEntry[] =
{
{ IPC_LOCK_TARGETID, &gLockMethods }
};
IPC_IMPL_GETMODULES(ipcLockModule, gLockModuleEntry)

View File

@@ -1,52 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = ipc
XPIDLSRCS = \
ipcIService.idl \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,280 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsISupports.idl"
interface ipcIMessageObserver;
interface ipcIClientObserver;
interface ipcIClientQueryHandler;
/**
* ipcIService
*
* the IPC service provides the means to communicate with an external IPC
* daemon and/or other mozilla-based applications on the same physical system.
* the IPC daemon hosts modules (some builtin and others dynamically loaded)
* with which applications may interact.
*
* at application startup, the IPC service will attempt to establish a
* connection with the IPC daemon. the IPC daemon will be automatically
* started if necessary. when a connection has been established, the IPC
* service will enumerate the "ipc-startup-category" and broadcast an
* "ipc-startup" notification using the observer service.
*
* when the connection to the IPC daemon is closed, an "ipc-shutdown"
* notification will be broadcast.
*
* each client has a name. the client name need not be unique across all
* clients, but it is usually good if it is. the IPC service does not require
* unique names. instead, the IPC daemon assigns each client a unique ID that
* is good for the current "session." clients can query other clients by name
* or by ID. the IPC service supports forwarding messages from one client to
* another via the IPC daemon.
*
* for performance reasons, this system should not be used to transfer large
* amounts of data. instead, applications may choose to utilize shared memory,
* and rely on the IPC service for synchronization and small message transfer
* only.
*/
[scriptable, uuid(53d3e3a7-528f-4b09-9eab-9416272568c0)]
interface ipcIService : nsISupports
{
/**************************************************************************
* properties of this process
*/
/**
* returns the "client ID" assigned to this process by the IPC daemon.
*
* @throws NS_ERROR_NOT_AVAILABLE if no connection to the IPC daemon.
*/
readonly attribute unsigned long clientID;
/**
* this process can appear under several client names. use the following
* methods to add or remove names for this process.
*
* for example, the mozilla browser might have the primary name "mozilla",
* but it could also register itself under the names "browser", "mail",
* "news", "addrbook", etc. other IPC clients can then query the IPC
* daemon for the client named "mail" in order to talk with a mail program.
*
* XXX An IPC client name resembles a XPCOM contract ID.
*/
void addClientName(in string aName);
void removeClientName(in string aName);
/**************************************************************************
* client query methods
*/
/**
* query info about a particular client given its client name. the
* observer's onClientInfo method is called with the result of the lookup,
* or if there is no client matching the given name, the observer's
* onClientDown method will be called instead.
*
* @param aName
* the name of the client being queried.
* @param aHandler
* the handler to be notified with result.
* @param aSync
* block the calling thread until the query completes.
*
* @return integer value identifying this query.
*/
unsigned long queryClientByName(in string aName,
in ipcIClientQueryHandler aHandler,
in boolean aSync);
/**
* query info about a particular client given its client ID. the observer's
* onClientInfo method is called with the result of the lookup, or if there
* is no client matching the given name, the observer's onClientDown method
* will be called instead.
*
* @param aClientID
* the ID of the client being queried.
* @param aHandler
* the handler to be notified with result.
* @param aSync
* block the calling thread until the query completes.
*
* @return integer value identifying this query.
*/
unsigned long queryClientByID(in unsigned long aClientID,
in ipcIClientQueryHandler aHandler,
in boolean aSync);
/**
* called to cancel a pending query.
*
* @param aQueryID
* the return value from one of the "query" methods.
*/
void cancelQuery(in unsigned long aQueryID);
/**
* set client observer. observer's onClientUp method is called whenever
* a new client comes online, and the observer's onClientDown method is
* called whenever a client goes offline.
*
* @param aObserver
* the client observer.
*/
void setClientObserver(in ipcIClientObserver aObserver);
// XXX need other functions to enumerate clients, clients implementing targets, etc.
/**************************************************************************
* message methods
*/
/**
* set a message observer for a particular message target.
*
* @param aTarget
* the message target being observed. any existing observer will
* be replaced.
* @param aObserver
* the message observer to receive incoming messages for the
* specified target. pass null to remove the existing observer.
*/
void setMessageObserver(in nsIDRef aTarget, in ipcIMessageObserver aObserver);
/**
* send message asynchronously to a client or a module in the IPC daemon.
* there is no guarantee that the message will be delivered.
*
* @param aClientID
* the client ID of the foreign application that should receive this
* message. pass 0 to send a message to a module in the IPC daemon.
* @param aTarget
* the target of the message. if aClientID is 0, then this is the
* ID of the daemon module that should receive this message.
* @param aData
* the message data.
* @param aDataLen
* the message length.
* @param aSync
* block the calling thread until a response to this message is
* received.
*/
void sendMessage(in unsigned long aClientID,
in nsIDRef aTarget,
[array, const, size_is(aDataLen)]
in octet aData,
in unsigned long aDataLen,
in boolean aSync);
};
/**
* ipcIMessageObserver
*/
[scriptable, uuid(e40a4a3c-2dc1-470e-ab7f-5675fe1f1384)]
interface ipcIMessageObserver : nsISupports
{
/**
* @param aTarget
* the target of the message, corresponding to the target this
* observer was registered under. this parameter is passed to allow
* an observer instance to receive messages for more than one target.
* @param aData
* the data of the message.
* @param aDataLen
* the data length of the message.
*/
void onMessageAvailable(in nsIDRef aTarget,
[array, const, size_is(aDataLen)]
in octet aData,
in unsigned long aDataLen);
};
/**
* ipcIClientObserver
*/
[scriptable, uuid(42283079-030c-4b13-b069-a08b7ad5eab2)]
interface ipcIClientObserver : nsISupports
{
const unsigned long CLIENT_UP = 1;
const unsigned long CLIENT_DOWN = 2;
void onClientStatus(in unsigned long aClientID,
in unsigned long aClientStatus);
};
/**
* ipcIClientQueryHandler
*
* the methods on this interface are called when the result of a client query
* becomes available.
*/
[scriptable, uuid(6fefea5c-f747-4bb0-972f-2a7b363a01db)]
interface ipcIClientQueryHandler : nsISupports
{
/**
* called on completion of a client query.
*
* @param aQueryID
* the return value from one of the "query" methods.
* @param aStatus
* the status of the query. if this is a failure code, then the
* query failed, otherwise the query succeeded. the value of this
* parameter explains the reason for any failure.
* @param aClientID
* ...
*/
void onQueryComplete(in unsigned long aQueryID,
in nsresult aStatus,
in unsigned long aClientID,
[array, size_is(aNameCount)]
in string aClientNames,
in unsigned long aNameCount,
[array, const, size_is(aTargetCount)]
in nsIDPtr aClientTargets,
in unsigned long aTargetCount);
};
%{C++
#define IPC_SERVICE_STARTUP_CATEGORY "ipc-startup-category"
#define IPC_SERVICE_STARTUP_TOPIC "ipc-startup"
#define IPC_SERVICE_SHUTDOWN_TOPIC "ipc-shutdown"
#define IPC_SERVICE_PREF_PRIMARY_CLIENT_NAME "ipc.primary-client-name"
%}

View File

@@ -1,73 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = ipc
LIBRARY_NAME = ipc_s
EXPORT_LIBRARY = 1
FORCE_STATIC_LIB = 1
MODULE_NAME = ipc
REQUIRES = \
xpcom \
string \
necko \
$(NULL)
CPPSRCS = \
ipcService.cpp \
ipcTransport.cpp \
$(NULL)
ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
CPPSRCS += ipcTransportWin.cpp
else
CPPSRCS += ipcTransportUnix.cpp
CPPSRCS += ipcSocketProviderUnix.cpp
endif
LOCAL_INCLUDES = \
-I$(srcdir)/../common \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,556 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdlib.h>
#include "plstr.h"
#include "nsIServiceManager.h"
#include "nsIEventQueueService.h"
#include "nsIEventQueue.h"
#include "nsIObserverService.h"
#include "nsICategoryManager.h"
#include "nsCategoryManagerUtils.h"
#include "nsNetError.h"
#include "nsEventQueueUtils.h"
#include "ipcConfig.h"
#include "ipcLog.h"
#include "ipcService.h"
#include "ipcMessageUtils.h"
#include "ipcm.h"
//-----------------------------------------------------------------------------
// helpers
//-----------------------------------------------------------------------------
static PRBool PR_CALLBACK
ipcReleaseMessageObserver(nsHashKey *aKey, void *aData, void* aClosure)
{
ipcIMessageObserver *obs = (ipcIMessageObserver *) aData;
NS_RELEASE(obs);
return PR_TRUE;
}
//----------------------------------------------------------------------------
// ipcClientQuery
//----------------------------------------------------------------------------
class ipcClientQuery
{
public:
ipcClientQuery(PRUint32 cID, ipcIClientQueryHandler *handler)
: mNext(nsnull)
, mQueryID(++gLastQueryID)
, mClientID(cID)
, mHandler(handler)
{ }
static PRUint32 gLastQueryID;
void SetClientID(PRUint32 cID) { mClientID = cID; }
void OnQueryComplete(nsresult status, const ipcmMessageClientInfo *msg);
PRUint32 QueryID() { return mQueryID; }
PRBool IsCanceled() { return mHandler.get() == NULL; }
ipcClientQuery *mNext;
private:
PRUint32 mQueryID;
PRUint32 mClientID;
nsCOMPtr<ipcIClientQueryHandler> mHandler;
};
PRUint32 ipcClientQuery::gLastQueryID = 0;
void
ipcClientQuery::OnQueryComplete(nsresult status, const ipcmMessageClientInfo *msg)
{
NS_ASSERTION(mHandler, "no handler");
PRUint32 nameCount = 0;
PRUint32 targetCount = 0;
const char **names = NULL;
const nsID **targets = NULL;
if (NS_SUCCEEDED(status)) {
nameCount = msg->NameCount();
targetCount = msg->TargetCount();
PRUint32 i;
names = (const char **) malloc(nameCount * sizeof(char *));
const char *lastName = NULL;
for (i = 0; i < nameCount; ++i) {
lastName = msg->NextName(lastName);
names[i] = lastName;
}
targets = (const nsID **) malloc(targetCount * sizeof(nsID *));
const nsID *lastTarget = NULL;
for (i = 0; i < targetCount; ++i) {
lastTarget = msg->NextTarget(lastTarget);
targets[i] = lastTarget;
}
}
mHandler->OnQueryComplete(mQueryID,
status,
mClientID,
names, nameCount,
targets, targetCount);
mHandler = NULL;
if (names)
free(names);
if (targets)
free(targets);
}
//-----------------------------------------------------------------------------
// ipcService
//-----------------------------------------------------------------------------
ipcService::ipcService()
: mTransport(nsnull)
, mClientID(0)
#if 0
, mDelayedMsgQ(nsnull)
, mWaiting(PR_FALSE)
, mInWaitMessage(PR_FALSE)
#endif
{
NS_INIT_ISUPPORTS();
IPC_InitLog(">>>");
}
ipcService::~ipcService()
{
NS_ASSERTION(mTransport == nsnull, "no xpcom-shutdown event??");
}
nsresult
ipcService::Init()
{
nsresult rv;
nsCOMPtr<nsIObserverService> observ(do_GetService("@mozilla.org/observer-service;1"));
if (observ) {
observ->AddObserver(this, "xpcom-shutdown", PR_FALSE);
observ->AddObserver(this, "profile-change-net-teardown", PR_FALSE);
observ->AddObserver(this, "profile-change-net-restore", PR_FALSE);
}
mTransport = new ipcTransport();
if (!mTransport)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(mTransport);
rv = mTransport->Init(this);
if (NS_FAILED(rv)) return rv;
return NS_OK;
}
void
ipcService::OnIPCMClientID(const ipcmMessageClientID *msg)
{
LOG(("ipcService::OnIPCMClientID\n"));
ipcClientQuery *query = mQueryQ.First();
if (!query) {
NS_WARNING("no pending query; ignoring message.");
return;
}
PRUint32 cID = msg->ClientID();
PRBool sync = msg->TestFlag(IPC_MSG_FLAG_SYNC_REPLY);
//
// (1) store client ID in query
// (2) move query to end of queue
// (3) issue CLIENT_INFO request
//
query->SetClientID(cID);
mQueryQ.RemoveFirst();
mQueryQ.Append(query);
mTransport->SendMsg(new ipcmMessageQueryClientInfo(cID), sync);
}
void
ipcService::OnIPCMClientInfo(const ipcmMessageClientInfo *msg)
{
LOG(("ipcService::OnIPCMClientInfo\n"));
ipcClientQuery *query = mQueryQ.First();
if (!query) {
NS_WARNING("no pending query; ignoring message.");
return;
}
if (!query->IsCanceled())
query->OnQueryComplete(NS_OK, msg);
mQueryQ.DeleteFirst();
}
void
ipcService::OnIPCMError(const ipcmMessageError *msg)
{
LOG(("ipcService::OnIPCMError [reason=0x%08x]\n", msg->Reason()));
ipcClientQuery *query = mQueryQ.First();
if (!query) {
NS_WARNING("no pending query; ignoring message.");
return;
}
if (!query->IsCanceled())
query->OnQueryComplete(NS_ERROR_FAILURE, NULL);
mQueryQ.DeleteFirst();
}
//-----------------------------------------------------------------------------
ipcService::
ProcessDelayedMsgQ_Event::ProcessDelayedMsgQ_Event(ipcService *serv,
ipcMessageQ *msgQ)
{
NS_ADDREF(mServ = serv);
mMsgQ = msgQ;
}
ipcService::
ProcessDelayedMsgQ_Event::~ProcessDelayedMsgQ_Event()
{
NS_RELEASE(mServ);
}
void * PR_CALLBACK
ipcService::ProcessDelayedMsgQ_EventHandler(PLEvent *plevent)
{
LOG(("ipcService::ProcessDelayedMsgQ_EventHandler\n"));
ProcessDelayedMsgQ_Event *ev = (ProcessDelayedMsgQ_Event *) plevent;
while (!ev->mMsgQ->IsEmpty()) {
ipcMessage *msg = ev->mMsgQ->First();
ev->mMsgQ->RemoveFirst();
ev->mServ->OnMessageAvailable(msg);
delete msg;
}
return nsnull;
}
void PR_CALLBACK
ipcService::ProcessDelayedMsgQ_EventCleanup(PLEvent *plevent)
{
delete (ProcessDelayedMsgQ_Event *) plevent;
}
//-----------------------------------------------------------------------------
// interface impl
//-----------------------------------------------------------------------------
NS_IMPL_ISUPPORTS2(ipcService, ipcIService, nsIObserver)
NS_IMETHODIMP
ipcService::GetClientID(PRUint32 *clientID)
{
if (mClientID == 0)
return NS_ERROR_NOT_AVAILABLE;
*clientID = mClientID;
return NS_OK;
}
NS_IMETHODIMP
ipcService::AddClientName(const char *name)
{
NS_ENSURE_TRUE(mTransport, NS_ERROR_NOT_INITIALIZED);
ipcMessage *msg = new ipcmMessageClientAddName(name);
if (!msg)
return NS_ERROR_OUT_OF_MEMORY;
return mTransport->SendMsg(msg);
}
NS_IMETHODIMP
ipcService::RemoveClientName(const char *name)
{
NS_ENSURE_TRUE(mTransport, NS_ERROR_NOT_INITIALIZED);
ipcMessage *msg = new ipcmMessageClientDelName(name);
if (!msg)
return NS_ERROR_OUT_OF_MEMORY;
return mTransport->SendMsg(msg);
}
NS_IMETHODIMP
ipcService::QueryClientByName(const char *name,
ipcIClientQueryHandler *handler,
PRBool sync,
PRUint32 *queryID)
{
if (!mTransport)
return NS_ERROR_NOT_AVAILABLE;
ipcMessage *msg;
msg = new ipcmMessageQueryClientByName(name);
if (!msg)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv;
rv = mTransport->SendMsg(msg, sync);
if (NS_FAILED(rv)) return rv;
ipcClientQuery *query = new ipcClientQuery(0, handler);
if (queryID)
*queryID = query->QueryID();
mQueryQ.Append(query);
return NS_OK;
}
NS_IMETHODIMP
ipcService::QueryClientByID(PRUint32 clientID,
ipcIClientQueryHandler *handler,
PRBool sync,
PRUint32 *queryID)
{
if (!mTransport)
return NS_ERROR_NOT_AVAILABLE;
ipcMessage *msg;
msg = new ipcmMessageQueryClientInfo(clientID);
if (!msg)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv;
rv = mTransport->SendMsg(msg, sync);
if (NS_FAILED(rv)) return rv;
ipcClientQuery *query = new ipcClientQuery(clientID, handler);
if (queryID)
*queryID = query->QueryID();
mQueryQ.Append(query);
return NS_OK;
}
NS_IMETHODIMP
ipcService::CancelQuery(PRUint32 queryID)
{
ipcClientQuery *query = mQueryQ.First();
while (query) {
if (query->QueryID() == queryID) {
query->OnQueryComplete(NS_BINDING_ABORTED, NULL);
break;
}
query = query->mNext;
}
return NS_OK;
}
NS_IMETHODIMP
ipcService::SetClientObserver(ipcIClientObserver *observer)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
ipcService::SetMessageObserver(const nsID &target, ipcIMessageObserver *observer)
{
NS_ENSURE_TRUE(mTransport, NS_ERROR_NOT_INITIALIZED);
nsIDKey key(target);
PRBool sendAdd = PR_TRUE;
ipcIMessageObserver *cobs = (ipcIMessageObserver *) mObserverDB.Get(&key);
if (cobs) {
NS_RELEASE(cobs);
if (!observer) {
mObserverDB.Remove(&key);
//
// send CLIENT_DEL_TARGET
//
mTransport->SendMsg(new ipcmMessageClientDelTarget(target));
return NS_OK;
}
sendAdd = PR_FALSE;
}
if (observer) {
NS_ADDREF(observer);
mObserverDB.Put(&key, observer);
if (sendAdd) {
//
// send CLIENT_ADD_TARGET
//
mTransport->SendMsg(new ipcmMessageClientAddTarget(target));
}
}
return NS_OK;
}
NS_IMETHODIMP
ipcService::SendMessage(PRUint32 clientID,
const nsID &target,
const PRUint8 *data,
PRUint32 dataLen,
PRBool sync)
{
NS_ENSURE_TRUE(mTransport, NS_ERROR_NOT_INITIALIZED);
if (target.Equals(IPCM_TARGET)) {
NS_ERROR("do not try to talk to the IPCM target directly");
return NS_ERROR_INVALID_ARG;
}
ipcMessage *msg;
if (clientID)
msg = new ipcmMessageForward(clientID, target, (const char *) data, dataLen);
else
msg = new ipcMessage(target, (const char *) data, dataLen);
if (!msg)
return NS_ERROR_OUT_OF_MEMORY;
return mTransport->SendMsg(msg, sync);
}
//-----------------------------------------------------------------------------
// nsIObserver impl
//-----------------------------------------------------------------------------
NS_IMETHODIMP
ipcService::Observe(nsISupports *subject, const char *topic, const PRUnichar *data)
{
if (strcmp(topic, "xpcom-shutdown") == 0 ||
strcmp(topic, "profile-change-net-teardown") == 0) {
// disconnect any message observers
mObserverDB.Reset(ipcReleaseMessageObserver, nsnull);
// drop daemon connection
if (mTransport)
mTransport->Shutdown();
}
else if (strcmp(topic, "profile-change-net-restore") == 0) {
if (mTransport)
mTransport->Init(this);
}
return NS_OK;
}
//-----------------------------------------------------------------------------
// ipcTransportObserver impl
//-----------------------------------------------------------------------------
void
ipcService::OnConnectionEstablished(PRUint32 clientID)
{
mClientID = clientID;
//
// enumerate ipc startup category...
//
NS_CreateServicesFromCategory(IPC_SERVICE_STARTUP_CATEGORY,
NS_STATIC_CAST(ipcIService *, this),
IPC_SERVICE_STARTUP_TOPIC);
}
void
ipcService::OnConnectionLost()
{
mClientID = 0;
//
// error out any pending queries
//
while (mQueryQ.First()) {
ipcClientQuery *query = mQueryQ.First();
query->OnQueryComplete(NS_BINDING_ABORTED, NULL);
mQueryQ.DeleteFirst();
}
//
// broadcast ipc shutdown...
//
nsCOMPtr<nsIObserverService> observ(
do_GetService("@mozilla.org/observer-service;1"));
if (observ)
observ->NotifyObservers(NS_STATIC_CAST(ipcIService *, this),
IPC_SERVICE_SHUTDOWN_TOPIC, nsnull);
}
void
ipcService::OnMessageAvailable(const ipcMessage *msg)
{
LOG(("ipcService::OnMessageAvailable [msg=%p]\n", msg));
if (msg->Target().Equals(IPCM_TARGET)) {
//
// all IPCM messages stop here.
//
PRUint32 type = IPCM_GetMsgType(msg);
switch (type) {
case IPCM_MSG_TYPE_CLIENT_ID:
OnIPCMClientID((const ipcmMessageClientID *) msg);
break;
case IPCM_MSG_TYPE_CLIENT_INFO:
OnIPCMClientInfo((const ipcmMessageClientInfo *) msg);
break;
case IPCM_MSG_TYPE_ERROR:
OnIPCMError((const ipcmMessageError *) msg);
break;
}
}
else {
nsIDKey key(msg->Target());
ipcIMessageObserver *observer = (ipcIMessageObserver *) mObserverDB.Get(&key);
if (observer)
observer->OnMessageAvailable(msg->Target(),
(const PRUint8 *) msg->Data(),
msg->DataLen());
}
}

View File

@@ -1,110 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcService_h__
#define ipcService_h__
#include "nsIRequest.h"
#include "nsCOMPtr.h"
#include "nsHashtable.h"
#include "plevent.h"
#include "ipcIService.h"
#include "ipcTransport.h"
#include "ipcList.h"
#include "ipcMessage.h"
#include "ipcMessageQ.h"
#include "ipcm.h"
typedef ipcList<class ipcClientQuery> ipcClientQueryQ;
//----------------------------------------------------------------------------
// ipcService
//----------------------------------------------------------------------------
class ipcService : public ipcIService
, public ipcTransportObserver
, public nsIObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_IPCISERVICE
NS_DECL_NSIOBSERVER
ipcService();
virtual ~ipcService();
nsresult Init();
// ipcTransportObserver:
void OnConnectionEstablished(PRUint32 clientID);
void OnConnectionLost();
void OnMessageAvailable(const ipcMessage *);
//PRBool InWaitMessage() { return mInWaitMessage; }
private:
nsresult ErrorAccordingToIPCM(PRUint32 err);
void OnIPCMClientID(const ipcmMessageClientID *);
void OnIPCMClientInfo(const ipcmMessageClientInfo *);
void OnIPCMError(const ipcmMessageError *);
struct ProcessDelayedMsgQ_Event : PLEvent {
ProcessDelayedMsgQ_Event(ipcService *, ipcMessageQ *);
~ProcessDelayedMsgQ_Event();
ipcService *mServ;
ipcMessageQ *mMsgQ;
};
PR_STATIC_CALLBACK(void*) ProcessDelayedMsgQ_EventHandler(PLEvent *);
PR_STATIC_CALLBACK(void) ProcessDelayedMsgQ_EventCleanup(PLEvent *);
nsHashtable mObserverDB;
ipcTransport *mTransport;
PRUint32 mClientID;
ipcClientQueryQ mQueryQ;
#if 0
// WaitMessage support
ipcMessageQ *mDelayedMsgQ;
nsID mWaitingTarget;
PRPackedBool mWaiting;
PRPackedBool mInWaitMessage;
#endif
};
#endif // !ipcService_h__

View File

@@ -1,187 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "private/pprio.h"
#include "plstr.h"
#include "nsReadableUtils.h"
#include "nsMemory.h"
#include "ipcSocketProviderUnix.h"
#include "ipcLog.h"
static PRDescIdentity ipcIOLayerIdentity;
static PRIOMethods ipcIOLayerMethods;
static char *ipcIOSocketPath;
static PRStatus PR_CALLBACK
ipcIOLayerConnect(PRFileDesc* fd, const PRNetAddr* a, PRIntervalTime timeout)
{
if (!fd || !fd->lower)
return PR_FAILURE;
PRStatus status;
if (!ipcIOSocketPath || !ipcIOSocketPath[0]) {
NS_ERROR("not initialized");
return PR_FAILURE;
}
//
// ignore passed in address.
//
PRNetAddr addr;
addr.local.family = PR_AF_LOCAL;
PL_strncpyz(addr.local.path, ipcIOSocketPath, sizeof(addr.local.path));
status = fd->lower->methods->connect(fd->lower, &addr, timeout);
if (status != PR_SUCCESS)
return status;
//
// now that we have a connected socket; do some security checks on the
// file descriptor.
//
// (1) make sure owner matches
// (2) make sure permissions match expected permissions
//
// if these conditions aren't met then bail.
//
int unix_fd = PR_FileDesc2NativeHandle(fd->lower);
struct stat st;
if (fstat(unix_fd, &st) == -1) {
NS_ERROR("stat failed");
return PR_FAILURE;
}
if (st.st_uid != getuid() && st.st_uid != geteuid()) {
//
// on OSX 10.1.5, |fstat| has a bug when passed a file descriptor to
// a socket. it incorrectly returns a UID of 0. however, |stat|
// succeeds, but using |stat| introduces a race condition.
//
// XXX come up with a better security check.
//
if (st.st_uid != 0) {
NS_ERROR("userid check failed");
return PR_FAILURE;
}
if (stat(ipcIOSocketPath, &st) == -1) {
NS_ERROR("stat failed");
return PR_FAILURE;
}
if (st.st_uid != getuid() && st.st_uid != geteuid()) {
NS_ERROR("userid check failed");
return PR_FAILURE;
}
}
return PR_SUCCESS;
}
static void InitIPCMethods()
{
ipcIOLayerIdentity = PR_GetUniqueIdentity("moz:ipc-layer");
ipcIOLayerMethods = *PR_GetDefaultIOMethods();
ipcIOLayerMethods.connect = ipcIOLayerConnect;
}
NS_IMETHODIMP
ipcSocketProviderUnix::NewSocket(const char *host,
PRInt32 port,
const char *proxyHost,
PRInt32 proxyPort,
PRFileDesc **fd,
nsISupports **securityInfo)
{
static PRBool firstTime = PR_TRUE;
if (firstTime) {
InitIPCMethods();
firstTime = PR_FALSE;
}
PRFileDesc *sock = PR_OpenTCPSocket(PR_AF_LOCAL);
if (!sock) return NS_ERROR_OUT_OF_MEMORY;
PRFileDesc *layer = PR_CreateIOLayerStub(ipcIOLayerIdentity, &ipcIOLayerMethods);
if (!layer)
goto loser;
layer->secret = nsnull;
if (PR_PushIOLayer(sock, PR_GetLayersIdentity(sock), layer) != PR_SUCCESS)
goto loser;
*fd = sock;
return NS_OK;
loser:
if (layer)
layer->dtor(layer);
if (sock)
PR_Close(sock);
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
ipcSocketProviderUnix::AddToSocket(const char *host,
PRInt32 port,
const char *proxyHost,
PRInt32 proxyPort,
PRFileDesc *fd,
nsISupports **securityInfo)
{
NS_NOTREACHED("unexpected");
return NS_ERROR_UNEXPECTED;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(ipcSocketProviderUnix, nsISocketProvider)
void
ipcSocketProviderUnix::SetSocketPath(const char *socketPath)
{
if (ipcIOSocketPath)
free(ipcIOSocketPath);
ipcIOSocketPath = socketPath ? strdup(socketPath) : nsnull;
}

View File

@@ -1,58 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcSocketProviderUnix_h__
#define ipcSocketProviderUnix_h__
#include "nsISocketProvider.h"
class ipcSocketProviderUnix : public nsISocketProvider
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISOCKETPROVIDER
ipcSocketProviderUnix() { NS_INIT_ISUPPORTS(); }
virtual ~ipcSocketProviderUnix() { }
//
// called to initialize the socket path
//
static void SetSocketPath(const char *socketPath);
};
#endif // !ipcSocketProviderUnix_h__

View File

@@ -1,341 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsIServiceManager.h"
#include "nsIObserverService.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "nsIFile.h"
#include "nsIProcess.h"
#include "nsDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsEventQueueUtils.h"
#include "nsAutoLock.h"
#include "nsNetCID.h"
#include "netCore.h"
#include "prerror.h"
#include "plstr.h"
#include "ipcConfig.h"
#include "ipcLog.h"
#include "ipcMessageUtils.h"
#include "ipcTransport.h"
#include "ipcm.h"
//-----------------------------------------------------------------------------
// ipcTransport
//-----------------------------------------------------------------------------
nsresult
ipcTransport::Init(ipcTransportObserver *obs)
{
LOG(("ipcTransport::Init\n"));
mObserver = obs;
nsresult rv = PlatformInit();
if (NS_FAILED(rv)) return rv;
return Connect();
}
nsresult
ipcTransport::Shutdown()
{
LOG(("ipcTransport::Shutdown\n"));
mObserver = 0;
return Disconnect();
}
nsresult
ipcTransport::SendMsg(ipcMessage *msg, PRBool sync)
{
NS_ENSURE_ARG_POINTER(msg);
NS_ENSURE_TRUE(mObserver, NS_ERROR_NOT_INITIALIZED);
LOG(("ipcTransport::SendMsg [msg=%p dataLen=%u]\n", msg, msg->DataLen()));
ipcMessage *syncReply = nsnull;
{
nsAutoMonitor mon(mMonitor);
nsresult rv;
if (sync) {
msg->SetFlag(IPC_MSG_FLAG_SYNC_QUERY);
// flag before sending to avoid race with background thread.
mSyncWaiting = PR_TRUE;
}
if (mHaveConnection) {
rv = SendMsg_Internal(msg);
if (NS_FAILED(rv)) return rv;
}
else {
LOG((" delaying message until connected\n"));
mDelayedQ.Append(msg);
}
if (sync) {
if (!mSyncReplyMsg) {
LOG((" waiting for response...\n"));
mon.Wait();
}
if (!mSyncReplyMsg) {
LOG((" sync request timed out or was canceled\n"));
return NS_ERROR_FAILURE;
}
syncReply = mSyncReplyMsg;
mSyncReplyMsg = nsnull;
}
}
if (syncReply) {
// NOTE: may re-enter SendMsg
mObserver->OnMessageAvailable(syncReply);
delete syncReply;
}
return NS_OK;
}
void
ipcTransport::ProcessIncomingMsgQ()
{
LOG(("ipcTransport::ProcessIncomingMsgQ\n"));
// we can't hold mMonitor while calling into the observer, so we grab
// mIncomingMsgQ and NULL it out inside the monitor to prevent others
// from modifying it while we iterate over it.
ipcMessageQ *inQ;
{
nsAutoMonitor mon(mMonitor);
inQ = mIncomingMsgQ;
mIncomingMsgQ = nsnull;
}
if (inQ) {
while (!inQ->IsEmpty()) {
ipcMessage *msg = inQ->First();
if (mObserver)
mObserver->OnMessageAvailable(msg);
inQ->DeleteFirst();
}
delete inQ;
}
}
void *
ipcTransport::ProcessIncomingMsgQ_EventHandler(PLEvent *ev)
{
ipcTransport *self = (ipcTransport *) PL_GetEventOwner(ev);
self->ProcessIncomingMsgQ();
return nsnull;
}
void *
ipcTransport::ConnectionEstablished_EventHandler(PLEvent *ev)
{
ipcTransport *self = (ipcTransport *) PL_GetEventOwner(ev);
if (self->mObserver)
self->mObserver->OnConnectionEstablished(self->mClientID);
return nsnull;
}
void *
ipcTransport::ConnectionLost_EventHandler(PLEvent *ev)
{
ipcTransport *self = (ipcTransport *) PL_GetEventOwner(ev);
if (self->mObserver)
self->mObserver->OnConnectionLost();
return nsnull;
}
void
ipcTransport::Generic_EventCleanup(PLEvent *ev)
{
ipcTransport *self = (ipcTransport *) PL_GetEventOwner(ev);
NS_RELEASE(self);
delete ev;
}
// called on a background thread
void
ipcTransport::OnMessageAvailable(ipcMessage *rawMsg)
{
LOG(("ipcTransport::OnMessageAvailable [msg=%p dataLen=%u]\n",
rawMsg, rawMsg->DataLen()));
//
// XXX FIX COMMENTS XXX
//
// 1- append to incoming message queue
//
// 2- post event to main thread to handle incoming message queue
// or if sync waiting, unblock waiter so it can scan incoming
// message queue.
//
PRBool dispatchEvent = PR_FALSE;
PRBool connectEvent = PR_FALSE;
{
nsAutoMonitor mon(mMonitor);
if (!mHaveConnection) {
if (rawMsg->Target().Equals(IPCM_TARGET)) {
if (IPCM_GetMsgType(rawMsg) == IPCM_MSG_TYPE_CLIENT_ID) {
LOG((" connection established!\n"));
mHaveConnection = PR_TRUE;
// remember our client ID
ipcMessageCast<ipcmMessageClientID> msg(rawMsg);
mClientID = msg->ClientID();
connectEvent = PR_TRUE;
// move messages off the delayed message queue
while (!mDelayedQ.IsEmpty()) {
ipcMessage *msg = mDelayedQ.First();
mDelayedQ.RemoveFirst();
SendMsg_Internal(msg);
}
return;
}
}
LOG((" received unexpected first message!\n"));
return;
}
LOG((" mSyncWaiting=%u MSG_FLAG_SYNC_REPLY=%u\n",
mSyncWaiting, rawMsg->TestFlag(IPC_MSG_FLAG_SYNC_REPLY) != 0));
if (mSyncWaiting && rawMsg->TestFlag(IPC_MSG_FLAG_SYNC_REPLY)) {
mSyncReplyMsg = rawMsg;
mSyncWaiting = PR_FALSE;
mon.Notify();
}
else {
if (!mIncomingMsgQ) {
mIncomingMsgQ = new ipcMessageQ();
if (!mIncomingMsgQ)
return;
dispatchEvent = PR_TRUE;
}
mIncomingMsgQ->Append(rawMsg);
}
LOG((" connectEvent=%u dispatchEvent=%u mSyncReplyMsg=%p mIncomingMsgQ=%p\n",
connectEvent, dispatchEvent, mSyncReplyMsg, mIncomingMsgQ));
}
if (connectEvent)
ProxyToMainThread(ConnectionEstablished_EventHandler);
if (dispatchEvent)
ProxyToMainThread(ProcessIncomingMsgQ_EventHandler);
}
void
ipcTransport::ProxyToMainThread(PLHandleEventProc proc)
{
LOG(("ipcTransport::ProxyToMainThread\n"));
nsCOMPtr<nsIEventQueue> eq;
NS_GetMainEventQ(getter_AddRefs(eq));
if (eq) {
PLEvent *ev = new PLEvent();
PL_InitEvent(ev, this, proc, Generic_EventCleanup);
NS_ADDREF_THIS();
if (eq->PostEvent(ev) == PR_FAILURE) {
LOG((" PostEvent failed"));
NS_RELEASE_THIS();
delete ev;
}
}
}
nsresult
ipcTransport::SpawnDaemon()
{
LOG(("ipcTransport::SpawnDaemon\n"));
nsresult rv;
nsCOMPtr<nsIFile> file;
rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR, getter_AddRefs(file));
if (NS_FAILED(rv)) return rv;
rv = file->AppendNative(NS_LITERAL_CSTRING(IPC_DAEMON_APP_NAME));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIProcess> proc(do_CreateInstance(NS_PROCESS_CONTRACTID,&rv));
if (NS_FAILED(rv)) return rv;
rv = proc->Init(file);
if (NS_FAILED(rv)) return rv;
PRUint32 pid;
return proc->Run(PR_FALSE, nsnull, 0, &pid);
}
// called on a background thread
nsresult
ipcTransport::OnConnectFailure()
{
LOG(("ipcTransport::OnConnectFailure\n"));
nsresult rv;
if (!mSpawnedDaemon) {
//
// spawn daemon on connection failure
//
rv = SpawnDaemon();
if (NS_FAILED(rv)) {
LOG((" failed to spawn daemon [rv=%x]\n", rv));
return rv;
}
mSpawnedDaemon = PR_TRUE;
}
Disconnect();
PRUint32 ms = 50 * mConnectionAttemptCount;
LOG((" sleeping for %u ms...\n", ms));
PR_Sleep(PR_MillisecondsToInterval(ms));
Connect();
return NS_OK;
}
NS_IMPL_THREADSAFE_ISUPPORTS0(ipcTransport)

View File

@@ -1,169 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcTransport_h__
#define ipcTransport_h__
#include "nsIObserver.h"
#include "nsITimer.h"
#include "nsString.h"
#include "nsCOMPtr.h"
#include "prmon.h"
#include "ipcMessage.h"
#include "ipcMessageQ.h"
#ifdef XP_UNIX
#include "ipcTransportUnix.h"
typedef nsISocketEventHandler ipcTransportSuper;
#else
typedef nsISupports ipcTransportSuper;
#endif
//----------------------------------------------------------------------------
// ipcTransportObserver interface
//----------------------------------------------------------------------------
class ipcTransportObserver
{
public:
virtual void OnConnectionEstablished(PRUint32 clientID) = 0;
virtual void OnConnectionLost() = 0;
virtual void OnMessageAvailable(const ipcMessage *) = 0;
};
//-----------------------------------------------------------------------------
// ipcTransport
//-----------------------------------------------------------------------------
class ipcTransport : public ipcTransportSuper
{
public:
NS_DECL_ISUPPORTS
ipcTransport()
: mMonitor(PR_NewMonitor())
, mObserver(nsnull)
, mIncomingMsgQ(nsnull)
, mSyncReplyMsg(nsnull)
, mSyncWaiting(nsnull)
, mSentHello(PR_FALSE)
, mHaveConnection(PR_FALSE)
, mSpawnedDaemon(PR_FALSE)
, mConnectionAttemptCount(0)
, mClientID(0)
{}
virtual ~ipcTransport()
{
PR_DestroyMonitor(mMonitor);
#ifdef XP_UNIX
if (mReceiver)
((ipcReceiver *) mReceiver.get())->ClearTransport();
#endif
}
nsresult Init(ipcTransportObserver *observer);
nsresult Shutdown();
// takes ownership of |msg|
nsresult SendMsg(ipcMessage *msg, PRBool sync = PR_FALSE);
PRBool HaveConnection() const { return mHaveConnection; }
public:
//
// internal to implementation
//
void OnMessageAvailable(ipcMessage *); // takes ownership
private:
//
// helpers
//
nsresult PlatformInit();
nsresult Connect();
nsresult Disconnect();
nsresult OnConnectFailure();
nsresult SendMsg_Internal(ipcMessage *msg);
nsresult SpawnDaemon();
void ProxyToMainThread(PLHandleEventProc);
void ProcessIncomingMsgQ();
PR_STATIC_CALLBACK(void *) ProcessIncomingMsgQ_EventHandler(PLEvent *);
PR_STATIC_CALLBACK(void *) ConnectionEstablished_EventHandler(PLEvent *);
PR_STATIC_CALLBACK(void *) ConnectionLost_EventHandler(PLEvent *);
PR_STATIC_CALLBACK(void) Generic_EventCleanup(PLEvent *);
//
// data
//
PRMonitor *mMonitor;
ipcTransportObserver *mObserver; // weak reference
ipcMessageQ mDelayedQ;
ipcMessageQ *mIncomingMsgQ;
ipcMessage *mSyncReplyMsg;
PRPackedBool mSyncWaiting;
PRPackedBool mSentHello;
PRPackedBool mHaveConnection;
PRPackedBool mSpawnedDaemon;
PRUint32 mConnectionAttemptCount;
PRUint32 mClientID;
#ifdef XP_UNIX
nsCOMPtr<nsIInputStreamNotify> mReceiver;
nsCOMPtr<nsISocketTransport> mTransport;
nsCOMPtr<nsIInputStream> mInputStream;
nsCOMPtr<nsIOutputStream> mOutputStream;
//
// unix specific helpers
//
nsresult CreateTransport();
nsresult GetSocketPath(nsACString &);
public:
NS_DECL_NSISOCKETEVENTHANDLER
//
// internal helper methods
//
void OnConnectionLost(nsresult reason);
#endif
};
#endif // !ipcTransport_h__

View File

@@ -1,355 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "prenv.h"
#include "nsIThread.h"
#include "nsIFile.h"
#include "nsIServiceManager.h"
#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
#include "ipcSocketProviderUnix.h"
#include "nsISocketTransportService.h"
#include "nsEventQueueUtils.h"
#include "nsStreamUtils.h"
#include "nsNetCID.h"
#include "nsNetError.h"
#include "nsCOMPtr.h"
#include "ipcConfig.h"
#include "ipcLog.h"
#include "ipcTransportUnix.h"
#include "ipcTransport.h"
#include "ipcm.h"
static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
#define IPC_BUFFER_SEGMENT_SIZE 4096
// for use with nsISocketTransportService::PostEvent
enum {
IPC_TRANSPORT_EVENT_CONNECT,
IPC_TRANSPORT_EVENT_DISCONNECT,
IPC_TRANSPORT_EVENT_SENDMSG
};
//-----------------------------------------------------------------------------
// ipcTransport (XP_UNIX specific methods)
//-----------------------------------------------------------------------------
nsresult
ipcTransport::PlatformInit()
{
PRNetAddr addr; // this way we know our buffer is large enough ;-)
IPC_GetDefaultSocketPath(addr.local.path, sizeof(addr.local.path));
ipcSocketProviderUnix::SetSocketPath(addr.local.path);
return NS_OK;
}
static NS_METHOD ipcWriteMessage(nsIOutputStream *stream,
void *closure,
char *segment,
PRUint32 offset,
PRUint32 count,
PRUint32 *countWritten)
{
ipcMessage *msg = (ipcMessage *) closure;
PRBool complete;
PRStatus rv = msg->WriteTo(segment, count, countWritten, &complete);
NS_ASSERTION(rv == PR_SUCCESS, "failed to write message");
// stop writing once the message has been completely written.
if (*countWritten == 0 && complete)
return NS_BASE_STREAM_CLOSED;
return NS_OK;
}
// runs on main thread or socket thread
nsresult
ipcTransport::SendMsg_Internal(ipcMessage *msg)
{
LOG(("ipcTransport::SendMsg_Internal [msg=%p dataLen=%u]\n", msg, msg->DataLen()));
if (nsIThread::IsMainThread()) {
LOG((" proxy to socket thread\n"));
nsresult rv;
nsCOMPtr<nsISocketTransportService> sts(
do_GetService(kSocketTransportServiceCID, &rv)); // XXX cache service
if (NS_FAILED(rv)) return rv;
return sts->PostEvent(this, IPC_TRANSPORT_EVENT_SENDMSG, 0, msg);
}
NS_ENSURE_TRUE(mOutputStream, NS_ERROR_NOT_INITIALIZED);
nsresult rv;
PRUint32 n;
rv = mOutputStream->WriteSegments(ipcWriteMessage, msg, msg->MsgLen(), &n);
if (NS_FAILED(rv)) return rv;
NS_ASSERTION(n == msg->MsgLen(), "not all bytes written");
delete msg; // done with message
return NS_OK;
}
// runs on main thread or socket thread
nsresult
ipcTransport::Connect()
{
LOG(("ipcTransport::Connect\n"));
if (++mConnectionAttemptCount > 20) {
LOG((" giving up after 20 unsuccessful connection attempts\n"));
return NS_ERROR_ABORT;
}
nsresult rv;
if (nsIThread::IsMainThread()) {
LOG((" proxy to socket thread\n"));
nsCOMPtr<nsISocketTransportService> sts(
do_GetService(kSocketTransportServiceCID, &rv)); // XXX cache service
if (NS_FAILED(rv)) return rv;
return sts->PostEvent(this, IPC_TRANSPORT_EVENT_CONNECT, 0, nsnull);
}
rv = CreateTransport();
if (NS_FAILED(rv)) return rv;
//
// send CLIENT_HELLO; expect CLIENT_ID in response.
//
rv = SendMsg_Internal(new ipcmMessageClientHello());
if (NS_FAILED(rv)) return rv;
//
// put the receiver to work...
//
nsCOMPtr<nsIAsyncInputStream> asyncIn = do_QueryInterface(mInputStream, &rv);
if (NS_FAILED(rv)) return rv;
if (!mReceiver) {
mReceiver = new ipcReceiver(this);
if (!mReceiver)
return NS_ERROR_OUT_OF_MEMORY;
}
return asyncIn->AsyncWait(mReceiver, 0, nsnull);
}
// runs on main thread or socket thread
nsresult
ipcTransport::Disconnect()
{
if (nsIThread::IsMainThread()) {
LOG((" proxy to socket thread\n"));
nsresult rv;
nsCOMPtr<nsISocketTransportService> sts(
do_GetService(kSocketTransportServiceCID, &rv)); // XXX cache service
if (NS_FAILED(rv)) return rv;
return sts->PostEvent(this, IPC_TRANSPORT_EVENT_DISCONNECT, 0, nsnull);
}
mHaveConnection = PR_FALSE;
if (mTransport) {
mTransport->Close(NS_BINDING_ABORTED);
mTransport = nsnull;
mInputStream = nsnull;
mOutputStream = nsnull;
}
return NS_OK;
}
// runs on socket transport thread
void
ipcTransport::OnConnectionLost(nsresult reason)
{
LOG(("ipcTransport::OnConnectionLost [reason=%x]\n", reason));
PRBool hadConnection = mHaveConnection;
Disconnect();
if (hadConnection)
ProxyToMainThread(ConnectionLost_EventHandler);
if (reason == NS_BINDING_ABORTED)
return;
if (NS_FAILED(reason))
OnConnectFailure();
}
nsresult
ipcTransport::CreateTransport()
{
nsresult rv;
nsCOMPtr<nsISocketTransportService> sts(
do_GetService(kSocketTransportServiceCID, &rv));
if (NS_FAILED(rv)) return rv;
const char *types[] = { IPC_SOCKET_TYPE };
rv = sts->CreateTransport(types, 1,
NS_LITERAL_CSTRING("127.0.0.1"), IPC_PORT, nsnull,
getter_AddRefs(mTransport));
if (NS_FAILED(rv)) return rv;
// open a blocking, buffered output stream (buffer size is unlimited)
rv = mTransport->OpenOutputStream(nsITransport::OPEN_BLOCKING,
IPC_BUFFER_SEGMENT_SIZE, PRUint32(-1),
getter_AddRefs(mOutputStream));
if (NS_FAILED(rv)) return rv;
// open a non-blocking, buffered input stream (buffer size limited)
rv = mTransport->OpenInputStream(0, IPC_BUFFER_SEGMENT_SIZE, 4,
getter_AddRefs(mInputStream));
return rv;
}
nsresult
ipcTransport::GetSocketPath(nsACString &socketPath)
{
nsCOMPtr<nsIFile> file;
NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(file));
if (!file)
return NS_ERROR_FAILURE;
const char *logName = PR_GetEnv("LOGNAME");
if (!(logName && *logName)) {
logName = PR_GetEnv("USER");
if (!(logName && *logName)) {
LOG(("could not determine username from environment\n"));
return NS_ERROR_FAILURE;
}
}
nsCAutoString leaf;
leaf = NS_LITERAL_CSTRING(".mozilla-ipc-")
+ nsDependentCString(logName);
file->AppendNative(leaf);
file->AppendNative(NS_LITERAL_CSTRING("ipcd"));
file->GetNativePath(socketPath);
return NS_OK;
}
//----------------------------------------------------------------------------
// ipcTransport::nsISocketEventHandler
//----------------------------------------------------------------------------
NS_IMETHODIMP
ipcTransport::OnSocketEvent(PRUint32 type, PRUint32 uparam, void *vparam)
{
switch (type) {
case IPC_TRANSPORT_EVENT_CONNECT:
Connect();
break;
case IPC_TRANSPORT_EVENT_DISCONNECT:
Disconnect();
break;
case IPC_TRANSPORT_EVENT_SENDMSG:
SendMsg_Internal((ipcMessage *) vparam);
break;
}
return NS_OK;
}
//----------------------------------------------------------------------------
// ipcReceiver
//----------------------------------------------------------------------------
NS_IMPL_THREADSAFE_ISUPPORTS1(ipcReceiver, nsIInputStreamNotify)
NS_METHOD
ipcReceiver::ReadSegment(nsIInputStream *stream,
void *closure,
const char *ptr,
PRUint32 offset,
PRUint32 count,
PRUint32 *countRead)
{
ipcReceiver *self = (ipcReceiver *) closure;
*countRead = 0;
while (count) {
PRUint32 nread;
PRBool complete;
if (!self->mMsg) {
self->mMsg = new ipcMessage();
if (!self->mMsg)
return (self->mStatus = NS_ERROR_OUT_OF_MEMORY);
}
self->mMsg->ReadFrom(ptr, count, &nread, &complete);
if (complete) {
self->mTransport->OnMessageAvailable(self->mMsg); // hand over ownership
self->mMsg = nsnull;
}
count -= nread;
ptr += nread;
*countRead += nread;
}
return NS_OK;
}
NS_IMETHODIMP
ipcReceiver::OnInputStreamReady(nsIAsyncInputStream *stream)
{
LOG(("ipcReceiver::OnInputStreamReady\n"));
nsresult rv;
PRUint32 n;
rv = stream->ReadSegments(ReadSegment, this, IPC_BUFFER_SEGMENT_SIZE, &n);
if (NS_SUCCEEDED(rv)) {
rv = mStatus;
if (NS_SUCCEEDED(rv) && n == 0)
rv = NS_BASE_STREAM_CLOSED;
}
if (NS_FAILED(rv)) {
mTransport->OnConnectionLost(rv);
return NS_OK;
}
// continue reading...
return stream->AsyncWait(this, 0, nsnull);
}

View File

@@ -1,82 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ipcTransportUnix_h__
#define ipcTransportUnix_h__
#include "nsIAsyncInputStream.h"
#include "nsIAsyncOutputStream.h"
#include "nsISocketTransport.h"
#include "nsISocketTransportService.h"
#include "prio.h"
#include "ipcMessageQ.h"
class ipcTransport;
//-----------------------------------------------------------------------------
// ipcReceiver
//-----------------------------------------------------------------------------
class ipcReceiver : public nsIInputStreamNotify
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIINPUTSTREAMNOTIFY
ipcReceiver(ipcTransport *transport)
: mTransport(transport)
, mMsg(nsnull)
, mStatus(NS_OK)
{ }
virtual ~ipcReceiver() { }
// called by the transport when it is going away.
void ClearTransport() { mTransport = nsnull; }
private:
static NS_METHOD ReadSegment(nsIInputStream *, void *, const char *,
PRUint32, PRUint32, PRUint32 *);
// the transport owns the receiver, so this back pointer does not need
// to be an owning reference.
ipcTransport *mTransport;
ipcMessage *mMsg; // message in progress
nsresult mStatus;
};
#endif // !ipcTransportUnix_h__

View File

@@ -1,315 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <windows.h>
#include "prprf.h"
#include "prmon.h"
#include "prthread.h"
#include "plevent.h"
#include "nsIServiceManager.h"
#include "nsIEventQueue.h"
#include "nsIEventQueueService.h"
#include "nsAutoLock.h"
#include "ipcConfig.h"
#include "ipcLog.h"
#include "ipcTransport.h"
#include "ipcm.h"
//-----------------------------------------------------------------------------
// windows message thread
//-----------------------------------------------------------------------------
#define IPC_WM_SENDMSG (WM_USER + 0x1)
#define IPC_WM_SHUTDOWN (WM_USER + 0x2)
static nsresult ipcThreadStatus = NS_OK;
static PRThread *ipcThread = NULL;
static PRMonitor *ipcMonitor = NULL;
static HWND ipcDaemonHwnd = NULL;
static HWND ipcLocalHwnd = NULL;
static PRBool ipcShutdown = PR_FALSE; // not accessed on message thread!!
static ipcTransport *ipcTrans = NULL; // not accessed on message thread!!
//-----------------------------------------------------------------------------
// window proc
//-----------------------------------------------------------------------------
static LRESULT CALLBACK
ipcThreadWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LOG(("got message [msg=%x wparam=%x lparam=%x]\n", uMsg, wParam, lParam));
if (uMsg == WM_COPYDATA) {
COPYDATASTRUCT *cd = (COPYDATASTRUCT *) lParam;
if (cd && cd->lpData) {
ipcMessage *msg = new ipcMessage();
PRUint32 bytesRead;
PRBool complete;
PRStatus rv = msg->ReadFrom((const char *) cd->lpData, cd->cbData,
&bytesRead, &complete);
if (rv == PR_SUCCESS && complete && ipcTrans)
ipcTrans->OnMessageAvailable(msg); // takes ownership of msg
else {
LOG((" unable to deliver message [complete=%u]\n", complete));
delete msg;
}
}
return TRUE;
}
if (uMsg == IPC_WM_SENDMSG) {
ipcMessage *msg = (ipcMessage *) lParam;
if (msg) {
LOG((" sending message...\n"));
COPYDATASTRUCT cd;
cd.dwData = GetCurrentProcessId();
cd.cbData = (DWORD) msg->MsgLen();
cd.lpData = (PVOID) msg->MsgBuf();
SendMessageA(ipcDaemonHwnd, WM_COPYDATA, (WPARAM) hWnd, (LPARAM) &cd);
LOG((" done.\n"));
delete msg;
}
return 0;
}
if (uMsg == IPC_WM_SHUTDOWN) {
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
//-----------------------------------------------------------------------------
// ipc thread functions
//-----------------------------------------------------------------------------
static void
ipcThreadFunc(void *arg)
{
LOG(("entering message thread\n"));
DWORD pid = GetCurrentProcessId();
WNDCLASS wc;
memset(&wc, 0, sizeof(wc));
wc.lpfnWndProc = ipcThreadWindowProc;
wc.lpszClassName = IPC_CLIENT_WINDOW_CLASS;
RegisterClass(&wc);
char wName[sizeof(IPC_CLIENT_WINDOW_NAME_PREFIX) + 20];
PR_snprintf(wName, sizeof(wName), "%s%u", IPC_CLIENT_WINDOW_NAME_PREFIX, pid);
ipcLocalHwnd = CreateWindow(IPC_CLIENT_WINDOW_CLASS, wName,
0, 0, 0, 10, 10, NULL, NULL, NULL, NULL);
{
nsAutoMonitor mon(ipcMonitor);
if (!ipcLocalHwnd)
ipcThreadStatus = NS_ERROR_FAILURE;
mon.Notify();
}
if (ipcLocalHwnd) {
MSG msg;
while (GetMessage(&msg, ipcLocalHwnd, 0, 0))
DispatchMessage(&msg);
ipcShutdown = PR_TRUE; // assuming atomic memory write
DestroyWindow(ipcLocalHwnd);
ipcLocalHwnd = NULL;
}
LOG(("exiting message thread\n"));
return;
}
static PRStatus
ipcThreadInit(ipcTransport *transport)
{
if (ipcThread)
return PR_FAILURE;
NS_ADDREF(ipcTrans = transport);
ipcShutdown = PR_FALSE;
ipcMonitor = PR_NewMonitor();
if (!ipcMonitor)
return PR_FAILURE;
// spawn message thread
ipcThread = PR_CreateThread(PR_USER_THREAD, ipcThreadFunc, NULL,
PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
PR_JOINABLE_THREAD, 0);
if (!ipcThread) {
NS_WARNING("thread creation failed");
return PR_FAILURE;
}
// wait for hidden window to be created
{
nsAutoMonitor mon(ipcMonitor);
while (!ipcLocalHwnd && NS_SUCCEEDED(ipcThreadStatus))
mon.Wait();
}
if (NS_FAILED(ipcThreadStatus)) {
NS_WARNING("message thread failed");
return PR_FAILURE;
}
return PR_SUCCESS;
}
static PRStatus
ipcThreadShutdown()
{
if (PR_AtomicSet(&ipcShutdown, PR_TRUE) == PR_FALSE) {
LOG(("posting IPC_WM_SHUTDOWN message\n"));
PostMessage(ipcLocalHwnd, IPC_WM_SHUTDOWN, 0, 0);
}
LOG(("joining w/ message thread...\n"));
PR_JoinThread(ipcThread);
ipcThread = NULL;
//
// ok, now the message thread is dead
//
PR_DestroyMonitor(ipcMonitor);
ipcMonitor = NULL;
NS_RELEASE(ipcTrans);
// NS_RELEASE(ipcEventQ);
return PR_SUCCESS;
}
//-----------------------------------------------------------------------------
// windows specific ipcTransport impl
//-----------------------------------------------------------------------------
nsresult
ipcTransport::PlatformInit()
{
return NS_OK;
}
nsresult
ipcTransport::Disconnect()
{
mHaveConnection = PR_FALSE;
if (ipcThread)
ipcThreadShutdown();
// clear our reference to the daemon's HWND.
ipcDaemonHwnd = NULL;
return NS_OK;
}
nsresult
ipcTransport::Connect()
{
LOG(("ipcTransport::Connect\n"));
if (++mConnectionAttemptCount > 20) {
LOG((" giving up after 20 unsuccessful connection attempts\n"));
return NS_ERROR_ABORT;
}
NS_ENSURE_TRUE(ipcDaemonHwnd == NULL, NS_ERROR_ALREADY_INITIALIZED);
ipcDaemonHwnd = FindWindow(IPC_WINDOW_CLASS, IPC_WINDOW_NAME);
if (!ipcDaemonHwnd) {
LOG((" daemon does not appear to be running\n"));
//
// daemon does not exist
//
return OnConnectFailure();
}
//
// delay creation of the message thread until we know the daemon exists.
//
if (!ipcThread)
ipcThreadInit(this);
//
// send CLIENT_HELLO; expect CLIENT_ID in response.
//
SendMsg_Internal(new ipcmMessageClientHello());
mSentHello = PR_TRUE;
#if 0
// XXX need something else here
//
// begin a timer. if the timer fires before we get a CLIENT_ID, then
// assume the connection attempt failed.
//
nsresult rv;
mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv))
rv = mTimer->Init(this, 1000, nsITimer::TYPE_ONE_SHOT);
return rv;
#endif
return NS_OK;
}
nsresult
ipcTransport::SendMsg_Internal(ipcMessage *msg)
{
LOG(("ipcTransport::SendMsg_Internal\n"));
if (ipcShutdown) {
NS_WARNING("unable to send message b/c message thread is shutdown\n");
goto loser;
}
if (!PostMessage(ipcLocalHwnd, IPC_WM_SENDMSG, 0, (LPARAM) msg)) {
LOG((" PostMessage failed w/ error = %u\n", GetLastError()));
goto loser;
}
return NS_OK;
loser:
delete msg;
return NS_ERROR_FAILURE;
}

View File

@@ -1,50 +0,0 @@
#
# The contents of this file are subject to the Netscape Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = test_ipc
REQUIRES = xpcom \
string \
ipc \
$(NULL)
CPPSRCS = \
TestIPC.cpp \
$(NULL)
SIMPLE_PROGRAMS = $(CPPSRCS:.cpp=$(BIN_SUFFIX))
include $(topsrcdir)/config/config.mk
LIBS = \
$(EXTRA_DSO_LIBS) \
$(MOZ_JS_LIBS) \
$(XPCOM_LIBS) \
$(NSPR_LIBS) \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,316 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla IPC.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "ipcIService.h"
#include "ipcILockService.h"
#include "nsIEventQueueService.h"
#include "nsIServiceManager.h"
#include "nsIComponentRegistrar.h"
#include "nsString.h"
#include "prmem.h"
static const nsID kIPCMTargetID =
{ /* 753ca8ff-c8c2-4601-b115-8c2944da1150 */
0x753ca8ff,
0xc8c2,
0x4601,
{0xb1, 0x15, 0x8c, 0x29, 0x44, 0xda, 0x11, 0x50}
};
static const nsID kTestTargetID =
{ /* e628fc6e-a6a7-48c7-adba-f241d1128fb8 */
0xe628fc6e,
0xa6a7,
0x48c7,
{0xad, 0xba, 0xf2, 0x41, 0xd1, 0x12, 0x8f, 0xb8}
};
#define RETURN_IF_FAILED(rv, step) \
PR_BEGIN_MACRO \
if (NS_FAILED(rv)) { \
printf("*** %s failed: rv=%x\n", step, rv); \
return rv;\
} \
PR_END_MACRO
static NS_DEFINE_CID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);
static nsIEventQueue* gEventQ = nsnull;
static PRBool gKeepRunning = PR_TRUE;
//static PRInt32 gMsgCount = 0;
static ipcIService *gIpcServ = nsnull;
static ipcILockService *gIpcLockServ = nsnull;
static void
SendMsg(ipcIService *ipc, PRUint32 cID, const nsID &target, const char *data, PRUint32 dataLen, PRBool sync = PR_FALSE)
{
printf("*** sending message: [to-client=%u dataLen=%u]\n", cID, dataLen);
ipc->SendMessage(cID, target, (const PRUint8 *) data, dataLen, sync);
// gMsgCount++;
}
//-----------------------------------------------------------------------------
class myIpcMessageObserver : public ipcIMessageObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_IPCIMESSAGEOBSERVER
myIpcMessageObserver() { NS_INIT_ISUPPORTS(); }
};
NS_IMPL_ISUPPORTS1(myIpcMessageObserver, ipcIMessageObserver)
NS_IMETHODIMP
myIpcMessageObserver::OnMessageAvailable(const nsID &target, const PRUint8 *data, PRUint32 dataLen)
{
printf("*** got message: [%s]\n", (const char *) data);
// if (--gMsgCount == 0)
// gKeepRunning = PR_FALSE;
return NS_OK;
}
//-----------------------------------------------------------------------------
class myIpcClientQueryHandler : public ipcIClientQueryHandler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_IPCICLIENTQUERYHANDLER
};
NS_IMPL_ISUPPORTS1(myIpcClientQueryHandler, ipcIClientQueryHandler)
NS_IMETHODIMP
myIpcClientQueryHandler::OnQueryComplete(PRUint32 aQueryID,
nsresult aStatus,
PRUint32 aClientID,
const char **aNames,
PRUint32 aNameCount,
const nsID **aTargets,
PRUint32 aTargetCount)
{
printf("*** query complete [queryID=%u status=0x%x clientID=%u]\n",
aQueryID, aStatus, aClientID);
PRUint32 i;
printf("*** names:\n");
for (i = 0; i < aNameCount; ++i)
printf("*** %d={%s}\n", i, aNames[i]);
printf("*** targets:\n");
for (i = 0; i < aTargetCount; ++i) {
const char *trailer;
if (aTargets[i]->Equals(kTestTargetID))
trailer = " (TEST_TARGET_ID)";
else if (aTargets[i]->Equals(kIPCMTargetID))
trailer = " (IPCM_TARGET_ID)";
else
trailer = " (unknown)";
char *str = aTargets[i]->ToString();
printf("*** %d=%s%s\n", i, str, trailer);
PR_Free(str);
}
if (aClientID != 0) {
const char hello[] = "hello friend!";
SendMsg(gIpcServ, aClientID, kTestTargetID, hello, sizeof(hello));
}
return NS_OK;
}
//-----------------------------------------------------------------------------
class myIpcLockNotify : public ipcILockNotify
{
public:
NS_DECL_ISUPPORTS
NS_DECL_IPCILOCKNOTIFY
};
NS_IMPL_ISUPPORTS1(myIpcLockNotify, ipcILockNotify)
NS_IMETHODIMP
myIpcLockNotify::OnAcquireLockComplete(const char *lockName, nsresult status)
{
printf("*** OnAcquireLockComplete [lock=%s status=%x]\n", lockName, status);
gIpcLockServ->ReleaseLock(lockName);
return NS_OK;
}
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
nsresult rv;
{
nsCOMPtr<nsIServiceManager> servMan;
NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
if (registrar)
registrar->AutoRegister(nsnull);
// Create the Event Queue for this thread...
nsCOMPtr<nsIEventQueueService> eqs =
do_GetService(kEventQueueServiceCID, &rv);
RETURN_IF_FAILED(rv, "do_GetService(EventQueueService)");
rv = eqs->CreateMonitoredThreadEventQueue();
RETURN_IF_FAILED(rv, "CreateMonitoredThreadEventQueue");
rv = eqs->GetThreadEventQueue(NS_CURRENT_THREAD, &gEventQ);
RETURN_IF_FAILED(rv, "GetThreadEventQueue");
nsCOMPtr<ipcIService> ipcServ(do_GetService("@mozilla.org/ipc/service;1", &rv));
RETURN_IF_FAILED(rv, "do_GetService(ipcServ)");
NS_ADDREF(gIpcServ = ipcServ);
if (argc > 1) {
printf("*** using client name [%s]\n", argv[1]);
gIpcServ->AddClientName(argv[1]);
}
ipcServ->SetMessageObserver(kTestTargetID, new myIpcMessageObserver());
const char *data =
"01 this is a really long message.\n"
"02 this is a really long message.\n"
"03 this is a really long message.\n"
"04 this is a really long message.\n"
"05 this is a really long message.\n"
"06 this is a really long message.\n"
"07 this is a really long message.\n"
"08 this is a really long message.\n"
"09 this is a really long message.\n"
"10 this is a really long message.\n"
"11 this is a really long message.\n"
"12 this is a really long message.\n"
"13 this is a really long message.\n"
"14 this is a really long message.\n"
"15 this is a really long message.\n"
"16 this is a really long message.\n"
"17 this is a really long message.\n"
"18 this is a really long message.\n"
"19 this is a really long message.\n"
"20 this is a really long message.\n"
"21 this is a really long message.\n"
"22 this is a really long message.\n"
"23 this is a really long message.\n"
"24 this is a really long message.\n"
"25 this is a really long message.\n"
"26 this is a really long message.\n"
"27 this is a really long message.\n"
"28 this is a really long message.\n"
"29 this is a really long message.\n"
"30 this is a really long message.\n"
"31 this is a really long message.\n"
"32 this is a really long message.\n"
"33 this is a really long message.\n"
"34 this is a really long message.\n"
"35 this is a really long message.\n"
"36 this is a really long message.\n"
"37 this is a really long message.\n"
"38 this is a really long message.\n"
"39 this is a really long message.\n"
"40 this is a really long message.\n"
"41 this is a really long message.\n"
"42 this is a really long message.\n"
"43 this is a really long message.\n"
"44 this is a really long message.\n"
"45 this is a really long message.\n"
"46 this is a really long message.\n"
"47 this is a really long message.\n"
"48 this is a really long message.\n"
"49 this is a really long message.\n"
"50 this is a really long message.\n"
"51 this is a really long message.\n"
"52 this is a really long message.\n"
"53 this is a really long message.\n"
"54 this is a really long message.\n"
"55 this is a really long message.\n"
"56 this is a really long message.\n"
"57 this is a really long message.\n"
"58 this is a really long message.\n"
"59 this is a really long message.\n"
"60 this is a really long message.\n";
SendMsg(ipcServ, 0, kTestTargetID, data, strlen(data)+1, PR_TRUE);
PRUint32 queryID;
nsCOMPtr<ipcIClientQueryHandler> handler(new myIpcClientQueryHandler());
ipcServ->QueryClientByName("foopy", handler, PR_FALSE, &queryID);
//
// test lock service
//
nsCOMPtr<ipcILockService> lockService = do_GetService("@mozilla.org/ipc/lock-service;1", &rv);
RETURN_IF_FAILED(rv, "do_GetService(ipcLockServ)");
NS_ADDREF(gIpcLockServ = lockService);
nsCOMPtr<ipcILockNotify> notify(new myIpcLockNotify());
gIpcLockServ->AcquireLock("blah", notify, PR_TRUE);
rv = gIpcLockServ->AcquireLock("foo", nsnull, PR_TRUE);
printf("*** sync AcquireLock returned [rv=%x]\n", rv);
PLEvent *ev;
while (gKeepRunning) {
gEventQ->WaitForEvent(&ev);
gEventQ->HandleEvent(ev);
}
NS_RELEASE(gIpcServ);
printf("*** processing remaining events\n");
// process any remaining events
while (NS_SUCCEEDED(gEventQ->GetEvent(&ev)) && ev)
gEventQ->HandleEvent(ev);
printf("*** done\n");
} // this scopes the nsCOMPtrs
// no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
rv = NS_ShutdownXPCOM(nsnull);
NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
return 0;
}

View File

@@ -1,75 +0,0 @@
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Mozilla IPC.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2002
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Darin Fisher <darin@netscape.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
DEPTH = ../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
MODULE = testmodule
LIBRARY_NAME = testmodule
EXPORT_LIBRARY = 1
MODULE_NAME = testmodule
REQUIRES = xpcom \
ipc \
$(NULL)
CPPSRCS = TestModule.cpp
LOCAL_INCLUDES = \
-I$(srcdir)/../common \
$(NULL)
EXTRA_DSO_LDOPTS = \
$(LIBS_DIR) \
$(NSPR_LIBS) \
$(EXTRA_DSO_LIBS) \
$(NULL)
include $(topsrcdir)/config/rules.mk
_IPC_FILES = \
$(LIB_PREFIX)$(LIBRARY_NAME)$(DLL_SUFFIX) \
$(NULL)
libs:: $(_IPC_FILES)
$(INSTALL) $^ $(DIST)/bin/ipc/modules
install:: $(_IPC_FILES)
$(SYSINSTALL) $(IFLAGS1) $^ $(DESTDIR)$(mozappdir)/ipc/modules

View File

@@ -1,62 +0,0 @@
#include <stdio.h>
#include "ipcModuleUtil.h"
#define TEST_MODULE_ID \
{ /* e628fc6e-a6a7-48c7-adba-f241d1128fb8 */ \
0xe628fc6e, \
0xa6a7, \
0x48c7, \
{0xad, 0xba, 0xf2, 0x41, 0xd1, 0x12, 0x8f, 0xb8} \
}
static const nsID kTestModuleID = TEST_MODULE_ID;
struct TestModule
{
static void Init()
{
printf("*** TestModule::Init\n");
}
static void Shutdown()
{
printf("*** TestModule::Shutdown\n");
}
static void HandleMsg(ipcClientHandle client,
const nsID &target,
const void *data,
PRUint32 dataLen)
{
printf("*** TestModule::HandleMsg [%s]\n", (const char *) data);
static const char buf[] = "pong";
IPC_SendMsg(client, kTestModuleID, buf, sizeof(buf));
}
static void ClientUp(ipcClientHandle client)
{
printf("*** TestModule::ClientUp [%u]\n", IPC_GetClientID(client));
}
static void ClientDown(ipcClientHandle client)
{
printf("*** TestModule::ClientDown [%u]\n", IPC_GetClientID(client));
}
};
static ipcModuleMethods gTestMethods =
{
IPC_MODULE_METHODS_VERSION,
TestModule::Init,
TestModule::Shutdown,
TestModule::HandleMsg,
TestModule::ClientUp,
TestModule::ClientDown
};
static ipcModuleEntry gTestModuleEntry[] =
{
{ TEST_MODULE_ID, &gTestMethods }
};
IPC_IMPL_GETMODULES(TestModule, gTestModuleEntry)