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
529 changed files with 5283 additions and 75856 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

@@ -1,4 +1,4 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/* -*- 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
@@ -16,27 +16,23 @@
* Reserved.
*/
#include "nsIURI.idl"
#ifndef _REGISTER_ASSIGNER_H_
#define _REGISTER_ASSIGNER_H_
/**
* JAR URLs have the following syntax
*
* jar:<jar-file-uri>!/<jar-entry>
*
* EXAMPLE: jar:http://www.big.com/blue.jar!/ocean.html
*/
[scriptable, uuid(c7e410d3-85f2-11d3-9f63-006008a6efe9)]
interface nsIJARURI : nsIURI {
#include "Fundamentals.h"
#include "VirtualRegister.h"
/**
* Returns the root URI (the one for the actual JAR file) for this JAR.
* eg http://www.big.com/blue.jar
*/
attribute nsIURI JARFile;
class FastBitMatrix;
/**
* Returns the entry specified for this JAR URI.
* eg ocean.html
*/
attribute string JAREntry;
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

@@ -1,4 +1,4 @@
/* -*- Mode: IDL; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/* -*- 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
@@ -16,27 +16,22 @@
* Reserved.
*/
#include "nsIURI.idl"
#ifndef _REGISTER_PRESSURE_H_
#define _REGISTER_PRESSURE_H_
/**
* JAR URLs have the following syntax
*
* jar:<jar-file-uri>!/<jar-entry>
*
* EXAMPLE: jar:http://www.big.com/blue.jar!/ocean.html
*/
[scriptable, uuid(c7e410d3-85f2-11d3-9f63-006008a6efe9)]
interface nsIJARURI : nsIURI {
#include "BitSet.h"
#include "HashSet.h"
/**
* Returns the root URI (the one for the actual JAR file) for this JAR.
* eg http://www.big.com/blue.jar
*/
attribute nsIURI JARFile;
/**
* Returns the entry specified for this JAR URI.
* eg ocean.html
*/
attribute string JAREntry;
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,42 +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 = necko
LIBRARY_NAME = necko_datetime
SHORT_LIBNAME = neckodtm
IS_COMPONENT = 1
CPPSRCS = \
nsDateTimeHandler.cpp \
nsDateTimeChannel.cpp \
nsDateTimeModule.cpp \
$(NULL)
EXTRA_DSO_LDOPTS += $(MOZ_COMPONENT_LIBS)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,431 +0,0 @@
/* -*- 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.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):
*/
// datetime implementation
#include "nsDateTimeChannel.h"
#include "nsIServiceManager.h"
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsXPIDLString.h"
#include "nsISocketTransportService.h"
static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
// nsDateTimeChannel methods
nsDateTimeChannel::nsDateTimeChannel() {
NS_INIT_REFCNT();
mContentLength = -1;
mPort = -1;
}
nsDateTimeChannel::~nsDateTimeChannel() {
}
NS_IMPL_ISUPPORTS4(nsDateTimeChannel, nsIChannel, nsIRequest, nsIStreamListener, nsIStreamObserver)
nsresult
nsDateTimeChannel::Init(nsIURI* uri)
{
nsresult rv;
NS_ASSERTION(uri, "no uri");
mUrl = uri;
rv = mUrl->GetPort(&mPort);
if (NS_FAILED(rv) || mPort < 1)
mPort = DATETIME_PORT;
rv = mUrl->GetPath(getter_Copies(mHost));
if (NS_FAILED(rv)) return rv;
if (!*(const char *)mHost) return NS_ERROR_NOT_INITIALIZED;
return NS_OK;
}
NS_METHOD
nsDateTimeChannel::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult)
{
nsDateTimeChannel* dc = new nsDateTimeChannel();
if (dc == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(dc);
nsresult rv = dc->QueryInterface(aIID, aResult);
NS_RELEASE(dc);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIRequest methods:
NS_IMETHODIMP
nsDateTimeChannel::IsPending(PRBool *result)
{
NS_NOTREACHED("nsDateTimeChannel::IsPending");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetStatus(nsresult *status)
{
*status = NS_OK;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::Cancel(nsresult status)
{
NS_NOTREACHED("nsDateTimeChannel::Cancel");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::Suspend(void)
{
NS_NOTREACHED("nsDateTimeChannel::Suspend");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::Resume(void)
{
NS_NOTREACHED("nsDateTimeChannel::Resume");
return NS_ERROR_NOT_IMPLEMENTED;
}
////////////////////////////////////////////////////////////////////////////////
// nsIChannel methods:
NS_IMETHODIMP
nsDateTimeChannel::GetOriginalURI(nsIURI* *aURI)
{
*aURI = mOriginalURI ? mOriginalURI : mUrl;
NS_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetOriginalURI(nsIURI* aURI)
{
mOriginalURI = aURI;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetURI(nsIURI* *aURI)
{
*aURI = mUrl;
NS_IF_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetURI(nsIURI* aURI)
{
mUrl = aURI;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::OpenInputStream(nsIInputStream **_retval)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, 32, 32, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
return channel->OpenInputStream(_retval);
}
NS_IMETHODIMP
nsDateTimeChannel::OpenOutputStream(nsIOutputStream **_retval)
{
NS_NOTREACHED("nsDateTimeChannel::OpenOutputStream");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::AsyncOpen(nsIStreamObserver *observer, nsISupports* ctxt)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, 32, 32, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
return channel->AsyncOpen(observer, ctxt);
}
NS_IMETHODIMP
nsDateTimeChannel::AsyncRead(nsIStreamListener *aListener,
nsISupports *ctxt)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, 32, 32, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
mListener = aListener;
return channel->AsyncRead(this, ctxt);
}
NS_IMETHODIMP
nsDateTimeChannel::AsyncWrite(nsIInputStream *fromStream,
nsIStreamObserver *observer,
nsISupports *ctxt)
{
NS_NOTREACHED("nsDateTimeChannel::AsyncWrite");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetLoadAttributes(PRUint32 *aLoadAttributes)
{
*aLoadAttributes = mLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetLoadAttributes(PRUint32 aLoadAttributes)
{
mLoadAttributes = aLoadAttributes;
return NS_OK;
}
#define DATETIME_TYPE "text/plain"
NS_IMETHODIMP
nsDateTimeChannel::GetContentType(char* *aContentType) {
if (!aContentType) return NS_ERROR_NULL_POINTER;
*aContentType = nsCRT::strdup(DATETIME_TYPE);
if (!*aContentType) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetContentType(const char *aContentType)
{
//It doesn't make sense to set the content-type on this type
// of channel...
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsDateTimeChannel::GetContentLength(PRInt32 *aContentLength)
{
*aContentLength = mContentLength;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetContentLength(PRInt32 aContentLength)
{
NS_NOTREACHED("nsDateTimeChannel::SetContentLength");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetTransferOffset(PRUint32 *aTransferOffset)
{
NS_NOTREACHED("nsDateTimeChannel::GetTransferOffset");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::SetTransferOffset(PRUint32 aTransferOffset)
{
NS_NOTREACHED("nsDateTimeChannel::SetTransferOffset");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetTransferCount(PRInt32 *aTransferCount)
{
NS_NOTREACHED("nsDateTimeChannel::GetTransferCount");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::SetTransferCount(PRInt32 aTransferCount)
{
NS_NOTREACHED("nsDateTimeChannel::SetTransferCount");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetBufferSegmentSize(PRUint32 *aBufferSegmentSize)
{
NS_NOTREACHED("nsDateTimeChannel::GetBufferSegmentSize");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::SetBufferSegmentSize(PRUint32 aBufferSegmentSize)
{
NS_NOTREACHED("nsDateTimeChannel::SetBufferSegmentSize");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetBufferMaxSize(PRUint32 *aBufferMaxSize)
{
NS_NOTREACHED("nsDateTimeChannel::GetBufferMaxSize");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::SetBufferMaxSize(PRUint32 aBufferMaxSize)
{
NS_NOTREACHED("nsDateTimeChannel::SetBufferMaxSize");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetShouldCache(PRBool *aShouldCache)
{
*aShouldCache = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetPipeliningAllowed(PRBool *aPipeliningAllowed)
{
*aPipeliningAllowed = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetPipeliningAllowed(PRBool aPipeliningAllowed)
{
NS_NOTREACHED("SetPipeliningAllowed");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsDateTimeChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
{
*aLoadGroup = mLoadGroup;
NS_IF_ADDREF(*aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
{
if (mLoadGroup) // if we already had a load group remove ourselves...
(void)mLoadGroup->RemoveChannel(this, nsnull, nsnull, nsnull);
mLoadGroup = aLoadGroup;
if (mLoadGroup) {
return mLoadGroup->AddChannel(this, nsnull);
}
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetOwner(nsISupports* *aOwner)
{
*aOwner = mOwner.get();
NS_IF_ADDREF(*aOwner);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetOwner(nsISupports* aOwner)
{
mOwner = aOwner;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aNotificationCallbacks)
{
*aNotificationCallbacks = mCallbacks.get();
NS_IF_ADDREF(*aNotificationCallbacks);
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks)
{
mCallbacks = aNotificationCallbacks;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeChannel::GetSecurityInfo(nsISupports * *aSecurityInfo)
{
*aSecurityInfo = nsnull;
return NS_OK;
}
// nsIStreamObserver methods
NS_IMETHODIMP
nsDateTimeChannel::OnStartRequest(nsIChannel *aChannel, nsISupports *aContext) {
return mListener->OnStartRequest(this, aContext);
}
NS_IMETHODIMP
nsDateTimeChannel::OnStopRequest(nsIChannel* aChannel, nsISupports* aContext,
nsresult aStatus, const PRUnichar* aMsg) {
if (mLoadGroup) {
nsresult rv = mLoadGroup->RemoveChannel(this, nsnull, aStatus, aMsg);
if (NS_FAILED(rv)) return rv;
}
return mListener->OnStopRequest(this, aContext, aStatus, aMsg);
}
// nsIStreamListener method
NS_IMETHODIMP
nsDateTimeChannel::OnDataAvailable(nsIChannel* aChannel, nsISupports* aContext,
nsIInputStream *aInputStream, PRUint32 aSourceOffset,
PRUint32 aLength) {
mContentLength = aLength;
return mListener->OnDataAvailable(this, aContext, aInputStream, aSourceOffset, aLength);
}

View File

@@ -1,77 +0,0 @@
/* -*- 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.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):
*/
// A datetime channel retrieves date time information from
// RFC 867 compliant datetime servers. The date/time returned
// to the caller is of MIME type "text/plain".
#ifndef nsDateTimeChannel_h___
#define nsDateTimeChannel_h___
#include "nsString.h"
#include "nsILoadGroup.h"
#include "nsIInputStream.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
#include "nsXPIDLString.h"
#include "nsIChannel.h"
#include "nsIURI.h"
#include "nsDateTimeHandler.h"
#include "nsIStreamListener.h"
class nsDateTimeChannel : public nsIChannel, public nsIStreamListener {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSISTREAMOBSERVER
// nsDateTimeChannel methods:
nsDateTimeChannel();
virtual ~nsDateTimeChannel();
// Define a Create method to be used with a factory:
static NS_METHOD
Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
nsresult Init(nsIURI* uri);
protected:
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIURI> mOriginalURI;
nsCOMPtr<nsIURI> mUrl;
nsCOMPtr<nsIStreamListener> mListener;
PRUint32 mLoadAttributes;
nsCOMPtr<nsILoadGroup> mLoadGroup;
nsCString mContentType;
PRInt32 mContentLength;
nsCOMPtr<nsISupports> mOwner;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
PRInt32 mPort;
nsXPIDLCString mHost;
};
#endif /* nsDateTimeChannel_h___ */

View File

@@ -1,116 +0,0 @@
/* -*- 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.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):
*/
#include "nspr.h"
#include "nsDateTimeChannel.h"
#include "nsDateTimeHandler.h"
#include "nsIURL.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIInterfaceRequestor.h"
#include "nsIProgressEventSink.h"
static NS_DEFINE_CID(kSimpleURICID, NS_SIMPLEURI_CID);
////////////////////////////////////////////////////////////////////////////////
nsDateTimeHandler::nsDateTimeHandler() {
NS_INIT_REFCNT();
}
nsDateTimeHandler::~nsDateTimeHandler() {
}
NS_IMPL_ISUPPORTS(nsDateTimeHandler, NS_GET_IID(nsIProtocolHandler));
NS_METHOD
nsDateTimeHandler::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult) {
nsDateTimeHandler* ph = new nsDateTimeHandler();
if (ph == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(ph);
nsresult rv = ph->QueryInterface(aIID, aResult);
NS_RELEASE(ph);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIProtocolHandler methods:
NS_IMETHODIMP
nsDateTimeHandler::GetScheme(char* *result) {
*result = nsCRT::strdup("datetime");
if (!*result) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeHandler::GetDefaultPort(PRInt32 *result) {
*result = DATETIME_PORT;
return NS_OK;
}
NS_IMETHODIMP
nsDateTimeHandler::NewURI(const char *aSpec, nsIURI *aBaseURI,
nsIURI **result) {
nsresult rv;
// no concept of a relative datetime url
NS_ASSERTION(!aBaseURI, "base url passed into datetime protocol handler");
nsIURI* url;
rv = nsComponentManager::CreateInstance(kSimpleURICID, nsnull,
NS_GET_IID(nsIURI),
(void**)&url);
if (NS_FAILED(rv)) return rv;
rv = url->SetSpec((char*)aSpec);
if (NS_FAILED(rv)) {
NS_RELEASE(url);
return rv;
}
*result = url;
return rv;
}
NS_IMETHODIMP
nsDateTimeHandler::NewChannel(nsIURI* url, nsIChannel* *result)
{
nsresult rv;
nsDateTimeChannel* channel;
rv = nsDateTimeChannel::Create(nsnull, NS_GET_IID(nsIChannel), (void**)&channel);
if (NS_FAILED(rv)) return rv;
rv = channel->Init(url);
if (NS_FAILED(rv)) {
NS_RELEASE(channel);
return rv;
}
*result = channel;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,51 +0,0 @@
/* -*- 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.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):
*/
// The datetime protocol handler creates "datetime" URIs of the form
// "datetime:RFC867Server".
#ifndef nsDateTimeHandler_h___
#define nsDateTimeHandler_h___
#include "nsIProtocolHandler.h"
#define DATETIME_PORT 13
// {AA27D2A0-B71B-11d3-A1A0-0050041CAF44}
#define NS_DATETIMEHANDLER_CID \
{ 0xaa27d2a0, 0xb71b, 0x11d3, { 0xa1, 0xa0, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } }
class nsDateTimeHandler : public nsIProtocolHandler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROTOCOLHANDLER
// nsDateTimeHandler methods:
nsDateTimeHandler();
virtual ~nsDateTimeHandler();
// Define a Create method to be used with a factory:
static NS_METHOD Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
};
#endif /* nsDateTimeHandler_h___ */

View File

@@ -1,34 +0,0 @@
/* -*- 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.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):
*/
#include "nsIGenericFactory.h"
#include "nsDateTimeHandler.h"
static nsModuleComponentInfo gResComponents[] = {
{ "The DateTime Protocol Handler",
NS_DATETIMEHANDLER_CID,
NS_NETWORK_PROTOCOL_PROGID_PREFIX "datetime",
nsDateTimeHandler::Create
}
};
NS_IMPL_NSGETMODULE("datetime", gResComponents)

View File

@@ -1,41 +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 = necko
LIBRARY_NAME = necko_finger
IS_COMPONENT = 1
CPPSRCS = \
nsFingerHandler.cpp \
nsFingerChannel.cpp \
nsFingerModule.cpp \
$(NULL)
EXTRA_DSO_LDOPTS += $(MOZ_COMPONENT_LIBS)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,517 +0,0 @@
/* -*- 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.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):
*/
// finger implementation
#include "nsFingerChannel.h"
#include "nsIServiceManager.h"
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsXPIDLString.h"
#include "nsISocketTransportService.h"
#include "nsIStringStream.h"
#include "nsMimeTypes.h"
static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
#define BUFFER_SEG_SIZE (4*1024)
#define BUFFER_MAX_SIZE (64*1024)
// nsFingerChannel methods
nsFingerChannel::nsFingerChannel()
: mContentLength(-1),
mActAsObserver(PR_TRUE),
mPort(-1),
mStatus(NS_OK)
{
NS_INIT_REFCNT();
}
nsFingerChannel::~nsFingerChannel() {
}
NS_IMPL_THREADSAFE_ISUPPORTS4(nsFingerChannel, nsIChannel, nsIRequest,
nsIStreamListener, nsIStreamObserver)
nsresult
nsFingerChannel::Init(nsIURI* uri)
{
nsresult rv;
nsXPIDLCString autoBuffer;
NS_ASSERTION(uri, "no uri");
mUrl = uri;
// For security reasons, we do not allow the user to specify a
// non-default port for finger: URL's.
mPort = FINGER_PORT;
rv = mUrl->GetPath(getter_Copies(autoBuffer)); // autoBuffer = user@host
if (NS_FAILED(rv)) return rv;
nsCString cString(autoBuffer);
nsCString tempBuf;
PRUint32 i;
// Now parse out the user and host
for (i=0; cString[i] != '\0'; i++) {
if (cString[i] == '@') {
cString.Left(tempBuf, i);
mUser = tempBuf;
cString.Right(tempBuf, cString.Length() - i - 1);
mHost = tempBuf;
break;
}
}
// Catch the case of just the host being given
if (cString[i] == '\0') {
mHost = cString;
}
#ifdef DEBUG_bryner
printf("Status:mUser = %s, mHost = %s\n", (const char*)mUser,
(const char*)mHost);
#endif
if (!*(const char *)mHost) return NS_ERROR_NOT_INITIALIZED;
return NS_OK;
}
NS_METHOD
nsFingerChannel::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult)
{
nsFingerChannel* fc = new nsFingerChannel();
if (fc == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(fc);
nsresult rv = fc->QueryInterface(aIID, aResult);
NS_RELEASE(fc);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIRequest methods:
NS_IMETHODIMP
nsFingerChannel::IsPending(PRBool *result)
{
NS_NOTREACHED("nsFingerChannel::IsPending");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetStatus(nsresult *status)
{
*status = mStatus;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::Cancel(nsresult status)
{
nsresult rv = NS_ERROR_FAILURE;
mStatus = status;
if (mTransport) {
rv = mTransport->Cancel(status);
}
return rv;
}
NS_IMETHODIMP
nsFingerChannel::Suspend(void)
{
NS_NOTREACHED("nsFingerChannel::Suspend");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::Resume(void)
{
NS_NOTREACHED("nsFingerChannel::Resume");
return NS_ERROR_NOT_IMPLEMENTED;
}
////////////////////////////////////////////////////////////////////////////////
// nsIChannel methods:
NS_IMETHODIMP
nsFingerChannel::GetOriginalURI(nsIURI* *aURI)
{
*aURI = mOriginalURI ? mOriginalURI : mUrl;
NS_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetOriginalURI(nsIURI* aURI)
{
mOriginalURI = aURI;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetURI(nsIURI* *aURI)
{
*aURI = mUrl;
NS_IF_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetURI(nsIURI* aURI)
{
mUrl = aURI;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::OpenInputStream(nsIInputStream **_retval)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, BUFFER_SEG_SIZE,
BUFFER_MAX_SIZE, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
return channel->OpenInputStream(_retval);
}
NS_IMETHODIMP
nsFingerChannel::OpenOutputStream(nsIOutputStream **_retval)
{
NS_NOTREACHED("nsFingerChannel::OpenOutputStream");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::AsyncOpen(nsIStreamObserver *observer, nsISupports* ctxt)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::AsyncRead(nsIStreamListener *aListener, nsISupports *ctxt)
{
nsresult rv = NS_OK;
NS_WITH_SERVICE(nsISocketTransportService, socketService, kSocketTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> channel;
rv = socketService->CreateTransport(mHost, mPort, mHost, BUFFER_SEG_SIZE,
BUFFER_MAX_SIZE, getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
mListener = aListener;
mResponseContext = ctxt;
mTransport = channel;
return SendRequest(channel);
}
NS_IMETHODIMP
nsFingerChannel::AsyncWrite(nsIInputStream *fromStream,
nsIStreamObserver *observer,
nsISupports *ctxt)
{
NS_NOTREACHED("nsFingerChannel::AsyncWrite");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetLoadAttributes(PRUint32 *aLoadAttributes)
{
*aLoadAttributes = mLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetLoadAttributes(PRUint32 aLoadAttributes)
{
mLoadAttributes = aLoadAttributes;
return NS_OK;
}
#define FINGER_TYPE TEXT_PLAIN
NS_IMETHODIMP
nsFingerChannel::GetContentType(char* *aContentType) {
if (!aContentType) return NS_ERROR_NULL_POINTER;
*aContentType = nsCRT::strdup(FINGER_TYPE);
if (!*aContentType) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetContentType(const char *aContentType)
{
//It doesn't make sense to set the content-type on this type
// of channel...
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsFingerChannel::GetContentLength(PRInt32 *aContentLength)
{
*aContentLength = mContentLength;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetContentLength(PRInt32 aContentLength)
{
NS_NOTREACHED("nsFingerChannel::SetContentLength");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetTransferOffset(PRUint32 *aTransferOffset)
{
NS_NOTREACHED("nsFingerChannel::GetTransferOffset");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::SetTransferOffset(PRUint32 aTransferOffset)
{
NS_NOTREACHED("nsFingerChannel::SetTransferOffset");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetTransferCount(PRInt32 *aTransferCount)
{
NS_NOTREACHED("nsFingerChannel::GetTransferCount");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::SetTransferCount(PRInt32 aTransferCount)
{
NS_NOTREACHED("nsFingerChannel::SetTransferCount");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetBufferSegmentSize(PRUint32 *aBufferSegmentSize)
{
NS_NOTREACHED("nsFingerChannel::GetBufferSegmentSize");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::SetBufferSegmentSize(PRUint32 aBufferSegmentSize)
{
NS_NOTREACHED("nsFingerChannel::SetBufferSegmentSize");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetBufferMaxSize(PRUint32 *aBufferMaxSize)
{
NS_NOTREACHED("nsFingerChannel::GetBufferMaxSize");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::SetBufferMaxSize(PRUint32 aBufferMaxSize)
{
NS_NOTREACHED("nsFingerChannel::SetBufferMaxSize");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetShouldCache(PRBool *aShouldCache)
{
*aShouldCache = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetPipeliningAllowed(PRBool *aPipeliningAllowed)
{
*aPipeliningAllowed = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetPipeliningAllowed(PRBool aPipeliningAllowed)
{
NS_NOTREACHED("SetPipeliningAllowed");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsFingerChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
{
*aLoadGroup = mLoadGroup;
NS_IF_ADDREF(*aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
{
mLoadGroup = aLoadGroup;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetOwner(nsISupports* *aOwner)
{
*aOwner = mOwner.get();
NS_IF_ADDREF(*aOwner);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetOwner(nsISupports* aOwner)
{
mOwner = aOwner;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aNotificationCallbacks)
{
*aNotificationCallbacks = mCallbacks.get();
NS_IF_ADDREF(*aNotificationCallbacks);
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks)
{
mCallbacks = aNotificationCallbacks;
return NS_OK;
}
NS_IMETHODIMP
nsFingerChannel::GetSecurityInfo(nsISupports * *aSecurityInfo)
{
*aSecurityInfo = nsnull;
return NS_OK;
}
// nsIStreamObserver methods
NS_IMETHODIMP
nsFingerChannel::OnStartRequest(nsIChannel *aChannel, nsISupports *aContext) {
if (!mActAsObserver) {
// acting as a listener
return mListener->OnStartRequest(this, aContext);
} else {
// we don't want to pass our AsyncWrite's OnStart through
// we just ignore this
return NS_OK;
}
}
NS_IMETHODIMP
nsFingerChannel::OnStopRequest(nsIChannel* aChannel, nsISupports* aContext,
nsresult aStatus, const PRUnichar* aMsg) {
#ifdef DEBUG_bryner
printf("nsFingerChannel::OnStopRequest, mActAsObserver=%d\n",
mActAsObserver);
printf(" aChannel = %p\n", aChannel);
#endif
nsresult rv = NS_OK;
if (NS_FAILED(aStatus) || !mActAsObserver) {
if (mLoadGroup) {
rv = mLoadGroup->RemoveChannel(this, nsnull, aStatus, aMsg);
if (NS_FAILED(rv)) return rv;
}
rv = mListener->OnStopRequest(this, aContext, aStatus, aMsg);
mTransport = 0;
return rv;
} else {
// at this point we know the request has been sent.
// we're no longer acting as an observer.
mActAsObserver = PR_FALSE;
return aChannel->AsyncRead(this, mResponseContext);
}
}
// nsIStreamListener method
NS_IMETHODIMP
nsFingerChannel::OnDataAvailable(nsIChannel* aChannel, nsISupports* aContext,
nsIInputStream *aInputStream, PRUint32 aSourceOffset,
PRUint32 aLength) {
mContentLength = aLength;
return mListener->OnDataAvailable(this, aContext, aInputStream, aSourceOffset, aLength);
}
nsresult
nsFingerChannel::SendRequest(nsIChannel* aChannel) {
// The text to send should already be in mUser
nsresult rv = NS_OK;
nsCOMPtr<nsISupports> result;
nsCOMPtr<nsIInputStream> charstream;
nsCString requestBuffer(mUser);
if (mLoadGroup) {
mLoadGroup->AddChannel(this, nsnull);
}
requestBuffer.Append(CRLF);
mRequest = requestBuffer.ToNewCString();
rv = NS_NewCharInputStream(getter_AddRefs(result), mRequest);
if (NS_FAILED(rv)) return rv;
charstream = do_QueryInterface(result, &rv);
if (NS_FAILED(rv)) return rv;
#ifdef DEBUG_bryner
printf("Sending: %s\n", requestBuffer.GetBuffer());
#endif
rv = aChannel->SetTransferCount(requestBuffer.Length());
if (NS_FAILED(rv)) return rv;
rv = aChannel->AsyncWrite(charstream, this, 0);
return rv;
}

View File

@@ -1,84 +0,0 @@
/* -*- 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.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):
*/
#ifndef nsFingerChannel_h___
#define nsFingerChannel_h___
#include "nsString.h"
#include "nsILoadGroup.h"
#include "nsIInputStream.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
#include "nsXPIDLString.h"
#include "nsIChannel.h"
#include "nsIURI.h"
#include "nsFingerHandler.h"
#include "nsIStreamListener.h"
class nsFingerChannel : public nsIChannel, public nsIStreamListener {
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSISTREAMOBSERVER
// nsFingerChannel methods:
nsFingerChannel();
virtual ~nsFingerChannel();
// Define a Create method to be used with a factory:
static NS_METHOD
Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
nsresult Init(nsIURI* uri);
protected:
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIURI> mOriginalURI;
nsCOMPtr<nsIURI> mUrl;
nsCOMPtr<nsIStreamListener> mListener;
PRUint32 mLoadAttributes;
nsCOMPtr<nsILoadGroup> mLoadGroup;
nsCString mContentType;
PRInt32 mContentLength;
nsCOMPtr<nsISupports> mOwner;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
PRBool mActAsObserver;
PRInt32 mPort;
nsXPIDLCString mHost;
nsXPIDLCString mUser;
nsXPIDLCString mRequest;
nsCOMPtr<nsISupports> mResponseContext;
nsCOMPtr<nsIChannel> mTransport;
nsresult mStatus;
protected:
nsresult SendRequest(nsIChannel* aChannel);
};
#endif /* nsFingerChannel_h___ */

View File

@@ -1,116 +0,0 @@
/* -*- 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.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):
*/
#include "nspr.h"
#include "nsFingerChannel.h"
#include "nsFingerHandler.h"
#include "nsIURL.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIInterfaceRequestor.h"
#include "nsIProgressEventSink.h"
static NS_DEFINE_CID(kSimpleURICID, NS_SIMPLEURI_CID);
////////////////////////////////////////////////////////////////////////////////
nsFingerHandler::nsFingerHandler() {
NS_INIT_REFCNT();
}
nsFingerHandler::~nsFingerHandler() {
}
NS_IMPL_ISUPPORTS(nsFingerHandler, NS_GET_IID(nsIProtocolHandler));
NS_METHOD
nsFingerHandler::Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult) {
nsFingerHandler* ph = new nsFingerHandler();
if (ph == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(ph);
nsresult rv = ph->QueryInterface(aIID, aResult);
NS_RELEASE(ph);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIProtocolHandler methods:
NS_IMETHODIMP
nsFingerHandler::GetScheme(char* *result) {
*result = nsCRT::strdup("finger");
if (!*result) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsFingerHandler::GetDefaultPort(PRInt32 *result) {
*result = FINGER_PORT;
return NS_OK;
}
NS_IMETHODIMP
nsFingerHandler::NewURI(const char *aSpec, nsIURI *aBaseURI,
nsIURI **result) {
nsresult rv;
// no concept of a relative finger url
NS_ASSERTION(!aBaseURI, "base url passed into finger protocol handler");
nsIURI* url;
rv = nsComponentManager::CreateInstance(kSimpleURICID, nsnull,
NS_GET_IID(nsIURI),
(void**)&url);
if (NS_FAILED(rv)) return rv;
rv = url->SetSpec((char*)aSpec);
if (NS_FAILED(rv)) {
NS_RELEASE(url);
return rv;
}
*result = url;
return rv;
}
NS_IMETHODIMP
nsFingerHandler::NewChannel(nsIURI* url, nsIChannel* *result)
{
nsresult rv;
nsFingerChannel* channel;
rv = nsFingerChannel::Create(nsnull, NS_GET_IID(nsIChannel), (void**)&channel);
if (NS_FAILED(rv)) return rv;
rv = channel->Init(url);
if (NS_FAILED(rv)) {
NS_RELEASE(channel);
return rv;
}
*result = channel;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,52 +0,0 @@
/* -*- 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.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):
*/
// The finger protocol handler creates "finger" URIs of the form
// "finger:user@host" or "finger:host".
#ifndef nsFingerHandler_h___
#define nsFingerHandler_h___
#include "nsIProtocolHandler.h"
#define FINGER_PORT 79
// {0x76d6d5d8-1dd2-11b2-b361-850ddf15ef07}
#define NS_FINGERHANDLER_CID \
{ 0x76d6d5d8, 0x1dd2, 0x11b2, \
{0xb3, 0x61, 0x85, 0x0d, 0xdf, 0x15, 0xef, 0x07} }
class nsFingerHandler : public nsIProtocolHandler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROTOCOLHANDLER
// nsFingerHandler methods:
nsFingerHandler();
virtual ~nsFingerHandler();
// Define a Create method to be used with a factory:
static NS_METHOD Create(nsISupports* aOuter, const nsIID& aIID, void* *aResult);
};
#endif /* nsFingerHandler_h___ */

View File

@@ -1,34 +0,0 @@
/* -*- 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.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):
*/
#include "nsIGenericFactory.h"
#include "nsFingerHandler.h"
static nsModuleComponentInfo gResComponents[] = {
{ "The Finger Protocol Handler",
NS_FINGERHANDLER_CID,
NS_NETWORK_PROTOCOL_PROGID_PREFIX "finger",
nsFingerHandler::Create
}
};
NS_IMPL_NSGETMODULE("finger", gResComponents)

View File

@@ -1,39 +0,0 @@
/* -*- Mode: IDL; 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.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):
*/
#include "nsIChannel.idl"
interface nsISimpleEnumerator;
[scriptable, uuid(c7e410d1-85f2-11d3-9f63-006008a6efe9)]
interface nsIJARChannel : nsIChannel
{
/**
* Enumerates all the entries in the JAR (the root URI).
* ARGUMENTS:
* aRoot - a string representing the root dir to enumerate from
* or null to enumerate the whole thing.
*/
nsISimpleEnumerator EnumerateEntries(in string aRoot);
};

View File

@@ -1,32 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsIProtocolHandler.idl"
[scriptable, uuid(92c3b42c-98c4-11d3-8cd9-0060b0fc14a3)]
interface nsIJARProtocolHandler : nsIProtocolHandler {
/**
* Add any jar-specific methods here later.
*/
};

View File

@@ -1,978 +0,0 @@
/* -*- 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 "nsNetUtil.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsSpecialSystemDirectory.h"
#include "nsJARChannel.h"
#include "nsCRT.h"
#include "nsIFileTransportService.h"
#include "nsIURL.h"
#include "nsIMIMEService.h"
#include "nsAutoLock.h"
#include "nsIFileStreams.h"
#include "nsMimeTypes.h"
#include "nsScriptSecurityManager.h"
#include "nsIAggregatePrincipal.h"
static NS_DEFINE_CID(kFileTransportServiceCID, NS_FILETRANSPORTSERVICE_CID);
static NS_DEFINE_CID(kMIMEServiceCID, NS_MIMESERVICE_CID);
static NS_DEFINE_CID(kZipReaderCID, NS_ZIPREADER_CID);
static NS_DEFINE_CID(kScriptSecurityManagerCID, NS_SCRIPTSECURITYMANAGER_CID);
#if defined(PR_LOGGING)
#include "nsXPIDLString.h"
//
// Log module for SocketTransport logging...
//
// To enable logging (see prlog.h for full details):
//
// set NSPR_LOG_MODULES=nsJarProtocol:5
// set NSPR_LOG_FILE=nspr.log
//
// this enables PR_LOG_DEBUG level information and places all output in
// the file nspr.log
//
PRLogModuleInfo* gJarProtocolLog = nsnull;
#endif /* PR_LOGGING */
////////////////////////////////////////////////////////////////////////////////
class nsJARDownloadObserver : public nsIStreamObserver
{
public:
NS_DECL_ISUPPORTS
NS_IMETHOD OnStartRequest(nsIChannel* jarCacheTransport,
nsISupports* context) {
return NS_OK;
}
NS_IMETHOD OnStopRequest(nsIChannel* jarCacheTransport,
nsISupports* context,
nsresult status,
const PRUnichar* aMsg) {
nsresult rv = NS_OK;
nsAutoMonitor monitor(mJARChannel->mMonitor);
#ifdef PR_LOGGING
nsCOMPtr<nsIURI> jarURI;
rv = jarCacheTransport->GetURI(getter_AddRefs(jarURI));
if (NS_SUCCEEDED(rv)) {
nsXPIDLCString jarURLStr;
rv = jarURI->GetSpec(getter_Copies(jarURLStr));
if (NS_SUCCEEDED(rv)) {
PR_LOG(gJarProtocolLog, PR_LOG_DEBUG,
("nsJarProtocol: jar download complete %s status=%x",
(const char*)jarURLStr, status));
}
}
#endif
if (NS_SUCCEEDED(status) && mJARChannel->mJarCacheTransport) {
NS_ASSERTION(jarCacheTransport == (mJARChannel->mJarCacheTransport).get(),
"wrong transport");
// after successfully downloading the jar file to the cache,
// start the extraction process:
nsCOMPtr<nsIFileChannel> jarCacheFile;
rv = NS_NewLocalFileChannel(getter_AddRefs(jarCacheFile),
mJarCacheFile,
PR_RDONLY,
0);
if (NS_FAILED(rv)) return rv;
rv = jarCacheFile->SetLoadGroup(mJARChannel->mLoadGroup);
if (NS_FAILED(rv)) return rv;
rv = jarCacheFile->SetBufferSegmentSize(mJARChannel->mBufferSegmentSize);
if (NS_FAILED(rv)) return rv;
rv = jarCacheFile->SetBufferMaxSize(mJARChannel->mBufferMaxSize);
if (NS_FAILED(rv)) return rv;
rv = jarCacheFile->SetLoadAttributes(mJARChannel->mLoadAttributes);
if (NS_FAILED(rv)) return rv;
rv = jarCacheFile->SetNotificationCallbacks(mJARChannel->mCallbacks);
if (NS_FAILED(rv)) return rv;
mJARChannel->SetJARBaseFile(jarCacheFile);
rv = mOnJARFileAvailable(mJARChannel, mClosure);
}
mJARChannel->mJarCacheTransport = nsnull;
return rv;
}
nsJARDownloadObserver(nsIFile* jarCacheFile, nsJARChannel* jarChannel,
OnJARFileAvailableFun onJARFileAvailable,
void* closure)
: mJarCacheFile(jarCacheFile),
mJARChannel(jarChannel),
mOnJARFileAvailable(onJARFileAvailable),
mClosure(closure)
{
NS_INIT_REFCNT();
NS_ADDREF(mJARChannel);
}
virtual ~nsJARDownloadObserver() {
NS_RELEASE(mJARChannel);
}
protected:
nsCOMPtr<nsIFile> mJarCacheFile;
nsJARChannel* mJARChannel;
OnJARFileAvailableFun mOnJARFileAvailable;
void* mClosure;
};
NS_IMPL_THREADSAFE_ISUPPORTS1(nsJARDownloadObserver, nsIStreamObserver)
////////////////////////////////////////////////////////////////////////////////
nsJARChannel::nsJARChannel()
: mContentType(nsnull),
mContentLength(-1),
mLoadAttributes(LOAD_NORMAL),
mStartPosition(0),
mReadCount(-1),
mJAREntry(nsnull),
mMonitor(nsnull),
mStatus(NS_OK)
{
NS_INIT_REFCNT();
#if defined(PR_LOGGING)
//
// Initialize the global PRLogModule for socket transport logging
// if necessary...
//
if (nsnull == gJarProtocolLog) {
gJarProtocolLog = PR_NewLogModule("nsJarProtocol");
}
#endif /* PR_LOGGING */
}
nsJARChannel::~nsJARChannel()
{
if (mContentType)
nsCRT::free(mContentType);
if (mJAREntry)
nsCRT::free(mJAREntry);
if (mMonitor)
PR_DestroyMonitor(mMonitor);
}
NS_IMPL_ISUPPORTS6(nsJARChannel,
nsIJARChannel,
nsIChannel,
nsIRequest,
nsIStreamObserver,
nsIStreamListener,
nsIFileSystem)
NS_METHOD
nsJARChannel::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
nsresult rv;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsJARChannel* jarChannel = new nsJARChannel();
if (jarChannel == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(jarChannel);
rv = jarChannel->QueryInterface(aIID, aResult);
NS_RELEASE(jarChannel);
return rv;
}
nsresult
nsJARChannel::Init(nsIJARProtocolHandler* aHandler, nsIURI* uri)
{
nsresult rv;
mURI = do_QueryInterface(uri, &rv);
if (NS_FAILED(rv)) return rv;
mMonitor = PR_NewMonitor();
if (mMonitor == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIRequest methods
NS_IMETHODIMP
nsJARChannel::IsPending(PRBool* result)
{
NS_NOTREACHED("nsJARChannel::IsPending");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::GetStatus(nsresult *status)
{
*status = mStatus;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::Cancel(nsresult status)
{
nsresult rv;
nsAutoMonitor monitor(mMonitor);
if (mJarCacheTransport) {
rv = mJarCacheTransport->Cancel(status);
if (NS_FAILED(rv)) return rv;
mJarCacheTransport = nsnull;
}
if (mJarExtractionTransport) {
rv = mJarExtractionTransport->Cancel(status);
if (NS_FAILED(rv)) return rv;
mJarExtractionTransport = nsnull;
}
mStatus = status;
return rv;
}
NS_IMETHODIMP
nsJARChannel::Suspend()
{
nsresult rv;
nsAutoMonitor monitor(mMonitor);
if (mJarCacheTransport) {
rv = mJarCacheTransport->Suspend();
if (NS_FAILED(rv)) return rv;
}
if (mJarExtractionTransport) {
rv = mJarExtractionTransport->Suspend();
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::Resume()
{
nsresult rv;
nsAutoMonitor monitor(mMonitor);
if (mJarCacheTransport) {
rv = mJarCacheTransport->Resume();
if (NS_FAILED(rv)) return rv;
}
if (mJarExtractionTransport) {
rv = mJarExtractionTransport->Resume();
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIChannel methods
NS_IMETHODIMP
nsJARChannel::GetOriginalURI(nsIURI* *aOriginalURI)
{
*aOriginalURI = mOriginalURI ? mOriginalURI : nsCOMPtr<nsIURI>(mURI);
NS_ADDREF(*aOriginalURI);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetOriginalURI(nsIURI* aOriginalURI)
{
mOriginalURI = aOriginalURI;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetURI(nsIURI* *aURI)
{
*aURI = mURI;
NS_ADDREF(*aURI);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetURI(nsIURI* aURI)
{
nsresult rv;
mURI = do_QueryInterface(aURI, &rv);
return rv;
}
static nsresult
OpenJARElement(nsJARChannel* channel, void* closure)
{
nsresult rv;
nsIInputStream* *result = (nsIInputStream**)closure;
nsAutoCMonitor mon(channel);
rv = channel->Open(nsnull, nsnull);
if (NS_FAILED(rv)) return rv;
rv = channel->GetInputStream(result);
mon.Notify(); // wake up OpenInputStream
return rv;
}
NS_IMETHODIMP
nsJARChannel::OpenInputStream(nsIInputStream* *result)
{
nsAutoCMonitor mon(this);
nsresult rv;
*result = nsnull;
rv = EnsureJARFileAvailable(OpenJARElement, result);
if (NS_FAILED(rv)) return rv;
if (*result == nsnull)
mon.Wait();
return rv;
}
NS_IMETHODIMP
nsJARChannel::OpenOutputStream(nsIOutputStream* *result)
{
NS_NOTREACHED("nsJARChannel::OpenOutputStream");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::AsyncOpen(nsIStreamObserver* observer, nsISupports* ctxt)
{
NS_NOTREACHED("nsJARChannel::AsyncOpen");
return NS_ERROR_NOT_IMPLEMENTED;
}
static nsresult
ReadJARElement(nsJARChannel* channel, void* closure)
{
nsresult rv;
rv = channel->AsyncReadJARElement();
return rv;
}
NS_IMETHODIMP
nsJARChannel::AsyncRead(nsIStreamListener* listener, nsISupports* ctxt)
{
mUserContext = ctxt;
mUserListener = listener;
return EnsureJARFileAvailable(ReadJARElement, nsnull);
}
nsresult
nsJARChannel::EnsureJARFileAvailable(OnJARFileAvailableFun onJARFileAvailable,
void* closure)
{
nsresult rv;
#ifdef PR_LOGGING
nsXPIDLCString jarURLStr;
mURI->GetSpec(getter_Copies(jarURLStr));
PR_LOG(gJarProtocolLog, PR_LOG_DEBUG,
("nsJarProtocol: EnsureJARFileAvailable %s", (const char*)jarURLStr));
#endif
rv = mURI->GetJARFile(getter_AddRefs(mJARBaseURI));
if (NS_FAILED(rv)) return rv;
rv = mURI->GetJAREntry(&mJAREntry);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIChannel> jarBaseChannel;
rv = NS_OpenURI(getter_AddRefs(jarBaseChannel), mJARBaseURI, nsnull);
if (NS_FAILED(rv)) return rv;
rv = jarBaseChannel->SetLoadGroup(mLoadGroup);
if (NS_FAILED(rv)) return rv;
rv = jarBaseChannel->SetLoadAttributes(mLoadAttributes);
if (NS_FAILED(rv)) return rv;
rv = jarBaseChannel->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
if (mLoadGroup)
(void)mLoadGroup->AddChannel(this, nsnull);
// mJARBaseFile = do_QueryInterface(jarBaseChannel, &rv);
PRBool shouldCache;
rv = jarBaseChannel->GetShouldCache(&shouldCache);
if (NS_SUCCEEDED(rv) && !shouldCache) {
// then we've already got a local jar file -- no need to download it
PR_LOG(gJarProtocolLog, PR_LOG_DEBUG,
("nsJarProtocol: extracting local jar file %s", (const char*)jarURLStr));
rv = onJARFileAvailable(this, closure);
}
else {
// otherwise, we need to download the jar file
nsCOMPtr<nsIFile> jarCacheFile;
rv = GetCacheFile(getter_AddRefs(jarCacheFile));
if (NS_FAILED(rv)) return rv;
PRBool filePresent;
rv = jarCacheFile->IsFile(&filePresent);
if (NS_SUCCEEDED(rv) && filePresent)
{
// then we've already got the file in the local cache -- no need to download it
rv = NS_NewLocalFileChannel(getter_AddRefs(mJARBaseFile),
jarCacheFile,
PR_RDONLY,
0);
if (NS_FAILED(rv)) return rv;
rv = mJARBaseFile->SetBufferSegmentSize(mBufferSegmentSize);
if (NS_FAILED(rv)) return rv;
rv = mJARBaseFile->SetBufferMaxSize(mBufferMaxSize);
if (NS_FAILED(rv)) return rv;
PR_LOG(gJarProtocolLog, PR_LOG_DEBUG,
("nsJarProtocol: jar file already in cache %s", (const char*)jarURLStr));
rv = onJARFileAvailable(this, closure);
return rv;
}
NS_WITH_SERVICE(nsIFileTransportService, fts, kFileTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsAutoMonitor monitor(mMonitor);
// use a file transport to serve as a data pump for the download (done
// on some other thread)
nsCOMPtr<nsIChannel> jarCacheTransport;
rv = fts->CreateTransport(jarCacheFile, PR_RDONLY, 0,
getter_AddRefs(mJarCacheTransport));
if (NS_FAILED(rv)) return rv;
rv = mJarCacheTransport->SetBufferSegmentSize(mBufferSegmentSize);
if (NS_FAILED(rv)) return rv;
rv = mJarCacheTransport->SetBufferMaxSize(mBufferMaxSize);
if (NS_FAILED(rv)) return rv;
rv = mJarCacheTransport->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIStreamObserver> downloadObserver =
new nsJARDownloadObserver(jarCacheFile, this, onJARFileAvailable, closure);
if (downloadObserver == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
PR_LOG(gJarProtocolLog, PR_LOG_DEBUG,
("nsJarProtocol: downloading jar file %s", (const char*)jarURLStr));
nsCOMPtr<nsIInputStream> jarBaseIn;
rv = jarBaseChannel->OpenInputStream(getter_AddRefs(jarBaseIn));
if (NS_FAILED(rv)) return rv;
rv = mJarCacheTransport->AsyncWrite(jarBaseIn, nsnull, downloadObserver);
}
return rv;
}
nsresult
nsJARChannel::GetCacheFile(nsIFile* *cacheFile)
{
// XXX change later to use the real network cache
nsresult rv;
nsCOMPtr<nsIFile> jarCacheFile;
rv = NS_GetSpecialDirectory("xpcom.currentProcess.componentDirectory",
getter_AddRefs(jarCacheFile));
if (NS_FAILED(rv)) return rv;
jarCacheFile->Append("jarCache");
PRBool exists;
rv = jarCacheFile->Exists(&exists);
if (NS_FAILED(rv)) return rv;
if (!exists) {
rv = jarCacheFile->Create(nsIFile::DIRECTORY_TYPE, 0664);
if (NS_FAILED(rv)) return rv;
}
nsCOMPtr<nsIURL> jarBaseURL = do_QueryInterface(mJARBaseURI, &rv);
if (NS_FAILED(rv)) return rv;
char* jarFileName;
rv = jarBaseURL->GetFileName(&jarFileName);
if (NS_FAILED(rv)) return rv;
rv = jarCacheFile->Append(jarFileName);
nsCRT::free(jarFileName);
if (NS_FAILED(rv)) return rv;
*cacheFile = jarCacheFile;
NS_ADDREF(*cacheFile);
return rv;
}
nsresult
nsJARChannel::AsyncReadJARElement()
{
nsresult rv;
nsAutoMonitor monitor(mMonitor);
NS_ASSERTION(mJARBaseFile, "mJARBaseFile is null");
if (mLoadGroup) {
nsCOMPtr<nsILoadGroupListenerFactory> factory;
//
// Create a load group "proxy" listener...
//
rv = mLoadGroup->GetGroupListenerFactory(getter_AddRefs(factory));
if (factory) {
nsIStreamListener *newListener;
rv = factory->CreateLoadGroupListener(mUserListener, &newListener);
if (NS_SUCCEEDED(rv)) {
mUserListener = newListener;
NS_RELEASE(newListener);
}
}
rv = mLoadGroup->AddChannel(this, nsnull);
if (NS_FAILED(rv)) return rv;
}
NS_WITH_SERVICE(nsIFileTransportService, fts, kFileTransportServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
rv = fts->CreateTransportFromFileSystem(this,
getter_AddRefs(mJarExtractionTransport));
if (NS_FAILED(rv)) return rv;
rv = mJarExtractionTransport->SetBufferSegmentSize(mBufferSegmentSize);
if (NS_FAILED(rv)) return rv;
rv = mJarExtractionTransport->SetBufferMaxSize(mBufferMaxSize);
if (NS_FAILED(rv)) return rv;
rv = mJarExtractionTransport->SetNotificationCallbacks(mCallbacks);
if (NS_FAILED(rv)) return rv;
#ifdef PR_LOGGING
nsXPIDLCString jarURLStr;
mURI->GetSpec(getter_Copies(jarURLStr));
PR_LOG(gJarProtocolLog, PR_LOG_DEBUG,
("nsJarProtocol: AsyncRead jar entry %s", (const char*)jarURLStr));
#endif
rv = mJarExtractionTransport->SetTransferOffset(mStartPosition);
if (NS_FAILED(rv)) return rv;
rv = mJarExtractionTransport->SetTransferCount(mReadCount);
if (NS_FAILED(rv)) return rv;
rv = mJarExtractionTransport->AsyncRead(this, nsnull);
return rv;
}
NS_IMETHODIMP
nsJARChannel::AsyncWrite(nsIInputStream* fromStream,
nsIStreamObserver* observer,
nsISupports* ctxt)
{
NS_NOTREACHED("nsJARChannel::AsyncWrite");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::GetLoadAttributes(PRUint32* aLoadFlags)
{
*aLoadFlags = mLoadAttributes;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetLoadAttributes(PRUint32 aLoadFlags)
{
mLoadAttributes = aLoadFlags;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetContentType(char* *aContentType)
{
nsresult rv = NS_OK;
if (mContentType == nsnull) {
char* fileName = new char[PL_strlen(mJAREntry)+1];
PL_strcpy(fileName, mJAREntry);
if (fileName != nsnull) {
PRInt32 len = nsCRT::strlen(fileName);
const char* ext = nsnull;
for (PRInt32 i = len; i >= 0; i--) {
if (fileName[i] == '.') {
ext = &fileName[i + 1];
break;
}
}
if (ext) {
NS_WITH_SERVICE(nsIMIMEService, mimeServ, kMIMEServiceCID, &rv);
if (NS_SUCCEEDED(rv)) {
rv = mimeServ->GetTypeFromExtension(ext, &mContentType);
}
}
else
rv = NS_ERROR_FAILURE;
nsCRT::free(fileName);
}
else {
rv = NS_ERROR_FAILURE;
}
if (NS_FAILED(rv)) {
mContentType = nsCRT::strdup(UNKNOWN_CONTENT_TYPE);
if (mContentType == nsnull)
rv = NS_ERROR_OUT_OF_MEMORY;
else
rv = NS_OK;
}
}
if (NS_SUCCEEDED(rv)) {
*aContentType = nsCRT::strdup(mContentType);
if (*aContentType == nsnull)
rv = NS_ERROR_OUT_OF_MEMORY;
}
return rv;
}
NS_IMETHODIMP
nsJARChannel::SetContentType(const char *aContentType)
{
if (mContentType) {
nsCRT::free(mContentType);
}
mContentType = nsCRT::strdup(aContentType);
if (!mContentType) return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetContentLength(PRInt32* aContentLength)
{
if (mContentLength == -1)
return NS_ERROR_FAILURE;
*aContentLength = mContentLength;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetContentLength(PRInt32 aContentLength)
{
NS_NOTREACHED("nsJARChannel::SetContentLength");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::GetTransferOffset(PRUint32 *aTransferOffset)
{
*aTransferOffset = mStartPosition;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetTransferOffset(PRUint32 aTransferOffset)
{
mStartPosition = aTransferOffset;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetTransferCount(PRInt32 *aTransferCount)
{
*aTransferCount = mReadCount;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetTransferCount(PRInt32 aTransferCount)
{
mReadCount = aTransferCount;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetBufferSegmentSize(PRUint32 *aBufferSegmentSize)
{
*aBufferSegmentSize = mBufferSegmentSize;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetBufferSegmentSize(PRUint32 aBufferSegmentSize)
{
mBufferSegmentSize = aBufferSegmentSize;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetBufferMaxSize(PRUint32 *aBufferMaxSize)
{
*aBufferMaxSize = mBufferMaxSize;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetBufferMaxSize(PRUint32 aBufferMaxSize)
{
mBufferMaxSize = aBufferMaxSize;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetShouldCache(PRBool *aShouldCache)
{
// Jar files report that you shouldn't cache them because this is really
// a question about the jar entry, and the jar entry is always in a jar
// file on disk.
*aShouldCache = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetPipeliningAllowed(PRBool *aPipeliningAllowed)
{
*aPipeliningAllowed = PR_FALSE;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetPipeliningAllowed(PRBool aPipeliningAllowed)
{
NS_NOTREACHED("SetPipeliningAllowed");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsJARChannel::GetLoadGroup(nsILoadGroup* *aLoadGroup)
{
*aLoadGroup = mLoadGroup;
NS_IF_ADDREF(*aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetLoadGroup(nsILoadGroup* aLoadGroup)
{
mLoadGroup = aLoadGroup;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetOwner(nsISupports* *aOwner)
{
if (!mOwner)
{
nsCOMPtr<nsIPrincipal> certificate;
PRInt16 result;
nsresult rv = mJAR->GetCertificatePrincipal(mJAREntry,
getter_AddRefs(certificate),
&result);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
if (certificate)
{ // Get the codebase principal
NS_WITH_SERVICE(nsIScriptSecurityManager, secMan,
kScriptSecurityManagerCID, &rv);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
nsCOMPtr<nsIPrincipal> codebase;
rv = secMan->GetCodebasePrincipal(mJARBaseURI,
getter_AddRefs(codebase));
if (NS_FAILED(rv)) return rv;
// Join the certificate and the codebase
nsCOMPtr<nsIAggregatePrincipal> agg;
agg = do_QueryInterface(certificate, &rv);
NS_ASSERTION(NS_SUCCEEDED(rv),
"Certificate principal is not an aggregate");
rv = agg->SetCodebase(codebase);
if (NS_FAILED(rv)) return rv;
mOwner = do_QueryInterface(agg, &rv);
if (NS_FAILED(rv)) return rv;
}
}
*aOwner = mOwner;
NS_IF_ADDREF(*aOwner);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetOwner(nsISupports* aOwner)
{
mOwner = aOwner;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetNotificationCallbacks(nsIInterfaceRequestor* *aNotificationCallbacks)
{
*aNotificationCallbacks = mCallbacks.get();
NS_IF_ADDREF(*aNotificationCallbacks);
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::SetNotificationCallbacks(nsIInterfaceRequestor* aNotificationCallbacks)
{
mCallbacks = aNotificationCallbacks;
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetSecurityInfo(nsISupports * *aSecurityInfo)
{
*aSecurityInfo = nsnull;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsIStreamObserver methods:
NS_IMETHODIMP
nsJARChannel::OnStartRequest(nsIChannel* jarExtractionTransport,
nsISupports* context)
{
return mUserListener->OnStartRequest(this, mUserContext);
}
NS_IMETHODIMP
nsJARChannel::OnStopRequest(nsIChannel* jarExtractionTransport,
nsISupports* context,
nsresult status,
const PRUnichar* aMsg)
{
nsresult rv;
#ifdef PR_LOGGING
nsCOMPtr<nsIURI> jarURI;
nsXPIDLCString jarURLStr;
rv = mURI->GetSpec(getter_Copies(jarURLStr));
if (NS_SUCCEEDED(rv)) {
PR_LOG(gJarProtocolLog, PR_LOG_DEBUG,
("nsJarProtocol: jar extraction complete %s status=%x",
(const char*)jarURLStr, status));
}
#endif
rv = mUserListener->OnStopRequest(this, mUserContext, status, aMsg);
if (mLoadGroup) {
if (NS_SUCCEEDED(rv)) {
mLoadGroup->RemoveChannel(this, context, status, aMsg);
}
}
mUserListener = nsnull;
mUserContext = nsnull;
mJarExtractionTransport = nsnull;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIStreamListener methods:
NS_IMETHODIMP
nsJARChannel::OnDataAvailable(nsIChannel* jarCacheTransport,
nsISupports* context,
nsIInputStream *inStr,
PRUint32 sourceOffset,
PRUint32 count)
{
return mUserListener->OnDataAvailable(this, mUserContext,
inStr, sourceOffset, count);
}
////////////////////////////////////////////////////////////////////////////////
// nsIFileSystem methods:
NS_IMETHODIMP
nsJARChannel::Open(char* *contentType, PRInt32 *contentLength)
{
nsresult rv;
NS_ASSERTION(mJARBaseFile, "mJARBaseFile is null");
rv = nsComponentManager::CreateInstance(kZipReaderCID,
nsnull,
NS_GET_IID(nsIZipReader),
getter_AddRefs(mJAR));
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIFile> fs;
rv = mJARBaseFile->GetFile(getter_AddRefs(fs));
if (NS_FAILED(rv)) return rv;
rv = mJAR->Init(fs);
if (NS_FAILED(rv)) return rv;
rv = mJAR->Open();
if (NS_FAILED(rv)) return rv;
// If this fails, GetOwner will fail, but otherwise we can continue.
mJAR->ParseManifest();
nsCOMPtr<nsIZipEntry> entry;
rv = mJAR->GetEntry(mJAREntry, getter_AddRefs(entry));
if (NS_FAILED(rv)) return rv;
if (contentLength) {
rv = entry->GetRealSize((PRUint32*)contentLength);
if (NS_FAILED(rv)) return rv;
}
if (contentType) {
rv = GetContentType(contentType);
if (NS_FAILED(rv)) return rv;
}
return rv;
}
NS_IMETHODIMP
nsJARChannel::Close(nsresult status)
{
mJAR = null_nsCOMPtr();
return NS_OK;
}
NS_IMETHODIMP
nsJARChannel::GetInputStream(nsIInputStream* *aInputStream)
{
#ifdef PR_LOGGING
nsXPIDLCString jarURLStr;
mURI->GetSpec(getter_Copies(jarURLStr));
PR_LOG(gJarProtocolLog, PR_LOG_DEBUG,
("nsJarProtocol: GetInputStream jar entry %s", (const char*)jarURLStr));
#endif
return mJAR->GetInputStream(mJAREntry, aInputStream);
}
NS_IMETHODIMP
nsJARChannel::GetOutputStream(nsIOutputStream* *aOutputStream)
{
NS_NOTREACHED("nsJARChannel::GetOutputStream");
return NS_ERROR_NOT_IMPLEMENTED;
}
////////////////////////////////////////////////////////////////////////////////
// nsIJARChannel methods:
NS_IMETHODIMP
nsJARChannel::EnumerateEntries(const char *aRoot, nsISimpleEnumerator **_retval)
{
NS_NOTREACHED("nsJARChannel::EnumerateEntries");
return NS_ERROR_NOT_IMPLEMENTED;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,115 +0,0 @@
/* -*- 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.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):
*/
#ifndef nsJARChannel_h__
#define nsJARChannel_h__
#include "nsIJARChannel.h"
#include "nsIStreamListener.h"
#include "nsIJARProtocolHandler.h"
#include "nsIJARURI.h"
#include "nsIFileSystem.h"
#include "nsIChannel.h"
#include "nsIZipReader.h"
#include "nsIChannel.h"
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
#include "nsIFile.h"
#include "prmon.h"
class nsIFileChannel;
class nsJARChannel;
#define NS_JARCHANNEL_CID \
{ /* 0xc7e410d5-0x85f2-11d3-9f63-006008a6efe9 */ \
0xc7e410d5, \
0x85f2, \
0x11d3, \
{0x9f, 0x63, 0x00, 0x60, 0x08, 0xa6, 0xef, 0xe9} \
}
#define JAR_DIRECTORY "jarCache"
typedef nsresult
(*OnJARFileAvailableFun)(nsJARChannel* channel, void* closure);
class nsJARChannel : public nsIJARChannel,
public nsIStreamListener,
public nsIFileSystem
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
NS_DECL_NSICHANNEL
NS_DECL_NSIJARCHANNEL
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSISTREAMLISTENER
NS_DECL_NSIFILESYSTEM
nsJARChannel();
virtual ~nsJARChannel();
// Define a Create method to be used with a factory:
static NS_METHOD
Create(nsISupports* aOuter, REFNSIID aIID, void **aResult);
nsresult Init(nsIJARProtocolHandler* aHandler, nsIURI* uri);
nsresult EnsureJARFileAvailable(OnJARFileAvailableFun fun,
void* closure);
nsresult AsyncReadJARElement();
nsresult GetCacheFile(nsIFile* *cacheFile);
void SetJARBaseFile(nsIFileChannel* channel) { mJARBaseFile = channel; }
friend class nsJARDownloadObserver;
protected:
nsCOMPtr<nsIJARURI> mURI;
nsCOMPtr<nsILoadGroup> mLoadGroup;
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
nsCOMPtr<nsIURI> mOriginalURI;
nsLoadFlags mLoadAttributes;
nsCOMPtr<nsISupports> mOwner;
PRUint32 mStartPosition;
PRInt32 mReadCount;
nsCOMPtr<nsISupports> mUserContext;
nsCOMPtr<nsIStreamListener> mUserListener;
char* mContentType;
PRInt32 mContentLength;
nsCOMPtr<nsIURI> mJARBaseURI;
nsCOMPtr<nsIFileChannel> mJARBaseFile;
char* mJAREntry;
nsCOMPtr<nsIZipReader> mJAR;
PRUint32 mBufferSegmentSize;
PRUint32 mBufferMaxSize;
nsresult mStatus;
PRMonitor* mMonitor;
nsCOMPtr<nsIChannel> mJarCacheTransport;
nsCOMPtr<nsIChannel> mJarExtractionTransport;
};
#endif // nsJARChannel_h__

View File

@@ -1,138 +0,0 @@
/* -*- 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.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):
*/
#include "nsJARProtocolHandler.h"
#include "nsIIOService.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsJARURI.h"
#include "nsIURL.h"
#include "nsJARChannel.h"
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
static NS_DEFINE_CID(kJARUriCID, NS_JARURI_CID);
////////////////////////////////////////////////////////////////////////////////
nsJARProtocolHandler::nsJARProtocolHandler()
{
NS_INIT_REFCNT();
}
nsresult
nsJARProtocolHandler::Init()
{
return NS_OK;
}
nsJARProtocolHandler::~nsJARProtocolHandler()
{
}
NS_IMPL_ISUPPORTS2(nsJARProtocolHandler,
nsIJARProtocolHandler,
nsIProtocolHandler)
NS_METHOD
nsJARProtocolHandler::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsJARProtocolHandler* ph = new nsJARProtocolHandler();
if (ph == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(ph);
nsresult rv = ph->Init();
if (NS_SUCCEEDED(rv)) {
rv = ph->QueryInterface(aIID, aResult);
}
NS_RELEASE(ph);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIProtocolHandler methods:
NS_IMETHODIMP
nsJARProtocolHandler::GetScheme(char* *result)
{
*result = nsCRT::strdup("jar");
if (*result == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsJARProtocolHandler::GetDefaultPort(PRInt32 *result)
{
*result = -1; // no port for JAR: URLs
return NS_OK;
}
NS_IMETHODIMP
nsJARProtocolHandler::NewURI(const char *aSpec, nsIURI *aBaseURI,
nsIURI **result)
{
nsresult rv;
nsIURI* url;
if (aBaseURI) {
rv = aBaseURI->Clone(&url);
if (NS_FAILED(rv)) return rv;
rv = url->SetRelativePath(aSpec);
}
else {
rv = nsJARURI::Create(nsnull, NS_GET_IID(nsIJARURI), (void**)&url);
if (NS_FAILED(rv)) return rv;
rv = url->SetSpec((char*)aSpec);
}
if (NS_FAILED(rv)) {
NS_RELEASE(url);
return rv;
}
*result = url;
return rv;
}
NS_IMETHODIMP
nsJARProtocolHandler::NewChannel(nsIURI* uri, nsIChannel* *result)
{
nsresult rv;
nsJARChannel* channel;
rv = nsJARChannel::Create(nsnull, NS_GET_IID(nsIJARChannel), (void**)&channel);
if (NS_FAILED(rv)) return rv;
rv = channel->Init(this, uri);
if (NS_FAILED(rv)) {
NS_RELEASE(channel);
return rv;
}
*result = channel;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,57 +0,0 @@
/* -*- 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.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):
*/
#ifndef nsJARProtocolHandler_h___
#define nsJARProtocolHandler_h___
#include "nsIJARProtocolHandler.h"
#include "nsIProtocolHandler.h"
#include "nsIJARURI.h"
#define NS_JARPROTOCOLHANDLER_CID \
{ /* 0xc7e410d4-0x85f2-11d3-9f63-006008a6efe9 */ \
0xc7e410d4, \
0x85f2, \
0x11d3, \
{0x9f, 0x63, 0x00, 0x60, 0x08, 0xa6, 0xef, 0xe9} \
}
class nsJARProtocolHandler : public nsIJARProtocolHandler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROTOCOLHANDLER
// nsJARProtocolHandler methods:
nsJARProtocolHandler();
virtual ~nsJARProtocolHandler();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsresult Init();
protected:
};
#endif /* nsJARProtocolHandler_h___ */

View File

@@ -1,38 +0,0 @@
/* -*- 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.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):
*/
#include "nsIModule.h"
#include "nsIGenericFactory.h"
#include "nsJARProtocolHandler.h"
static nsModuleComponentInfo components[] =
{
{ "JAR Protocol Handler",
NS_JARPROTOCOLHANDLER_CID,
NS_NETWORK_PROTOCOL_PROGID_PREFIX "jar",
nsJARProtocolHandler::Create
},
};
NS_IMPL_NSGETMODULE("nsJarProtocolModule", components);

View File

@@ -1,384 +0,0 @@
/* -*- Mode: IDL; 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 "nsJARURI.h"
#include "nsNetUtil.h"
#include "nsIIOService.h"
#include "nsFileSpec.h"
#include "nsCRT.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIZipReader.h"
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
////////////////////////////////////////////////////////////////////////////////
nsJARURI::nsJARURI()
: mJAREntry(nsnull)
{
NS_INIT_REFCNT();
}
nsJARURI::~nsJARURI()
{
}
NS_IMPL_ISUPPORTS2(nsJARURI, nsIJARURI, nsIURI)
NS_METHOD
nsJARURI::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsJARURI* uri = new nsJARURI();
if (uri == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(uri);
nsresult rv = uri->Init();
if (NS_SUCCEEDED(rv)) {
rv = uri->QueryInterface(aIID, aResult);
}
NS_RELEASE(uri);
return rv;
}
nsresult
nsJARURI::Init()
{
return NS_OK;
}
#define NS_JAR_SCHEME "jar:"
#define NS_JAR_DELIMITER "!/"
nsresult
nsJARURI::FormatSpec(const char* entryPath, char* *result)
{
nsresult rv;
char* jarFileSpec;
rv = mJARFile->GetSpec(&jarFileSpec);
if (NS_FAILED(rv)) return rv;
nsCString spec(NS_JAR_SCHEME);
spec += jarFileSpec;
nsCRT::free(jarFileSpec);
spec += NS_JAR_DELIMITER;
spec += entryPath;
*result = nsCRT::strdup(spec);
return *result ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
////////////////////////////////////////////////////////////////////////////////
// nsURI methods:
NS_IMETHODIMP
nsJARURI::GetSpec(char* *aSpec)
{
return FormatSpec(mJAREntry, aSpec);
}
NS_IMETHODIMP
nsJARURI::SetSpec(const char * aSpec)
{
nsresult rv;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
PRUint32 startPos, endPos;
rv = serv->ExtractScheme(aSpec, &startPos, &endPos, nsnull);
if (NS_FAILED(rv)) return rv;
if (nsCRT::strncmp("jar", &aSpec[startPos], endPos - startPos - 1) != 0)
return NS_ERROR_MALFORMED_URI;
// Search backward from the end for the "!/" delimiter. Remember, jar URLs
// can nest, e.g.:
// jar:jar:http://www.foo.com/bar.jar!/a.jar!/b.html
// This gets the b.html document from out of the a.jar file, that's
// contained within the bar.jar file.
nsCAutoString jarPath(aSpec);
PRInt32 pos = jarPath.RFind(NS_JAR_DELIMITER);
if (pos == -1 || endPos + 1 > (PRUint32)pos)
return NS_ERROR_MALFORMED_URI;
jarPath.Cut(pos, jarPath.Length());
jarPath.Cut(0, endPos);
rv = serv->NewURI(jarPath, nsnull, getter_AddRefs(mJARFile));
if (NS_FAILED(rv)) return rv;
nsCAutoString entry(aSpec);
entry.Cut(0, pos + 2); // 2 == strlen(NS_JAR_DELIMITER)
rv = serv->ResolveRelativePath(entry, nsnull, &mJAREntry);
return rv;
}
NS_IMETHODIMP
nsJARURI::GetScheme(char * *aScheme)
{
*aScheme = nsCRT::strdup("jar");
return *aScheme ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
NS_IMETHODIMP
nsJARURI::SetScheme(const char * aScheme)
{
// doesn't make sense to set the scheme of a jar: URL
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetUsername(char * *aUsername)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetUsername(const char * aUsername)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetPassword(char * *aPassword)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetPassword(const char * aPassword)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetPreHost(char * *aPreHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetPreHost(const char * aPreHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetHost(char * *aHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetHost(const char * aHost)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetPort(PRInt32 *aPort)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetPort(PRInt32 aPort)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetPath(char * *aPath)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetPath(const char * aPath)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::GetURLParser(nsIURLParser * *aURLParser)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::SetURLParser(nsIURLParser * aURLParser)
{
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP
nsJARURI::Equals(nsIURI *other, PRBool *result)
{
nsresult rv;
*result = PR_FALSE;
nsJARURI* otherJAR;
rv = other->QueryInterface(NS_GET_IID(nsIJARURI), (void**)&otherJAR);
if (NS_FAILED(rv))
return NS_OK; // not equal
nsCOMPtr<nsIURI> otherJARFile;
rv = otherJAR->GetJARFile(getter_AddRefs(otherJARFile));
if (NS_FAILED(rv)) return rv;
PRBool equal;
rv = mJARFile->Equals(otherJARFile, &equal);
if (NS_FAILED(rv)) return rv;
if (!equal)
return NS_OK; // not equal
char* otherJAREntry;
rv = otherJAR->GetJAREntry(&otherJAREntry);
if (NS_FAILED(rv)) return rv;
*result = nsCRT::strcmp(mJAREntry, otherJAREntry) == 0;
nsCRT::free(otherJAREntry);
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::Clone(nsIURI **result)
{
nsresult rv;
nsCOMPtr<nsIURI> newJARFile;
rv = mJARFile->Clone(getter_AddRefs(newJARFile));
if (NS_FAILED(rv)) return rv;
char* newJAREntry = nsCRT::strdup(mJAREntry);
if (newJAREntry == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsJARURI* uri = new nsJARURI();
if (uri == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(uri);
uri->mJARFile = newJARFile;
uri->mJAREntry = newJAREntry;
*result = uri;
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::SetRelativePath(const char *relativePath)
{
nsresult rv;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCAutoString path(mJAREntry);
PRInt32 pos = path.RFind("/");
if (pos >= 0)
path.Truncate(pos + 1);
else
path = "";
char* resolvedEntry;
rv = serv->ResolveRelativePath(relativePath, path.GetBuffer(),
&resolvedEntry);
if (NS_FAILED(rv)) return rv;
nsCRT::free(mJAREntry);
mJAREntry = resolvedEntry;
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::Resolve(const char *relativePath, char **result)
{
nsresult rv;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
nsCAutoString path(mJAREntry);
PRInt32 pos = path.RFind("/");
if (pos >= 0)
path.Truncate(pos + 1);
else
path = "";
char* resolvedEntry;
rv = serv->ResolveRelativePath(relativePath, path.GetBuffer(),
&resolvedEntry);
if (NS_FAILED(rv)) return rv;
rv = FormatSpec(resolvedEntry, result);
nsCRT::free(resolvedEntry);
return rv;
}
////////////////////////////////////////////////////////////////////////////////
// nsIJARUri methods:
NS_IMETHODIMP
nsJARURI::GetJARFile(nsIURI* *jarFile)
{
*jarFile = mJARFile;
NS_ADDREF(*jarFile);
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::SetJARFile(nsIURI* jarFile)
{
mJARFile = jarFile;
return NS_OK;
}
NS_IMETHODIMP
nsJARURI::GetJAREntry(char* *entryPath)
{
nsCAutoString entry(mJAREntry);
PRInt32 pos = entry.RFindCharInSet("#?;");
if (pos >= 0)
entry.Truncate(pos);
*entryPath = entry.ToNewCString();
return *entryPath ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
NS_IMETHODIMP
nsJARURI::SetJAREntry(const char* entryPath)
{
nsresult rv;
NS_WITH_SERVICE(nsIIOService, serv, kIOServiceCID, &rv);
if (NS_FAILED(rv)) return rv;
if (mJAREntry)
nsCRT::free(mJAREntry);
rv = serv->ResolveRelativePath(entryPath, nsnull, &mJAREntry);
return rv;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,55 +0,0 @@
/* -*- Mode: IDL; 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 nsJARURI_h__
#define nsJARURI_h__
#include "nsIJARURI.h"
#include "nsCOMPtr.h"
#define NS_JARURI_CID \
{ /* 0xc7e410d7-0x85f2-11d3-9f63-006008a6efe9 */ \
0xc7e410d7, \
0x85f2, \
0x11d3, \
{0x9f, 0x63, 0x00, 0x60, 0x08, 0xa6, 0xef, 0xe9} \
}
class nsJARURI : public nsIJARURI
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIURI
NS_DECL_NSIJARURI
// nsJARURI
nsJARURI();
virtual ~nsJARURI();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsresult Init();
nsresult FormatSpec(const char* entryPath, char* *result);
protected:
nsCOMPtr<nsIURI> mJARFile;
char *mJAREntry;
};
#endif // nsJARURI_h__

View File

@@ -1,45 +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
DIRS = \
cache \
base \
dns \
socket \
build \
protocol \
mime \
streamconv \
$(NULL)
ifdef ENABLE_TESTS
DIRS += test
endif
include $(topsrcdir)/config/rules.mk

View File

@@ -1,32 +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
DIRS = public src
include $(topsrcdir)/config/rules.mk

View File

@@ -1,31 +0,0 @@
#!gmake
#
# 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 = ..\..
MODULE = necko
DIRS= \
public \
src \
$(NULL)
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,7 +0,0 @@
#
# This is a list of local files which get copied to the mozilla:dist directory
#
netCore.h
nsNetUtil.h
nsUnixColorPrintf.h

View File

@@ -1,17 +0,0 @@
#
# This is a list of local files which get copied to the mozilla:dist directory
#
nsIStreamListener.idl
nsIStreamObserver.idl
nsIURI.idl
nsIURL.idl
nsIChannel.idl
nsIRequest.idl
nsISocketTransportService.idl
nsIFileTransportService.idl
nsIFileSystem.idl
nsIPrompt.idl
nsIStreamLoader.idl
nsIURLParser.idl
nsIProtocolProxyService.idl

View File

@@ -1,67 +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 = necko
XPIDL_MODULE = necko_base
XPIDLSRCS = \
nsIFileStreams.idl \
nsIRequest.idl \
nsIChannel.idl \
nsIURI.idl \
nsIURL.idl \
nsIStreamObserver.idl \
nsIStreamListener.idl \
nsIIOService.idl \
nsIPrompt.idl \
nsIProtocolHandler.idl \
nsIProgressEventSink.idl \
nsINetModRegEntry.idl \
nsINetModuleMgr.idl \
nsINetNotify.idl \
nsILoadGroup.idl \
nsIFileTransportService.idl \
nsISocketTransportService.idl \
nsIStatusCodeEventSink.idl \
nsIFileSystem.idl \
nsIStreamLoader.idl \
nsINetPrompt.idl \
nsISocketTransport.idl \
nsIURLParser.idl \
nsIProxy.idl \
nsIProtocolProxyService.idl \
$(NULL)
EXPORTS = \
netCore.h \
nsNetUtil.h \
nsUnixColorPrintf.h \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,66 +0,0 @@
#!gmake
#
# 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):
MODULE = necko
DEPTH = ..\..\..
include <$(DEPTH)/config/config.mak>
EXPORTS = \
netCore.h \
nsNetUtil.h \
nsUnixColorPrintf.h \
$(NULL)
XPIDLSRCS = \
.\nsIFileStreams.idl \
.\nsIRequest.idl \
.\nsIChannel.idl \
.\nsIURI.idl \
.\nsIURL.idl \
.\nsIStreamObserver.idl \
.\nsIStreamListener.idl \
.\nsIIOService.idl \
.\nsIPrompt.idl \
.\nsIProtocolHandler.idl \
.\nsIProgressEventSink.idl \
.\nsINetModRegEntry.idl \
.\nsINetModuleMgr.idl \
.\nsINetNotify.idl \
.\nsILoadGroup.idl \
.\nsISocketTransportService.idl \
.\nsIFileTransportService.idl \
.\nsIStatusCodeEventSink.idl \
.\nsIFileSystem.idl \
.\nsIStreamLoader.idl \
.\nsINetPrompt.idl \
.\nsISocketTransport.idl \
.\nsIURLParser.idl \
.\nsIProxy.idl \
.\nsIProtocolProxyService.idl \
$(NULL)
include <$(DEPTH)/config/rules.mak>
$(DEPTH)\netwerk\dist\include:
-mkdir $(DEPTH)\netwerk\dist
-mkdir $(DEPTH)\netwerk\dist\include

View File

@@ -1,64 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* 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):
*/
#ifndef __netCore_h__
#define __netCore_h__
#include "nsError.h"
/* networking error codes */
// NET RANGE: 1 -20
// FTP RANGE: 21-30
// HTTP RANGE: 31-40
// DNS RANGE: 41-50
#define NS_ERROR_ALREADY_CONNECTED \
NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 11)
#define NS_ERROR_NOT_CONNECTED \
NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 12)
/* NS_ERROR_CONNECTION_REFUSED and NS_ERROR_NET_TIMEOUT moved to nsISocketTransportService.idl */
#define NS_ERROR_IN_PROGRESS \
NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 15)
#define NS_ERROR_OFFLINE \
NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 16)
#undef NS_NET
#ifdef _IMPL_NS_NET
#ifdef XP_PC
#define NS_NET _declspec(dllexport)
#else /* !XP_PC */
#define NS_NET
#endif /* !XP_PC */
#else /* !_IMPL_NS_NET */
#ifdef XP_PC
#define NS_NET _declspec(dllimport)
#else /* !XP_PC */
#define NS_NET
#endif /* !XP_PC */
#endif /* !_IMPL_NS_NET */
#endif // __netCore_h__

View File

@@ -1,403 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsIRequest.idl"
interface nsIURI;
interface nsIInputStream;
interface nsIOutputStream;
interface nsIStreamObserver;
interface nsIStreamListener;
interface nsILoadGroup;
interface nsIInterfaceRequestor;
interface nsIFile;
typedef unsigned long nsLoadFlags;
/**
* The nsIChannel interface allows the user to construct I/O requests for
* specific protocols, and manage them in a uniform way. Once a channel
* is created (via nsIIOService::NewChannel), parameters for that request
* may be set by using the channel attributes, or by QueryInterfacing to a
* subclass of nsIChannel for protocol-specific parameters. Then the actual
* request can be issued in one of several ways:
*
* - AsyncRead and AsyncWrite allow for asynchronous requests, calling
* back the user's stream listener or observer,
* - OpenInputStream and OpenOutputStream allow for synchronous reads
* and writes on the underlying channel.
*
* After a request has been completed, the channel is still valid for
* accessing protocol-specific results. For example, QueryInterfacing to
* nsIHTTPChannel allows response headers to be retrieved that result from
* http transactions.
*
* Note that a channel is really only valid for one request. Reusing a channel
* after a request has completed for a subsequent request may have undefined
* results, depending on the channel implementation.
*
* Also of note are a special kind of channel called "transports." Transports
* also implement the nsIChannel interface, but operate at a lower level from
* protocol channels. The socket and file transports are notable implementations
* of transports and allow higher level channels to be implemented. The cache
* may also behave as a transport, and possibly things like sound playing services
* etc. Transports usually operate in a separate thread and often multiplex
* multiple requests for the same kind of service or resources.
*/
[scriptable, uuid(1788e79e-f947-11d3-8cda-0060b0fc14a3)]
interface nsIChannel : nsIRequest
{
////////////////////////////////////////////////////////////////////////////
// nsIChannel accessors
////////////////////////////////////////////////////////////////////////////
/**
* Returns the original URL used to construct the channel.
* This is used in the case of a redirect or URI "resolution" (e.g.
* resolving a resource: URI to a file: URI) so that the original
* pre-redirect URI can still be obtained.
*
* Note that this is distinctly different from the http referrer
* (referring URI) which is typically the page that contained the
* original URI (accessible from nsIHTTPChannel).
*/
attribute nsIURI originalURI;
/**
* Returns the URL to which the channel currently refers. If a redirect
* or URI resolution occurs, this accessor returns the current location
* to which the channel is referring.
*/
attribute nsIURI URI;
/**
* Accesses the start offset from the beginning of the data from/to which
* reads/writes will occur. Users may set the transferOffset before making
* any of the following requests: asyncOpen, asyncRead, asyncWrite,
* openInputStream, openOutputstream.
*/
attribute unsigned long transferOffset;
/**
* Accesses the count of bytes to be transfered. For openInputStream and
* asyncRead, this specifies the amount to read, for asyncWrite, this
* specifies the amount to write (note that for openOutputStream, the
* end of the data can be signified simply by closing the stream).
* If the transferCount is set after reading has been initiated, the
* amount specified will become the current remaining amount to read
* before the channel is closed (this can be useful if the content
* length is encoded at the start of the stream).
*
* A transferCount value of -1 means the amount is unspecified, i.e.
* read or write all the data that is available.
*/
attribute long transferCount;
/**
* Accesses the load attributes for the channel. E.g. setting the load
* attributes with the LOAD_QUIET bit set causes the loading process to
* not deliver status notifications to the program performing the load,
* and to not contribute to keeping any nsILoadGroup it may be contained
* in from firing its OnLoadComplete notification.
*/
attribute nsLoadFlags loadAttributes;
/**
* Returns the content MIME type of the channel if available. Note that the
* content type can often be wrongly specified (wrong file extension, wrong
* MIME type, wrong document type stored on a server, etc.) and the caller
* most likely wants to verify with the actual data.
*/
attribute string contentType;
/**
* Returns the length of the data associated with the channel if available.
* If the length is unknown then -1 is returned.
*/
attribute long contentLength;
/**
* Accesses the owner corresponding to the entity that is
* responsible for this channel. Used by security code to grant
* or deny privileges to mobile code loaded from this channel.
*
* Note: This is a strong reference to the owner, so if the owner is also
* holding a pointer to the channel, care must be taken to explicitly drop
* its reference to the channel -- otherwise a leak will result.
*/
attribute nsISupports owner;
/**
* Accesses the load group in which the channel is a currently a member.
*/
attribute nsILoadGroup loadGroup;
/**
* Accesses the capabilities callbacks of the channel. This is set by clients
* who wish to provide a means to receive progress, status and protocol-specific
* notifications.
*/
attribute nsIInterfaceRequestor notificationCallbacks;
/**
* Any security information about this channel. This can be null.
*/
readonly attribute nsISupports securityInfo;
/**
* Accesses the buffer segment size. The buffer segment size is used as
* the initial size for any transfer buffers, and the increment size for
* whenever the buffer space needs to be grown.
* (Note this parameter is passed along to any underlying nsIPipe objects.)
* If unspecified, the channel implementation picks a default.
*/
attribute unsigned long bufferSegmentSize;
/**
* Accesses the buffer maximum size. The buffer maximum size is the limit
* size that buffer will be grown to before suspending the channel.
* (Note this parameter is passed along to any underlying nsIPipe objects.)
* If unspecified, the channel implementation picks a default.
*/
attribute unsigned long bufferMaxSize;
/**
* Returns true if the data from this channel should be cached. Local files
* report false because they exist on the local disk and need not be cached.
* Input stream channels, data protocol, datetime protocol and finger
* protocol channels also should not be cached. Http and ftp on the other
* hand should. Note that the value of this attribute doesn't reflect any
* http headers that may specify that this channel should not be cached.
*/
readonly attribute boolean shouldCache;
/**
* Setting pipeliningAllowed causes the load of a URL (issued via asyncOpen,
* asyncRead or asyncWrite) to be deferred in order to allow the request to
* be pipelined for greater throughput efficiency. Pipelined requests will
* be forced to load when the first non-pipelined request is issued.
*/
attribute boolean pipeliningAllowed;
////////////////////////////////////////////////////////////////////////////
// Load attribute flags. These may be or'd together.
////////////////////////////////////////////////////////////////////////////
/**
* Note that more will follow for each protocol's implementation of a channel,
* although channel writers have to be careful to not let the flag bits
* overlap. Otherwise, users won't be able to create a single flag word
* of load attributes that applies to a number of different channel types.
*/
/**
* No special load attributes -- use defaults:
*/
const unsigned long LOAD_NORMAL = 0;
/**
* Don't deliver status notifications to the nsIProgressEventSink, or keep
* this load from completing the nsILoadGroup it may belong to:
*/
const unsigned long LOAD_BACKGROUND = 1 << 0;
const unsigned long LOAD_DOCUMENT_URI = 1 << 1;
/**
* If the end consumer for this load has been retargeted after discovering
* it's content, this flag will be set:
*/
const unsigned long LOAD_RETARGETED_DOCUMENT_URI = 1 << 2;
////////////////////////////////////////////////////////////////////////////
/**
* The following flags control caching behavior. Not all protocols pay
* attention to all these flags, but they are applicable to more than one
* protocol, so they are defined here.
*/
/**
* Don't store data in the disk cache. This can be used to preserve
* privacy, e.g. so that no https transactions are recorded, or to avoid
* caching a stream to disk that is already stored in a local file,
* e.g. the mailbox: protocol.
*/
const unsigned long INHIBIT_PERSISTENT_CACHING = 1 << 8;
/**
* Force an end-to-end download of content data from the origin server (and
* any intervening proxies that sit between it and the client), e.g. this
* flag is used for a shift-reload.
*/
const unsigned long FORCE_RELOAD = 1 << 9;
/**
* Force revalidation with server (or proxy) to verify that cached content
* is up-to-date, e.g. by comparing last-modified date on server with that
* of the cached version. For example, this flag is used when the reload
* button is pressed.
*/
const unsigned long FORCE_VALIDATION = 1 << 10;
/**
* If the CACHE_AS_FILE flag is set, any stream content is stored in the
* cache as a single disk file. Content will not be cached in the memory
* cache nor will it be stored in any other type of cache, e.g. a flat-file
* cache database. This is used to implement the jar protocol handler and
* to provide the stream-as-file semantics required by the classic browser
* plugin API.
*/
const unsigned long CACHE_AS_FILE = 1 << 11;
/**
* When cache data is potentially out of date, it can be revalidated with
* the origin server to see if the content needs to be reloaded. The
* following four flags control how often this validation occurs.
* These flags are commonly used for "normal" loading. Note that
* the VALIDATE_HEURISTICALLY and VALIDATE_ONCE_PER_SESSION flags can be
* combined to validate heuristically but no more than once per session.
*/
const unsigned long VALIDATE_NEVER = 1 << 12;
const unsigned long VALIDATE_ALWAYS = 1 << 13;
const unsigned long VALIDATE_ONCE_PER_SESSION = 1 << 14;
const unsigned long VALIDATE_HEURISTICALLY = 1 << 15;
////////////////////////////////////////////////////////////////////////////
// nsIChannel operations
////////////////////////////////////////////////////////////////////////////
/**
* Opens a blocking input stream to the URL's specified source.
* @param startPosition - The offset from the start of the data
* from which to read.
* @param readCount - The number of bytes to read. If -1, everything
* up to the end of the data is read. If greater than the end of
* the data, the amount available is returned in the stream.
*/
nsIInputStream openInputStream();
/**
* Opens a blocking output stream to the URL's specified destination.
* @param startPosition - The offset from the start of the data
* from which to begin writing.
*/
nsIOutputStream openOutputStream();
/**
* Opens the channel asynchronously. The nsIStreamObserver's OnStartRequest
* method is called back when the channel actually becomes open, providing
* the content type. Its OnStopRequest method is called when the channel
* becomes closed.
*/
void asyncOpen(in nsIStreamObserver observer,
in nsISupports ctxt);
/**
* Reads asynchronously from the URL's specified source. Notifications
* are provided to the stream listener on the thread of the specified
* event queue.
* The startPosition argument designates the offset in the source where
* the data will be read.
* If the readCount == -1 then all the available data is delivered to
* the stream listener.
*/
void asyncRead(in nsIStreamListener listener,
in nsISupports ctxt);
/**
* Writes asynchronously to the URL's specified destination. Notifications
* are provided to the stream observer on the thread of the specified
* event queue.
* The startPosition argument designates the offset in the destination where
* the data will be written.
* If the writeCount == -1, then all the available data in the input
* stream is written.
*/
void asyncWrite(in nsIInputStream fromStream,
in nsIStreamObserver observer,
in nsISupports ctxt);
};
////////////////////////////////////////////////////////////////////////////////
/**
* nsIInputStreamChannel is an interface that allows for the initialization
* of a simple nsIChannel that is constructed from a single input stream and
* associated content type. Input stream channels only allow the input stream
* to be accessed, not the output stream.
*/
[scriptable, uuid(43070d6a-f947-11d3-8cda-0060b0fc14a3)]
interface nsIInputStreamChannel : nsIChannel
{
void init(in nsIURI uri,
in nsIInputStream inStr,
in string contentType,
in long contentLength);
};
%{C++
#define NS_INPUTSTREAMCHANNEL_CID \
{ /* 54d0d8e6-f947-11d3-8cda-0060b0fc14a3 */ \
0x54d0d8e6, \
0xf947, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}
////////////////////////////////////////////////////////////////////////////////
/**
* nsIFileChannel is an interface that allows for the initialization
* of a simple nsIChannel that is constructed from a single nsIFile and
* associated content type.
*/
[scriptable, uuid(68a26506-f947-11d3-8cda-0060b0fc14a3)]
interface nsIFileChannel : nsIChannel
{
void init(in nsIFile file,
in long ioFlags,
in long perm);
readonly attribute nsIFile file;
attribute long ioFlags;
attribute long permissions;
};
%{C++
#define NS_LOCALFILECHANNEL_CLASSNAME "Local File Channel"
#define NS_LOCALFILECHANNEL_PROGID "component://netscape/network/local-file-channel"
#define NS_LOCALFILECHANNEL_CID \
{ /* 6d5b2d44-f947-11d3-8cda-0060b0fc14a3 */ \
0x6d5b2d44, \
0xf947, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,30 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
[scriptable, uuid(fb65fd70-1881-11d3-9337-00104ba0fd40)]
interface nsIEventSinkGetter : nsISupports
{
nsISupports getEventSink(in string command, in nsIIDRef eventSinkIID);
};

View File

@@ -1,241 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsIInputStream.idl"
#include "nsIOutputStream.idl"
#include "nsILocalFile.idl"
[scriptable, uuid(e3d56a20-c7ec-11d3-8cda-0060b0fc14a3)]
interface nsIFileInputStream : nsIInputStream
{
void init(in nsIFile file, in long ioFlags, in long perm);
};
[scriptable, uuid(e6f68040-c7ec-11d3-8cda-0060b0fc14a3)]
interface nsIFileOutputStream : nsIOutputStream
{
void init(in nsIFile file, in long ioFlags, in long perm);
};
[scriptable, uuid(e9de5df0-c7ec-11d3-8cda-0060b0fc14a3)]
interface nsISeekableStream : nsISupports
{
// correspond to PRSeekWhence values
const long NS_SEEK_SET = 0;
const long NS_SEEK_CUR = 1;
const long NS_SEEK_END = 2;
void seek(in long whence, in long offset);
unsigned long tell();
};
[scriptable, uuid(616f5b48-da09-11d3-8cda-0060b0fc14a3)]
interface nsIBufferedInputStream : nsIInputStream
{
void init(in nsIInputStream fillFromStream,
in unsigned long bufferSize);
};
[scriptable, uuid(6476378a-da09-11d3-8cda-0060b0fc14a3)]
interface nsIBufferedOutputStream : nsIOutputStream
{
void init(in nsIOutputStream sinkToStream,
in unsigned long bufferSize);
};
%{C++
////////////////////////////////////////////////////////////////////////////////
#define NS_LOCALFILEINPUTSTREAM_CLASSNAME "Local File Input Stream"
#define NS_LOCALFILEINPUTSTREAM_PROGID "component://netscape/network/file-input-stream"
#define NS_LOCALFILEINPUTSTREAM_CID \
{ /* be9a53ae-c7e9-11d3-8cda-0060b0fc14a3 */ \
0xbe9a53ae, \
0xc7e9, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
#define NS_LOCALFILEOUTPUTSTREAM_CLASSNAME "Local File Output Stream"
#define NS_LOCALFILEOUTPUTSTREAM_PROGID "component://netscape/network/file-output-stream"
#define NS_LOCALFILEOUTPUTSTREAM_CID \
{ /* c272fee0-c7e9-11d3-8cda-0060b0fc14a3 */ \
0xc272fee0, \
0xc7e9, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
////////////////////////////////////////////////////////////////////////////////
#define NS_BUFFEREDINPUTSTREAM_CLASSNAME "Buffered Input Stream"
#define NS_BUFFEREDINPUTSTREAM_PROGID "component://netscape/network/buffered-input-stream"
#define NS_BUFFEREDINPUTSTREAM_CID \
{ /* 9226888e-da08-11d3-8cda-0060b0fc14a3 */ \
0x9226888e, \
0xda08, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
#define NS_BUFFEREDOUTPUTSTREAM_CLASSNAME "Buffered Output Stream"
#define NS_BUFFEREDOUTPUTSTREAM_PROGID "component://netscape/network/buffered-output-stream"
#define NS_BUFFEREDOUTPUTSTREAM_CID \
{ /* 9868b4ce-da08-11d3-8cda-0060b0fc14a3 */ \
0x9868b4ce, \
0xda08, \
0x11d3, \
{0x8c, 0xda, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
////////////////////////////////////////////////////////////////////////////////
// move to nsNetUtil.h later...
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsCOMPtr.h"
#include "nsIServiceManager.h"
#include "nsIChannel.h"
#include "nsILocalFile.h"
#include "nsIInputStream.h"
#include "nsIOutputStream.h"
#include "prio.h" // for read/write flags, permissions, etc.
// This will QI the file argument to an nsILocalFile in the Init method.
inline nsresult
NS_NewLocalFileChannel(nsIFileChannel **result,
nsIFile* file,
PRInt32 ioFlags = -1,
PRInt32 perm = -1)
{
nsresult rv;
nsCOMPtr<nsIFileChannel> channel;
static NS_DEFINE_CID(kLocalFileChannelCID, NS_LOCALFILECHANNEL_CID);
rv = nsComponentManager::CreateInstance(kLocalFileChannelCID,
nsnull,
NS_GET_IID(nsIFileChannel),
getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->Init(file, ioFlags, perm);
if (NS_FAILED(rv)) return rv;
*result = channel;
NS_ADDREF(*result);
return NS_OK;
}
// This will QI the file argument to an nsILocalFile in the Init method.
inline nsresult
NS_NewLocalFileInputStream(nsIInputStream* *result,
nsIFile* file,
PRInt32 ioFlags = -1,
PRInt32 perm = -1)
{
nsresult rv;
nsCOMPtr<nsIFileInputStream> in;
static NS_DEFINE_CID(kLocalFileInputStreamCID, NS_LOCALFILEINPUTSTREAM_CID);
rv = nsComponentManager::CreateInstance(kLocalFileInputStreamCID,
nsnull,
NS_GET_IID(nsIFileInputStream),
getter_AddRefs(in));
if (NS_FAILED(rv)) return rv;
rv = in->Init(file, ioFlags, perm);
if (NS_FAILED(rv)) return rv;
*result = in;
NS_ADDREF(*result);
return NS_OK;
}
// This will QI the file argument to an nsILocalFile in the Init method.
inline nsresult
NS_NewLocalFileOutputStream(nsIOutputStream* *result,
nsIFile* file,
PRInt32 ioFlags = -1,
PRInt32 perm = -1)
{
nsresult rv;
nsCOMPtr<nsIFileOutputStream> out;
static NS_DEFINE_CID(kLocalFileOutputStreamCID, NS_LOCALFILEOUTPUTSTREAM_CID);
rv = nsComponentManager::CreateInstance(kLocalFileOutputStreamCID,
nsnull,
NS_GET_IID(nsIFileOutputStream),
getter_AddRefs(out));
if (NS_FAILED(rv)) return rv;
rv = out->Init(file, ioFlags, perm);
if (NS_FAILED(rv)) return rv;
*result = out;
NS_ADDREF(*result);
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
inline nsresult
NS_NewBufferedInputStream(nsIInputStream* *result,
nsIInputStream* str,
PRUint32 bufferSize)
{
nsresult rv;
nsCOMPtr<nsIBufferedInputStream> in;
static NS_DEFINE_CID(kBufferedInputStreamCID, NS_BUFFEREDINPUTSTREAM_CID);
rv = nsComponentManager::CreateInstance(kBufferedInputStreamCID,
nsnull,
NS_GET_IID(nsIBufferedInputStream),
getter_AddRefs(in));
if (NS_FAILED(rv)) return rv;
rv = in->Init(str, bufferSize);
if (NS_FAILED(rv)) return rv;
*result = in;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewBufferedOutputStream(nsIOutputStream* *result,
nsIOutputStream* str,
PRUint32 bufferSize)
{
nsresult rv;
nsCOMPtr<nsIBufferedOutputStream> out;
static NS_DEFINE_CID(kBufferedOutputStreamCID, NS_BUFFEREDOUTPUTSTREAM_CID);
rv = nsComponentManager::CreateInstance(kBufferedOutputStreamCID,
nsnull,
NS_GET_IID(nsIBufferedOutputStream),
getter_AddRefs(out));
if (NS_FAILED(rv)) return rv;
rv = out->Init(str, bufferSize);
if (NS_FAILED(rv)) return rv;
*result = out;
NS_ADDREF(*result);
return NS_OK;
}
%}

View File

@@ -1,40 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
interface nsIInputStream;
interface nsIOutputStream;
[scriptable, uuid(818e1370-77c4-11d3-9395-00104ba0fd40)]
interface nsIFileSystem : nsISupports
{
void open(out string contentType,
out long contentLength);
void close(in nsresult status);
readonly attribute nsIInputStream inputStream;
readonly attribute nsIOutputStream outputStream;
};

View File

@@ -1,65 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
%{C++
#include "nsFileSpec.h"
%}
interface nsIChannel;
interface nsIFileSystem;
interface nsIEventSinkGetter;
interface nsIInputStream;
interface nsIRunnable;
interface nsIFile;
[scriptable, uuid(57211a60-8c45-11d3-93ac-00104ba0fd40)]
interface nsIFileTransportService : nsISupports
{
nsIChannel createTransport(in nsIFile file,
in long ioFlags,
in long perm);
// This version can be used with an existing input stream to serve
// as a data pump:
nsIChannel createTransportFromStream(in nsIInputStream fromStream,
in string contentType,
in long contentLength);
nsIChannel createTransportFromFileSystem(in nsIFileSystem fsObj);
void dispatchRequest(in nsIRunnable runnable);
void suspend(in nsIRunnable trans);
void resume(in nsIRunnable trans);
void processPendingRequests();
void shutdown();
};
%{C++
#define NS_FILETRANSPORTSERVICE_CID \
{ /* 2bb2b250-ea35-11d2-931b-00104ba0fd40 */ \
0x2bb2b250, \
0xea35, \
0x11d2, \
{0x93, 0x1b, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
%}

View File

@@ -1,169 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
#include "nsIChannel.idl"
interface nsIProtocolHandler;
interface nsIURI;
interface nsIInterfaceRequestor;
interface nsIStreamObserver;
interface nsIStreamListener;
interface nsIEventQueue;
interface nsIBufferInputStream;
interface nsIInputStream;
interface nsIBufferOutputStream;
interface nsIFileChannel;
interface nsILoadGroup;
interface nsILoadGroupObserver;
interface nsIFile;
interface nsIInputStream;
interface nsIOutputStream;
[scriptable, uuid(ab7c3a84-d488-11d3-8cda-0060b0fc14a3)]
interface nsIIOService : nsISupports
{
/**
* Returns a protocol handler for a given URI scheme.
*/
nsIProtocolHandler getProtocolHandler(in string scheme);
/**
* This method constructs a new URI by first determining the scheme
* of the URI spec, and then delegating the construction of the URI
* to the protocol handler for that scheme. QueryInterface can be used
* on the resulting URI object to obtain a more specific type of URI.
*/
nsIURI newURI(in string aSpec, in nsIURI aBaseURI);
/**
* Creates a channel for a given URI. The notificationCallbacks argument
* is used to obtain the appropriate callbacks for the URI's protocol from the
* application.
*
* @param originalURI - Specifies the original URI which caused the creation
* of this channel. This can occur when the construction of one channel
* (e.g. for resource:) causes another channel to be created on its behalf
* (e.g. a file: channel), or if a redirect occurs, causing the current
* URL to become different from the original URL. If NULL, the aURI parameter
* will be used as the originalURI instead.
*/
nsIChannel newChannelFromURI(in nsIURI aURI);
/**
* Convenience routine that first creates a URI by calling NewURI, and
* then passes the URI to NewChannelFromURI.
*
* @param originalURI - Specifies the original URI which caused the creation
* of this channel. This can occur when the construction of one channel
* (e.g. for resource:) causes another channel to be created on its behalf
* (e.g. a file: channel), or if a redirect occurs, causing the current
* URL to become different from the original URL. If NULL, the aURI parameter
* will be used as the originalURI instead.
*/
nsIChannel newChannel(in string aSpec, in nsIURI aBaseURI);
/**
* Returns true if networking is in "offline" mode. When in offline mode, attempts
* to access the network will fail (although this is not necessarily corrolated with
* whether there is actually a network available -- that's hard to detect without
* causing the dialer to come up).
*/
attribute boolean offline;
////////////////////////////////////////////////////////////////////////////
// URL parsing utilities
/**
* Utility for protocol implementors -- extracts the scheme from a URL
* string, consistently and according to spec.
* @param urlString - the URL string to parse
* @param schemeStartPos - the resulting starting position of the scheme substring
* (may skip over whitespace)
* @param schemeEndPos - the resulting ending position of the scheme substring
* (the position of the colon)
* @param scheme - an allocated substring containing the scheme. If this parameter
* is null going into the routine, then the scheme is not allocated and
* returned. Free with nsCRT::free.
*
* @return NS_OK - if successful
* @return NS_ERROR_MALFORMED_URI - if the urlString is not of the right form
*/
void extractScheme(in string urlString,
out unsigned long schemeStartPos,
out unsigned long schemeEndPos,
out string scheme);
/**
* Constants for the mask in the call to Escape
*/
const short url_Scheme = (1<<0);
const short url_Username = (1<<1);
const short url_Password = (1<<2);
const short url_Host = (1<<3);
const short url_Directory = (1<<4);
const short url_FileBaseName = (1<<5);
const short url_FileExtension = (1<<6);
const short url_Param = (1<<7);
const short url_Query = (1<<8);
const short url_Ref = (1<<9);
const short url_Forced = (1<<10);
/**
* Encode characters into % escaped hexcodes.
*/
string escape(in string str, in short mask);
/**
* Decode % escaped hex codes into character values.
*/
string unescape(in string str);
/**
* Get port from string.
*/
long extractPort(in string str);
/**
* Resolves a relative path string containing "." and ".."
* with respect to a base path (assumed to already be resolved).
* For example, resolving "../../foo/./bar/../baz.html" w.r.t.
* "/a/b/c/d/e/" yields "/a/b/c/foo/baz.html". Attempting to
* ascend above the base results in the NS_ERROR_MALFORMED_URI
* exception. If basePath is null, it treats it as "/".
*/
string resolveRelativePath(in string relativePath,
in string basePath);
};
%{C++
#define NS_IOSERVICE_CID \
{ /* 9ac9e770-18bc-11d3-9337-00104ba0fd40 */ \
0x9ac9e770, \
0x18bc, \
0x11d3, \
{0x93, 0x37, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
#define DUD 3.14
%}

View File

@@ -1,104 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsIRequest.idl"
interface nsIChannel;
interface nsISimpleEnumerator;
interface nsIStreamObserver;
interface nsIStreamListener;
interface nsIInputStream;
[scriptable, uuid(60fdf550-5392-11d3-9a97-0080c7cb1080)]
interface nsILoadGroupListenerFactory : nsISupports
{
nsIStreamListener createLoadGroupListener(in nsIStreamListener alistener);
};
/**
* A load group maintains a collection of active URL requests.
*/
[scriptable, uuid(19845248-29ab-11d3-8cce-0060b0fc14a3)]
interface nsILoadGroup : nsIRequest
{
void init(in nsIStreamObserver observer);
/**
* Accesses the default load attributes for the group, returned as
* a flag word. Setting the default load attributes will cause them
* to be applied to each new channel inserted into the group.
*/
attribute unsigned long defaultLoadAttributes;
/**
* Accesses the default load channel for the group. Each time a number
* of channels are added to a group, the DefaultLoadChannel may be set
* to indicate that all of the channels are related to a particular URL.
*/
attribute nsIChannel defaultLoadChannel;
/**
* Adds a new channel to the group. This will cause the default load
* attributes to be applied to that channel. If the channel added is
* the first channel in the group, the group's observer's OnStartRequest
* method is called.
*/
void addChannel(in nsIChannel channel,
in nsISupports ctxt);
/**
* Removes a channel from the group. If the channel removed is
* the last channel in the group, the group's observer's OnStopRequest
* method is called.
*/
void removeChannel(in nsIChannel channel,
in nsISupports ctxt,
in nsresult status,
in wstring errorMsg);
/**
* Returns the channels contained directly in this group.
* Enumerator element type: nsIChannel.
*/
readonly attribute nsISimpleEnumerator channels;
attribute nsIStreamObserver groupObserver;
attribute nsILoadGroupListenerFactory groupListenerFactory;
readonly attribute unsigned long activeCount;
};
%{C++
#define NS_LOADGROUP_CID \
{ /* e1c61582-2a84-11d3-8cce-0060b0fc14a3 */ \
0xe1c61582, \
0x2a84, \
0x11d3, \
{0x8c, 0xce, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}

View File

@@ -1,47 +0,0 @@
/* -*- Mode: IDL; 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.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):
*/
/* This interface defines a registry entry for the networking libraries
* external module registry. */
#include "nsISupports.idl"
#include "nsINetNotify.idl"
interface nsIEventQueue;
interface nsINetModRegEntry;
interface nsINetNotify;
%{ C++
// {F126BD90-1472-11d3-A15A-0050041CAF44}
#define NS_NETMODREGENTRY_CID \
{ 0xf126bd90, 0x1472, 0x11d3, { 0xa1, 0x5a, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } }
%}
[scriptable, uuid(9F482BD0-1476-11d3-A15A-0050041CAF44)]
interface nsINetModRegEntry : nsISupports
{
readonly attribute nsINetNotify syncProxy;
readonly attribute nsINetNotify asyncProxy;
readonly attribute string topic;
boolean equals(in nsINetModRegEntry aEntry);
};

View File

@@ -1,80 +0,0 @@
/* -*- Mode: IDL; 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.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):
*/
/* The nsINetModuleMgr singleton service allows external module to register
* themselves with the networking library to receive events they want to
* receive.
*
* An external module that is interested in being notified when a particular
* networking level event occurs would register with this service, and
* implement the appropriate interface(s) that correspond to the events they
* want to receive. These interfaces are defined by networking internal
* components (for example, http would define a notification interface that
* the external cookies module would implement).
*/
#include "nsISupports.idl"
#include "nsIEnumerator.idl"
#include "nsINetNotify.idl"
interface nsIEventQueue;
%{ C++
// {4EBDAFE0-13BA-11d3-A15A-0050041CAF44}
#define NS_NETMODULEMGR_CID \
{ 0x4ebdafe0, 0x13ba, 0x11d3, { 0xa1, 0x5a, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } }
// The list of available PROGIDS to register for notification on.
#define NS_NETWORK_MODULE_MANAGER_HTTP_REQUEST_PROGID "component://netscape/network/moduleMgr/http/request"
#define NS_NETWORK_MODULE_MANAGER_HTTP_RESPONSE_PROGID "component://netscape/network/moduleMgr/http/response"
%}
[scriptable, uuid(ff9ead40-0ef2-11d3-9de6-0010a4053fd0)]
interface nsINetModuleMgr : nsISupports {
// Register the external module to receive notifications.
//
// ARGUMENTS:
// aTopic: The internal component that the external module wants to monitor.
// aNotify: The external module interface methods to be called when an event is fired.
//
// RETURNS: nsresult
void registerModule(in string aTopic, in nsINetNotify aNotify);
// Unregister the external module. Removes the nsINetModuleMgr binding between
// internal component and external module.
//
// ARGUMENTS:
// aTopic: The internal component being monitored.
// aNotify: The external modules notification module.
//
// RETURNS: nsresult
void unregisterModule(in string aTopic, in nsINetNotify aNotify);
// Enumerates all the registered modules for the specified topic.
//
// ARGUMENTS:
// aTopic: the component to get all the notifiers for.
// aEnumerator: the array of notifiers.
void enumerateModules(in string aTopic, out nsISimpleEnumerator aEnumerator);
};

View File

@@ -1,28 +0,0 @@
/* -*- Mode: IDL; 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.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):
*/
#include "nsISupports.idl"
[uuid(4A3019E0-1CF3-11d3-A15B-0050041CAF44)]
interface nsINetNotify : nsISupports {
};

View File

@@ -1,76 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
[scriptable, uuid(edd8be01-8e0d-11d3-b7a0-c46e946292bc)]
interface nsINetPrompt : nsISupports
{
/**
* Puts up an alert dialog with an OK button.
*/
void alert( in string url, in boolean stripurl, in wstring title, in wstring text);
/**
* Puts up a dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean confirm( in string url, in boolean stripurl, in wstring title, in wstring text);
/**
* Puts up a username/password dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean promptUsernameAndPassword(
in string url,
in boolean stripurl,
in wstring title,
in wstring text,
out wstring user,
out wstring pwd);
/**
* Puts up a password dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean promptPassword(
in string url,
in boolean stripurl,
in wstring title,
in wstring text,
out wstring pwd);
/**
* Puts up a prompt dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean prompt(
in string url,
in boolean stripurl,
in wstring title,
in wstring text,
out wstring pwd);
};

View File

@@ -1,51 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
interface nsIURI;
interface nsIChannel;
/**
* An instance of nsIFfpEventSink should be passed as the eventSink
* argument of nsINetService::NewConnection for ftp URLs. It defines
* the callbacks to the application program (the html parser).
*/
[scriptable, uuid(dd47ee00-18c2-11d3-9337-00104ba0fd40)]
interface nsIProgressEventSink : nsISupports
{
/**
* Notify the EventSink that progress as occurred for the URL load.<BR>
*/
void onProgress(in nsIChannel channel,
in nsISupports ctxt,
in unsigned long aProgress,
in unsigned long aProgressMax);
/**
* Notify the EventSink with a status message for the URL load.<BR>
*/
void onStatus(in nsIChannel channel,
in nsISupports ctxt,
in wstring aMsg);
};

View File

@@ -1,102 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
[scriptable, uuid(a63f70c0-148b-11d3-9333-00104ba0fd40)]
interface nsIPrompt : nsISupports
{
/**
* Puts up an alert dialog with an OK button.
*/
void alert(in wstring text);
/**
* Puts up a dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean confirm(in wstring text);
/**
* Puts up a dialog with OK and Cancel buttons, and
* a message with a single checkbox.
* @return true for OK, false for Cancel
*/
boolean confirmCheck(in wstring text,
in wstring checkMsg,
out boolean checkValue);
/**
* Puts up a text input dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean prompt(in wstring text,
in wstring defaultText,
out wstring result);
/**
* Puts up a username/password dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean promptUsernameAndPassword(in wstring text,
out wstring user,
out wstring pwd);
/**
* Puts up a password dialog with OK and Cancel buttons.
* @return true for OK, false for Cancel
*/
boolean promptPassword(in wstring text,
in wstring title,
out wstring pwd);
/**
* Puts up a dialog box which has a list box of strings
*/
boolean select(in wstring inDialogTitle,
in wstring inMsg,
in PRUint32 inCount,
[array, size_is(inCount)] in wstring inList,
out long outSelection);
/**
* Put up a universal dialog
*/
void universalDialog(in wstring inTitleMessage,
in wstring inDialogTitle, /* e.g., alert, confirm, prompt, prompt password */
in wstring inMsg, /* main message for dialog */
in wstring inCheckboxMsg, /* message for checkbox */
in wstring inButton0Text, /* text for first button */
in wstring inButton1Text, /* text for second button */
in wstring inButton2Text, /* text for third button */
in wstring inButton3Text, /* text for fourth button */
in wstring inEditfield1Msg, /*message for first edit field */
in wstring inEditfield2Msg, /* message for second edit field */
inout wstring inoutEditfield1Value, /* initial and final value for first edit field */
inout wstring inoutEditfield2Value, /* initial and final value for second edit field */
in wstring inIConURL, /* url of icon to be displayed in dialog */
inout boolean inoutCheckboxState, /* initial and final state of checkbox */
in PRInt32 inNumberButtons, /* total number of buttons (0 to 4) */
in PRInt32 inNumberEditfields, /* total number of edit fields (0 to 2) */
in PRInt32 inEditField1Password, /* ??? */
out PRInt32 outButtonPressed); /* number of button that was pressed (0 to 3) */
};

View File

@@ -1,67 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
#include "nsIChannel.idl"
interface nsIURI;
interface nsIInterfaceRequestor;
interface nsILoadGroup;
[scriptable, uuid(15fd6940-8ea7-11d3-93ad-00104ba0fd40)]
interface nsIProtocolHandler : nsISupports
{
readonly attribute string scheme;
readonly attribute long defaultPort;
/**
* Makes a URI object that is suitable for loading by this protocol.
* In the usual case (when only the accessors provided by nsIURI are
* needed), this method just constructs a standard URI using the
* component manager with kStandardURLCID.
*/
nsIURI newURI(in string aSpec, in nsIURI aBaseURI);
/**
* Constructs a new channel for this protocol handler.
*
* @param originalURI - Specifies the original URI which caused the creation
* of this channel. This can occur when the construction of one channel
* (e.g. for resource:) causes another channel to be created on its behalf
* (e.g. a file: channel), or if a redirect occurs, causing the current
* URL to become different from the original URL. If NULL, the aURI parameter
* will be used as the originalURI instead.
*/
nsIChannel newChannel(in nsIURI aURI);
};
%{C++
#define NS_NETWORK_PROTOCOL_PROGID "component://netscape/network/protocol"
#define NS_NETWORK_PROTOCOL_PROGID_PREFIX NS_NETWORK_PROTOCOL_PROGID "?name="
#define NS_NETWORK_PROTOCOL_PROGID_PREFIX_LENGTH 43 // nsCRT::strlen(NS_NETWORK_PROTOCOL_PROGID_PREFIX)
// Unknown Protocol Error
#define NS_ERROR_UNKNOWN_PROTOCOL NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 18)
%}

View File

@@ -1,40 +0,0 @@
/* -*- Mode: IDL; 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.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):
*/
#include "nsISupports.idl"
#include "nsIURI.idl"
#include "nsIProxy.idl"
%{C++
#define NS_PROTOCOLPROXYSERVICE_CID \
{ /* E9B301C0-E0E4-11d3-A1A8-0050041CAF44 */ \
0xe9b301c0, 0xe0e4, 0x11d3, { 0xa1, 0xa8, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } }
%}
[scriptable, uuid(495CC980-E0D4-11d3-A1A8-0050041CAF44)]
interface nsIProtocolProxyService : nsISupports
{
readonly attribute PRBool proxyEnabled;
void examineForProxy(in nsIURI aURI, in nsIProxy aProxy);
};

View File

@@ -1,41 +0,0 @@
/* -*- Mode: IDL; 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.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):
*/
/*
The nsIProxy interface allows setting and getting of proxy host and port.
This is for use by protocol handlers. If you are writing a protocol handler
and would like to support proxy behaviour then derive from this as well as
the nsIProtocolHandler class.
-Gagan Saksena 02/25/99
*/
#include "nsISupports.idl"
[scriptable, uuid(0492D011-CD2F-11d2-B013-006097BFC036)]
interface nsIProxy : nsISupports
{
attribute string proxyHost;
/* -1 on Set call indicates switch to default port */
attribute long proxyPort;
};

View File

@@ -1,63 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
[scriptable, uuid(F2CAABA0-2F25-11d3-A164-0050041CAF44)]
interface nsIRequest : nsISupports
{
/**
* Returns true if the request is pending (active). Returns false
* after completion or successful calling Cancel. Suspended requests
* are still considered pending.
*/
boolean isPending();
/**
* Returns any error status associated with the request.
*/
readonly attribute nsresult status;
/**
* Cancels the current request. This will close any open input or
* output streams and terminate any async requests. Users should
* normally pass NS_BINDING_ABORTED, although other errors may also
* be passed. The error passed in will become the value of the
* status attribute.
*/
void cancel(in nsresult status);
/**
* Suspends the current requests. This may have the effect of closing
* any underlying transport (in order to free up resources), although
* any open streams remain logically opened and will continue delivering
* data when the transport is resumed.
*/
void suspend();
/**
* Resumes the current request. This may have the effect of re-opening
* any underlying transport and will resume the delivery of data to
* any open streams.
*/
void resume();
};

View File

@@ -1,55 +0,0 @@
/* -*- Mode: IDL; 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.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):
*/
#include "nsISupports.idl"
[scriptable, uuid(785CA0F0-C39E-11d3-9ED6-0010A4053FD0)]
interface nsISocketTransport : nsISupports
{
attribute boolean reuseConnection;
/**
* socket read/write timeout in seconds; 0 = no timeout
*/
attribute unsigned long socketTimeout;
/**
* socket connect timeout in seconds; 0 = no timeout
*/
attribute unsigned long socketConnectTimeout;
/**
* Is used to tell the channel to stop reading data after a certain point;
* needed by HTTP/1.1
*/
attribute long bytesExpected;
attribute unsigned long reuseCount;
/**
* Checks if the socket is still alive
*
* @param seconds amount of time after which the socket is always deemed to be
* dead (no further checking is done in this case); seconds = 0
* will cause it not to do the timeout checking at all
*/
boolean isAlive (in unsigned long seconds);
};

View File

@@ -1,77 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
interface nsIChannel;
interface nsIEventSinkGetter;
[scriptable, uuid(05331390-6884-11d3-9382-00104ba0fd40)]
interface nsISocketTransportService : nsISupports
{
/**
* Creates a transport for a specified host and port.
* The eventSinkGetter is used to get the appropriate callbacks
* for the socket activity from the application. These include
* the progress and the status messages like "Contacting host.."
* etc. The printHost contains the actual hostname (and not the
* proxy) for displaying in status messages.
*/
nsIChannel createTransport(in string host,
in long port,
in string printHost,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
nsIChannel createTransportOfType(in string socketType,
in string host,
in long port,
in string printHost,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
/**
* Returns true if the specified transport is good enough for
* being used again. The situations in which this may return false
* include- an error including server resets, an explicit
* Connection: close header (for HTTP) and timeouts!
*/
boolean reuseTransport(in nsIChannel i_Transport);
void init();
void shutdown();
void wakeup(in nsIChannel i_Transport);
};
%{C++
#define NS_SOCKETTRANSPORTSERVICE_CID \
{ /* c07e81e0-ef12-11d2-92b6-00105a1b0d64 */ \
0xc07e81e0, \
0xef12, \
0x11d2, \
{0x92, 0xb6, 0x00, 0x10, 0x5a, 0x1b, 0x0d, 0x64} \
}
#define NS_ERROR_CONNECTION_REFUSED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 13)
#define NS_ERROR_NET_TIMEOUT NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 14)
%}

View File

@@ -1,48 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
interface nsIProgressEventSink;
interface nsIChannel;
/**
* The nsIStatusCodeEventSink is a temporary interface to allow passing
* status codes from the socket threads onto the UI without having to
* pass strings. This could eventually go away if the proxy events
* stuff can handle nested event loop. dougt is working on that.
* We could continue to use this if this seems reasonable enough.
*/
[scriptable, uuid(6998ff36-1dd2-11b2-9ab7-e72a0f9fdd8c)]
interface nsIStatusCodeEventSink : nsISupports
{
/**
* Notify the EventSink with a status code for the URL load.<BR>
* Use IOService to request converting that code to a string.
*/
void onStatus(in nsIProgressEventSink sink,
in nsIChannel channel,
in nsISupports ctxt,
in unsigned long aCode);
};

View File

@@ -1,96 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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):
*/
#include "nsIStreamObserver.idl"
interface nsIBufferInputStream;
interface nsIInputStream;
interface nsIBufferOutputStream;
interface nsIEventQueue;
[scriptable, uuid(1a637020-1482-11d3-9333-00104ba0fd40)]
interface nsIStreamListener : nsIStreamObserver
{
void onDataAvailable(in nsIChannel channel,
in nsISupports ctxt,
in nsIInputStream inStr,
in unsigned long sourceOffset,
in unsigned long count);
};
/**
* An asynchronous stream listener is used to ship data over to another thread specified
* by the thread's event queue. The receiver stream listener is then used to receive
* the notifications on the other thread.
*
* This interface only provides the initialization needed after construction. Otherwise,
* these objects are used simply as nsIStreamListener.
*/
[scriptable, uuid(1b012ade-91bf-11d3-8cd9-0060b0fc14a3)]
interface nsIAsyncStreamListener : nsIStreamListener
{
/**
* Initializes an nsIAsyncStreamListener.
* @param eventQueue - may be null indicating the calling thread's event queue
*/
void init(in nsIStreamListener receiver,
in nsIEventQueue eventQueue);
};
/**
* A synchronous stream listener pushes data through a pipe that ends up
* in an input stream to be read by another thread.
*
* This interface only provides the initialization needed after construction. Otherwise,
* these objects are used simply as nsIStreamListener.
*/
[scriptable, uuid(1f9fb93e-91bf-11d3-8cd9-0060b0fc14a3)]
interface nsISyncStreamListener : nsIStreamListener
{
/**
* Initializes an nsISyncStreamListener.
*/
void init(out nsIInputStream inStream,
out nsIBufferOutputStream outStream);
};
%{C++
// Use this CID to construct an nsIAsyncStreamListener
#define NS_ASYNCSTREAMLISTENER_CID \
{ /* 60047bb2-91c0-11d3-8cd9-0060b0fc14a3 */ \
0x60047bb2, \
0x91c0, \
0x11d3, \
{0x8c, 0xd9, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
// Use this CID to construct an nsISyncStreamListener
#define NS_SYNCSTREAMLISTENER_CID \
{ /* 65fa5cb2-91c0-11d3-8cd9-0060b0fc14a3 */ \
0x65fa5cb2, \
0x91c0, \
0x11d3, \
{0x8c, 0xd9, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}

View File

@@ -1,72 +0,0 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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):
*/
#include "nsISupports.idl"
#include "nsIChannel.idl"
interface nsIURI;
interface nsILoadGroup;
interface nsIStreamObserver;
interface nsIStreamLoader;
interface nsIInterfaceRequestor;
[scriptable, uuid(359F7990-D4E9-11d3-A1A5-0050041CAF44)]
interface nsIStreamLoaderObserver : nsISupports
{
void onStreamComplete(in nsIStreamLoader loader,
in nsISupports ctxt,
in nsresult status,
in unsigned long resultLength,
[size_is(resultLength)] in string result);
};
[scriptable, uuid(31d37360-8e5a-11d3-93ad-00104ba0fd40)]
interface nsIStreamLoader : nsISupports
{
void init(in nsIURI uri,
in nsIStreamLoaderObserver completionObserver,
in nsISupports ctxt,
in nsILoadGroup loadGroup,
in nsIInterfaceRequestor notificationCallbacks,
in nsLoadFlags loadAttributes,
in unsigned long bufferSegmentSize,
in unsigned long bufferMaxSize);
/**
* Gets the number of bytes read so far.
*/
readonly attribute unsigned long numBytesRead;
/**
* Gets the owner of this file
*/
readonly attribute nsISupports owner;
};
%{C++
#define NS_STREAMLOADER_CID \
{ /* 5BA6D920-D4E9-11d3-A1A5-0050041CAF44 */ \
0x5ba6d920, 0xd4e9, 0x11d3, { 0xa1, 0xa5, 0x0, 0x50, 0x4, 0x1c, 0xaf, 0x44 } \
}
%}

View File

@@ -1,78 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
interface nsIEventQueue;
interface nsIChannel;
[scriptable, uuid(fd91e2e0-1481-11d3-9333-00104ba0fd40)]
interface nsIStreamObserver : nsISupports
{
void onStartRequest(in nsIChannel channel,
in nsISupports ctxt);
void onStopRequest(in nsIChannel channel,
in nsISupports ctxt,
in nsresult status,
in wstring errorMsg);
};
/**
* An asynchronous stream observer is used to ship data over to another thread specified
* by the thread's event queue. The receiver stream observer is then used to receive
* the notifications on the other thread.
*
* This interface only provides the initialization needed after construction. Otherwise,
* these objects are used simply as nsIStreamObservers.
*/
[scriptable, uuid(a28dc590-91b3-11d3-8cd9-0060b0fc14a3)]
interface nsIAsyncStreamObserver : nsIStreamObserver
{
/**
* Initializes an nsIAsyncStreamObserver.
* @param eventQueue - may be null indicating the calling thread's event queue
*/
void init(in nsIStreamObserver receiver,
in nsIEventQueue eventQueue);
};
%{C++
// Use this CID to construct an nsIAsyncStreamObserver
#define NS_ASYNCSTREAMOBSERVER_CID \
{ /* fcc7c380-91b3-11d3-8cd9-0060b0fc14a3 */ \
0xfcc7c380, \
0x91b3, \
0x11d3, \
{0x8c, 0xd9, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
////////////////////////////////////////////////////////////////////////////////
// Generic status codes for OnStopRequest:
#define NS_BINDING_SUCCEEDED NS_OK
#define NS_BINDING_FAILED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 1)
#define NS_BINDING_ABORTED NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 2)
%}

View File

@@ -1,183 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsISupports.idl"
#include "nsIURLParser.idl"
/**
* URIs are essentially structured names for things -- anything.
* This interface provides accessors to destructure those names.
*
* This interface follows Tim Berners-Lee's URI spec:
*
* http://www.w3.org/Addressing/URI/URI_Overview.html
*
* essentially:
*
* ftp://username:password@hostname:portnumber/pathname
* \ / \ / \ / \ /\ /
* - --------------- ------ -------- -------
* | | | | |
* | | | | Path
* | | | Port
* | | Host
* | PreHost
* Scheme
*
* The subclass nsIURL provides a means to open an input or output
* stream to a URI as a source/destination, as well as providing additional
* accessors to destructure the path, query and reference portions typically
* associated with URLs.
*/
%{C++
#undef GetPort // XXX Windows!
#undef SetPort // XXX Windows!
%}
[scriptable, uuid(07a22cc0-0ce5-11d3-9331-00104ba0fd40)]
interface nsIURI : nsISupports
{
/**
* Returns a string representation of the URI. Setting the spec
* causes the new spec to be parsed, initializing the URI. Setting
* the spec (or any of the accessors) causes also any currently
* open streams on the URI's channel to be closed.
*/
attribute string spec;
/**
* The Scheme is the protocol to which this URI refers. Setting
* the scheme is a special operation that builds up an equivalent
* URI string from the new scheme and all the other URI attributes
* and passes the it to the nsIOService to create a new URI for
* the new scheme.
*/
attribute string scheme;
/**
* The PreHost portion includes elements like the optional
* username:password, or maybe other scheme specific items.
*/
attribute string preHost;
attribute string username;
attribute string password;
/**
* The Host is the internet domain name to which this URI refers.
* Note that it could be an IP address as well.
*/
attribute string host;
/**
* A return value of -1 indicates that no port value is set and the
* implementor of the specific scheme will use its default port.
* Similarly setting a value of -1 indicates that the default is to be used.
* Thus as an example:
* for HTTP, Port 80 is same as a return value of -1.
* However after setting a port (even if its default), the port number will
* appear in the ToNewCString function.
*/
attribute long port;
/**
* Note that the path includes the leading '/' Thus if no path is
* available the Path accessor will return a "/"
* For SetPath if none is provided, one would be prefixed to the path.
*/
attribute string path;
/**
* This is a handle to the Parser used to parse the URI
*/
attribute nsIURLParser URLParser;
/**
* Note that this comparison is only on char* level. Use
* the scheme specific URI to do a more thorough check. For example,
* in HTTP:
* http://foo.com:80 == http://foo.com
* but this function through nsIURI alone will not return equality
* for this case.
*/
boolean equals(in nsIURI other);
/**
* Clones the current URI. The newly created URI will be in a closed
* state even if the underlying channel of the cloned URI is open.
* Cloning allows the current location to be retained since once the
* channel is opened the URI may get redirected to a new location.
*/
nsIURI clone();
/**
* Sets the given string to be a relative path for this URI, and
* changes this to read relative. Thus for example- if this =
* http://foo.com/bar/index.html, then calling SetRelativePath("/baz") will
* change this to http://foo.com/baz and calling it with "baz" will
* change this to http://foo.com/bar/baz.
*/
void setRelativePath(in string relativePath);
/**
* This method resolves a relative string into an absolute URI string,
* using the URI as the base.
*
* This method subsumes the deprecated method nsIIOService::MakeAbsolute.
*/
string resolve(in string relativePath);
};
%{C++
// Malformed URI Error
#define NS_ERROR_MALFORMED_URI NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_NETWORK, 10)
/**
* Protocol writers can obtain a very basic (ok, degenerate) implementation
* of nsIURI by calling the component manager with NS_SIMPLEURI_CID. The
* implementation returned will only parse things of the form:
*
* about:cache
* \ / \ /
* --- ---
* | |
* Scheme Path
*
* where the path is everything after the colon. Note that this is probably
* only useful for cases like about: or javascript: URIs.
*
* *** What you most likely will want is NS_STANDARDURL_CID which is much more
* full featured. Look at nsIURL.idl for more details.
*/
#define NS_SIMPLEURI_CID \
{ /* e0da1d70-2f7b-11d3-8cd0-0060b0fc14a3 */ \
0xe0da1d70, \
0x2f7b, \
0x11d3, \
{0x8c, 0xd0, 0x00, 0x60, 0xb0, 0xfc, 0x14, 0xa3} \
}
%}

View File

@@ -1,149 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsIURI.idl"
interface nsIChannel;
interface nsIEventSinkGetter;
/**
* The nsIURL interface provides convenience methods that further
* break down the path portion of nsIURI:
*
* http://directory/fileBaseName.fileExtension?query
* http://directory/fileBaseName.fileExtension#ref
* http://directory/fileBaseName.fileExtension;param
* \ \ /
* \ -----------------------
* \ | /
* \ fileName /
* ----------------------------
* |
* filePath
*/
[scriptable, uuid(d6116970-8034-11d3-9399-00104ba0fd40)]
interface nsIURL : nsIURI
{
////////////////////////////////////////////////////////////////////////////
// The path attribute is broken down into the following attributes:
// filePath, param, query, and ref:
/**
* Returns a path including the directory and file portions of a
* URL. E.g. The filePath of "http://foo/bar.html#baz" is
* "/foo/bar.html".
*/
attribute string filePath;
/**
* Returns the parameters specified after the ; in the URL.
*
*/
attribute string param;
/**
* Returns the query portion (the part after the "?") of the URL.
* If there isn't one, an empty string is returned.
*/
attribute string query;
/**
* Returns the reference portion (the part after the "#") of the URL.
* If there isn't one, an empty string is returned.
*/
attribute string ref;
////////////////////////////////////////////////////////////////////////////
// The filePath attribute is further broken down into the following
// attributes: directory, file:
/**
* Returns the directory portion of a URL.
* If the URL denotes a path to a directory and not a file,
* e.g. http://foo/bar/, then the Directory attribute accesses
* the complete /foo/bar/ portion, and the FileName is the
* empty string. If the trailing slash is omitted, then the
* Directory is /foo/ and the file is bar (i.e. this is a
* syntactic, not a semantic breakdown of the Path).
* And hence dont rely on this for something to be a definitely
* be a file. But you can get just the leading directory portion
* for sure.
*/
attribute string directory;
/**
* Returns the file name portion of a URL.
* If the URL denotes a path to a directory and not a file,
* e.g. http://foo/bar/, then the Directory attribute accesses
* the complete /foo/bar/ portion, and the FileName is the
* empty string. Note that this is purely based on searching
* for the last trailing slash. And hence dont rely on this to
* be a definite file.
*/
attribute string fileName;
////////////////////////////////////////////////////////////////////////////
// The fileName attribute is further broken down into the following
// attributes: fileName, fileExtension:
attribute string fileBaseName;
/**
* Returns the file extension portion of a filename in a url.
* If a file extension does not exist, the empty string is returned.
*/
attribute string fileExtension;
};
%{C++
/**
* Protocol writers can obtain a default nsIURL implementation by calling the
* component manager with NS_STANDARDURL_CID. The implementation returned will
* only implement the set of accessors specified by nsIURL. After obtaining the
* instance from the component manager, the Init routine must be called on it
* to initialize it from the user's URL spec.
*/
#define NS_STANDARDURL_CID \
{ /* de9472d0-8034-11d3-9399-00104ba0fd40 */ \
0xde9472d0, \
0x8034, \
0x11d3, \
{0x93, 0x99, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40} \
}
%}
////////////////////////////////////////////////////////////////////////////////
interface nsIFile;
/**
* nsIFileURL is used for the file: protocol, and gives access to the
* underlying nsIFile object.
*/
[scriptable, uuid(d26b2e2e-1dd1-11b2-88f3-8545a7ba7949)]
interface nsIFileURL : nsIURL
{
attribute nsIFile file;
};

View File

@@ -1,125 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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 Andreas Otte
*
* Contributor(s):
*/
#include "nsISupports.idl"
/**
* nsIURLParser is the abstract base class for parsing URLs
*/
[scriptable, uuid(4b4975f9-f128-47fd-b11e-88402233cbdf)]
interface nsIURLParser : nsISupports
{
/**
* Parses a URL and thinks it is parsing the scheme
*/
void ParseAtScheme(in string i_Spec,
out string o_Scheme,
out string o_Username,
out string o_Password,
out string o_Host,
out long o_Port,
out string o_Path);
/**
* Parses a URL and thinks it is parsing the prehost
*/
void ParseAtPreHost(in string i_Spec,
out string o_Username,
out string o_Password,
out string o_Host,
out long o_Port,
out string o_Path);
/**
* Parses a URL and thinks it is parsing the host
*/
void ParseAtHost(in string i_Spec,
out string o_Host,
out long o_Port,
out string o_Path);
/**
* Parses a URL and thinks it is parsing the port
*/
void ParseAtPort(in string i_Spec,
out long o_Port,
out string o_Path);
/**
* Parses a URL and thinks it is parsing the path
*/
void ParseAtPath(in string i_Spec,
out string o_Path);
/**
* Parses a URL-path and thinks it is parsing the directory
*/
void ParseAtDirectory(in string i_Path,
out string o_Directory,
out string o_FileBaseName,
out string o_FileExtension,
out string o_Param,
out string o_Query,
out string o_Ref);
/**
* Parses the URL-PreHost into its components
*/
void ParsePreHost(in string i_PreHost,
out string o_Username,
out string o_Password);
/**
* Parses the URL-Filename into its components
*/
void ParseFileName(in string i_FileName,
out string o_FileBaseName,
out string o_FileExtension);
};
%{C++
#define NS_STANDARDURLPARSER_CID \
{ /* dbf72351-4fd8-46f0-9dbc-fa5ba60a30c5 */ \
0xdbf72351, \
0x4fd8, \
0x46f0, \
{0x9d, 0xbc, 0xfa, 0x5b, 0xa6, 0x0a, 0x30, 0x5c} \
}
#define NS_AUTHORITYURLPARSER_CID \
{ /* 90012125-1616-4fa1-ae14-4e7fa5766eb6 */ \
0x90012125, \
0x1616, \
0x4fa1, \
{0xae, 0x14, 0x4e, 0x7f, 0xa5, 0x76, 0x6e, 0xb6} \
}
#define NS_NOAUTHORITYURLPARSER_CID \
{ /* 9eeb1b89-c87e-4404-9de6-dbd41aeaf3d7 */ \
0x9eeb1b89, \
0xc87e, \
0x4404, \
{0x9d, 0xe6, 0xdb, 0xd4, 0x1a, 0xea, 0xf3, 0xd7} \
}
%}

View File

@@ -1,409 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#ifndef nsNetUtil_h__
#define nsNetUtil_h__
#include "nsIURI.h"
#include "netCore.h"
#include "nsIInputStream.h"
#include "nsIStreamListener.h"
#include "nsILoadGroup.h"
#include "nsIInterfaceRequestor.h"
#include "nsString.h"
#include "nsIIOService.h"
#include "nsIServiceManager.h"
#include "nsIChannel.h"
#include "nsIAllocator.h"
#include "nsCOMPtr.h"
#include "nsIHTTPProtocolHandler.h"
#include "nsIStreamLoader.h"
#include "prio.h" // for read/write flags, permissions, etc.
inline nsresult
NS_NewURI(nsIURI* *result,
const char* spec,
nsIURI* baseURI = nsnull,
nsIIOService* ioService = nsnull) // pass in nsIIOService to optimize callers
{
nsresult rv;
nsIIOService* serv = ioService;
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
if (serv == nsnull) {
rv = nsServiceManager::GetService(kIOServiceCID, NS_GET_IID(nsIIOService),
(nsISupports**)&serv);
if (NS_FAILED(rv)) return rv;
}
rv = serv->NewURI(spec, baseURI, result);
if (ioService == nsnull) {
(void)nsServiceManager::ReleaseService(kIOServiceCID, serv);
}
return rv;
}
inline nsresult
NS_NewURI(nsIURI* *result,
const nsString& spec,
nsIURI* baseURI = nsnull,
nsIIOService* ioService = nsnull) // pass in nsIIOService to optimize callers
{
char* specStr = spec.ToNewUTF8String(); // this forces a single byte char*
if (specStr == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = NS_NewURI(result, specStr, baseURI, ioService);
nsAllocator::Free(specStr);
return rv;
}
inline nsresult
NS_OpenURI(nsIChannel* *result,
nsIURI* uri,
nsIIOService* ioService = nsnull, // pass in nsIIOService to optimize callers
nsILoadGroup* loadGroup = nsnull,
nsIInterfaceRequestor* notificationCallbacks = nsnull,
nsLoadFlags loadAttributes = nsIChannel::LOAD_NORMAL,
PRUint32 bufferSegmentSize = 0,
PRUint32 bufferMaxSize = 0)
{
nsresult rv;
nsIIOService* serv = ioService;
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
if (serv == nsnull) {
rv = nsServiceManager::GetService(kIOServiceCID, NS_GET_IID(nsIIOService),
(nsISupports**)&serv);
if (NS_FAILED(rv)) return rv;
}
nsIChannel* channel = nsnull;
rv = serv->NewChannelFromURI(uri, &channel);
if (NS_FAILED(rv)) return rv;
if (loadGroup) {
rv = channel->SetLoadGroup(loadGroup);
if (NS_FAILED(rv)) return rv;
}
if (notificationCallbacks) {
rv = channel->SetNotificationCallbacks(notificationCallbacks);
if (NS_FAILED(rv)) return rv;
}
if (loadAttributes != nsIChannel::LOAD_NORMAL) {
rv = channel->SetLoadAttributes(loadAttributes);
if (NS_FAILED(rv)) return rv;
}
if (bufferSegmentSize != 0) {
rv = channel->SetBufferSegmentSize(bufferSegmentSize);
if (NS_FAILED(rv)) return rv;
}
if (bufferMaxSize != 0) {
rv = channel->SetBufferMaxSize(bufferMaxSize);
if (NS_FAILED(rv)) return rv;
}
if (ioService == nsnull) {
(void)nsServiceManager::ReleaseService(kIOServiceCID, serv);
}
*result = channel;
return rv;
}
// Use this function with CAUTION. And do not use it on
// the UI thread. It creates a stream that blocks when
// you Read() from it and blocking the UI thread is
// illegal. If you don't want to implement a full
// blown asyncrhonous consumer (via nsIStreamListener)
// look at nsIStreamLoader instead.
inline nsresult
NS_OpenURI(nsIInputStream* *result,
nsIURI* uri,
nsIIOService* ioService = nsnull, // pass in nsIIOService to optimize callers
nsILoadGroup* loadGroup = nsnull,
nsIInterfaceRequestor* notificationCallbacks = nsnull,
nsLoadFlags loadAttributes = nsIChannel::LOAD_NORMAL,
PRUint32 bufferSegmentSize = 0,
PRUint32 bufferMaxSize = 0)
{
nsresult rv;
nsCOMPtr<nsIChannel> channel;
rv = NS_OpenURI(getter_AddRefs(channel), uri, ioService,
loadGroup, notificationCallbacks, loadAttributes,
bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) return rv;
nsIInputStream* inStr;
rv = channel->OpenInputStream(&inStr);
if (NS_FAILED(rv)) return rv;
*result = inStr;
return rv;
}
inline nsresult
NS_OpenURI(nsIStreamListener* aConsumer,
nsISupports* context,
nsIURI* uri,
nsIIOService* ioService = nsnull, // pass in nsIIOService to optimize callers
nsILoadGroup* loadGroup = nsnull,
nsIInterfaceRequestor* notificationCallbacks = nsnull,
nsLoadFlags loadAttributes = nsIChannel::LOAD_NORMAL,
PRUint32 bufferSegmentSize = 0,
PRUint32 bufferMaxSize = 0)
{
nsresult rv;
nsCOMPtr<nsIChannel> channel;
rv = NS_OpenURI(getter_AddRefs(channel), uri, ioService,
loadGroup, notificationCallbacks, loadAttributes,
bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) return rv;
rv = channel->AsyncRead(aConsumer, context);
return rv;
}
inline nsresult
NS_MakeAbsoluteURI(char* *result,
const char* spec,
nsIURI* baseURI = nsnull,
nsIIOService* ioService = nsnull) // pass in nsIIOService to optimize callers
{
nsresult rv;
NS_ASSERTION(baseURI, "It doesn't make sense to not supply a base URI");
if (spec == nsnull)
return baseURI->GetSpec(result);
nsIIOService* serv = ioService;
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
if (serv == nsnull) {
rv = nsServiceManager::GetService(kIOServiceCID, NS_GET_IID(nsIIOService),
(nsISupports**)&serv);
if (NS_FAILED(rv)) return rv;
}
PRUint32 startPos, endPos;
rv = serv->ExtractScheme(spec, &startPos, &endPos, nsnull);
if (NS_SUCCEEDED(rv)) {
// if spec has a scheme, then it's already absolute
*result = nsCRT::strdup(spec);
rv = (*result == nsnull) ? NS_ERROR_OUT_OF_MEMORY : NS_OK;
}
else {
rv = baseURI->Resolve(spec, result);
}
if (ioService == nsnull) {
(void)nsServiceManager::ReleaseService(kIOServiceCID, serv);
}
return rv;
}
inline nsresult
NS_MakeAbsoluteURI(nsString& result,
const nsString& spec,
nsIURI* baseURI = nsnull,
nsIIOService* ioService = nsnull) // pass in nsIIOService to optimize callers
{
char* resultStr;
char* specStr = spec.ToNewUTF8String();
if (!specStr) {
return NS_ERROR_OUT_OF_MEMORY;
}
nsresult rv = NS_MakeAbsoluteURI(&resultStr, specStr, baseURI, ioService);
nsAllocator::Free(specStr);
if (NS_FAILED(rv)) return rv;
result.AssignWithConversion(resultStr);
nsAllocator::Free(resultStr);
return rv;
}
inline nsresult
NS_NewPostDataStream(nsIInputStream **result,
PRBool isFile,
const char *data,
PRUint32 encodeFlags,
nsIIOService* ioService = nsnull) // pass in nsIIOService to optimize callers
{
nsresult rv;
nsIIOService* serv = ioService;
static NS_DEFINE_CID(kIOServiceCID, NS_IOSERVICE_CID);
if (serv == nsnull) {
rv = nsServiceManager::GetService(kIOServiceCID, NS_GET_IID(nsIIOService),
(nsISupports**)&serv);
if (NS_FAILED(rv)) return rv;
}
nsCOMPtr<nsIProtocolHandler> handler;
rv = serv->GetProtocolHandler("http", getter_AddRefs(handler));
if (ioService == nsnull) {
(void)nsServiceManager::ReleaseService(kIOServiceCID, serv);
}
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIHTTPProtocolHandler> http = do_QueryInterface(handler, &rv);
if (NS_FAILED(rv)) return rv;
return http->NewPostDataStream(isFile, data, encodeFlags, result);
}
inline nsresult
NS_NewInputStreamChannel(nsIChannel **result,
nsIURI* uri,
nsIInputStream* inStr,
const char* contentType,
PRInt32 contentLength)
{
nsresult rv;
nsCOMPtr<nsIInputStreamChannel> channel;
static NS_DEFINE_CID(kInputStreamChannelCID, NS_INPUTSTREAMCHANNEL_CID);
rv = nsComponentManager::CreateInstance(kInputStreamChannelCID,
nsnull,
NS_GET_IID(nsIInputStreamChannel),
getter_AddRefs(channel));
if (NS_FAILED(rv)) return rv;
rv = channel->Init(uri, inStr, contentType, contentLength);
if (NS_FAILED(rv)) return rv;
*result = channel;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewLoadGroup(nsILoadGroup* *result, nsIStreamObserver* obs)
{
nsresult rv;
nsCOMPtr<nsILoadGroup> group;
static NS_DEFINE_CID(kLoadGroupCID, NS_LOADGROUP_CID);
rv = nsComponentManager::CreateInstance(kLoadGroupCID, nsnull,
NS_GET_IID(nsILoadGroup),
getter_AddRefs(group));
if (NS_FAILED(rv)) return rv;
rv = group->Init(obs);
if (NS_FAILED(rv)) return rv;
*result = group;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewStreamLoader(nsIStreamLoader* *result,
nsIURI* uri,
nsIStreamLoaderObserver* observer,
nsISupports* context = nsnull,
nsILoadGroup* loadGroup = nsnull,
nsIInterfaceRequestor* notificationCallbacks = nsnull,
nsLoadFlags loadAttributes = nsIChannel::LOAD_NORMAL,
PRUint32 bufferSegmentSize = 0,
PRUint32 bufferMaxSize = 0)
{
nsresult rv;
nsCOMPtr<nsIStreamLoader> loader;
static NS_DEFINE_CID(kStreamLoaderCID, NS_STREAMLOADER_CID);
rv = nsComponentManager::CreateInstance(kStreamLoaderCID,
nsnull,
NS_GET_IID(nsIStreamLoader),
getter_AddRefs(loader));
if (NS_FAILED(rv)) return rv;
rv = loader->Init(uri, observer, context, loadGroup, notificationCallbacks, loadAttributes,
bufferSegmentSize, bufferMaxSize);
if (NS_FAILED(rv)) return rv;
*result = loader;
NS_ADDREF(*result);
return rv;
}
inline nsresult
NS_NewAsyncStreamObserver(nsIStreamObserver **result,
nsIStreamObserver *receiver,
nsIEventQueue *eventQueue)
{
nsresult rv;
nsCOMPtr<nsIAsyncStreamObserver> obs;
static NS_DEFINE_CID(kAsyncStreamObserverCID, NS_ASYNCSTREAMOBSERVER_CID);
rv = nsComponentManager::CreateInstance(kAsyncStreamObserverCID,
nsnull,
NS_GET_IID(nsIAsyncStreamObserver),
getter_AddRefs(obs));
if (NS_FAILED(rv)) return rv;
rv = obs->Init(receiver, eventQueue);
if (NS_FAILED(rv)) return rv;
*result = obs;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewAsyncStreamListener(nsIStreamListener **result,
nsIStreamListener *receiver,
nsIEventQueue *eventQueue)
{
nsresult rv;
nsCOMPtr<nsIAsyncStreamListener> lsnr;
static NS_DEFINE_CID(kAsyncStreamListenerCID, NS_ASYNCSTREAMLISTENER_CID);
rv = nsComponentManager::CreateInstance(kAsyncStreamListenerCID,
nsnull,
NS_GET_IID(nsIAsyncStreamListener),
getter_AddRefs(lsnr));
if (NS_FAILED(rv)) return rv;
rv = lsnr->Init(receiver, eventQueue);
if (NS_FAILED(rv)) return rv;
*result = lsnr;
NS_ADDREF(*result);
return NS_OK;
}
inline nsresult
NS_NewSyncStreamListener(nsIInputStream **inStream,
nsIBufferOutputStream **outStream,
nsIStreamListener **listener)
{
nsresult rv;
nsCOMPtr<nsISyncStreamListener> lsnr;
static NS_DEFINE_CID(kSyncStreamListenerCID, NS_SYNCSTREAMLISTENER_CID);
rv = nsComponentManager::CreateInstance(kSyncStreamListenerCID,
nsnull,
NS_GET_IID(nsISyncStreamListener),
getter_AddRefs(lsnr));
if (NS_FAILED(rv)) return rv;
rv = lsnr->Init(inStream, outStream);
if (NS_FAILED(rv)) return rv;
*listener = lsnr;
NS_ADDREF(*listener);
return NS_OK;
}
#endif // nsNetUtil_h__

View File

@@ -1,100 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* 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):
*/
#ifndef _nsUnixColorPrintf_h_
#define _nsUnixColorPrintf_h_
#if defined(XP_UNIX) && defined(NS_DEBUG)
#define STARTGRAY "\033[1;30m"
#define STARTRED "\033[1;31m"
#define STARTGREEN "\033[1;32m"
#define STARTYELLOW "\033[1;33m"
#define STARTBLUE "\033[1;34m"
#define STARTMAGENTA "\033[1;35m"
#define STARTCYAN "\033[1;36m"
#define STARTUNDERLINE "\033[4m"
#define STARTREVERSE "\033[7m"
#define ENDCOLOR "\033[0m"
#define PRINTF_GRAY nsUnixColorPrintf __color_printf(STARTGREY)
#define PRINTF_RED nsUnixColorPrintf __color_printf(STARTRED)
#define PRINTF_GREEN nsUnixColorPrintf __color_printf(STARTGREEN)
#define PRINTF_YELLOW nsUnixColorPrintf __color_printf(STARTYELLOW)
#define PRINTF_BLUE nsUnixColorPrintf __color_printf(STARTBLUE)
#define PRINTF_MAGENTA nsUnixColorPrintf __color_printf(STARTMAGENTA)
#define PRINTF_CYAN nsUnixColorPrintf __color_printf(STARTCYAN)
#define PRINTF_UNDERLINE nsUnixColorPrintf __color_printf(STARTUNDERLINE)
#define PRINTF_REVERSE nsUnixColorPrintf __color_printf(STARTREVERSE)
/*
The nsUnixColorPrintf is a handy set of color term codes to change
the color of console texts for easier spotting. As of now this is
Unix and Debug only.
Usage is simple.
See examples in
mozilla/netwerk/protocol/http/src/nsHTTPHandler.cpp
-Gagan Saksena 11/01/99
*/
class nsUnixColorPrintf
{
public:
nsUnixColorPrintf(const char* colorCode)
{
printf("%s",colorCode);
}
~nsUnixColorPrintf()
{
printf("%s",ENDCOLOR);
}
};
#else // XP_UNIX
#define STARTGRAY ""
#define STARTRED ""
#define STARTGREEN ""
#define STARTYELLOW ""
#define STARTBLUE ""
#define STARTMAGENTA ""
#define STARTCYAN ""
#define STARTUNDERLINE ""
#define STARTREVERSE ""
#define ENDCOLOR ""
#define PRINTF_GRAY
#define PRINTF_RED
#define PRINTF_GREEN
#define PRINTF_YELLOW
#define PRINTF_BLUE
#define PRINTF_MAGENTA
#define PRINTF_CYAN
#define PRINTF_UNDERLINE
#define PRINTF_REVERSE
#endif // XP_UNIX
#endif // nsUnixColorPrintf

View File

@@ -1,63 +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 = necko
LIBRARY_NAME = neckobase_s
CPPSRCS = \
nsURLHelper.cpp \
nsFileStreams.cpp \
nsBufferedStreams.cpp \
nsAsyncStreamListener.cpp \
nsSyncStreamListener.cpp \
nsIOService.cpp \
nsSocketTransport.cpp \
nsSocketTransportService.cpp \
nsFileTransport.cpp \
nsFileTransportService.cpp \
nsStdURLParser.cpp \
nsAuthURLParser.cpp \
nsNoAuthURLParser.cpp \
nsStdURL.cpp \
nsSimpleURI.cpp \
nsNetModuleMgr.cpp \
nsNetModRegEntry.cpp \
nsLoadGroup.cpp \
nsInputStreamChannel.cpp \
nsDirectoryIndexStream.cpp \
nsStreamLoader.cpp \
nsProtocolProxyService.cpp \
$(NULL)
# we don't want the shared lib, but we want to force the creation of a
# static lib.
override NO_SHARED_LIB=1
override NO_STATIC_LIB=
include $(topsrcdir)/config/rules.mk

View File

@@ -1,64 +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):
MODULE = necko
DEPTH = ..\..\..
include <$(DEPTH)/config/config.mak>
LCFLAGS = -DWIN32_LEAN_AND_MEAN -D_IMPL_NS_NET
LIBRARY_NAME=neckobase_s
CPP_OBJS = \
.\$(OBJDIR)\nsURLHelper.obj \
.\$(OBJDIR)\nsFileStreams.obj \
.\$(OBJDIR)\nsBufferedStreams.obj \
.\$(OBJDIR)\nsAsyncStreamListener.obj \
.\$(OBJDIR)\nsSyncStreamListener.obj \
.\$(OBJDIR)\nsIOService.obj \
.\$(OBJDIR)\nsSocketTransport.obj \
.\$(OBJDIR)\nsSocketTransportService.obj \
.\$(OBJDIR)\nsFileTransport.obj \
.\$(OBJDIR)\nsFileTransportService.obj \
.\$(OBJDIR)\nsStdURLParser.obj \
.\$(OBJDIR)\nsAuthURLParser.obj \
.\$(OBJDIR)\nsNoAuthURLParser.obj \
.\$(OBJDIR)\nsStdURL.obj \
.\$(OBJDIR)\nsSimpleURI.obj \
.\$(OBJDIR)\nsNetModuleMgr.obj \
.\$(OBJDIR)\nsNetModRegEntry.obj \
.\$(OBJDIR)\nsLoadGroup.obj \
.\$(OBJDIR)\nsInputStreamChannel.obj \
.\$(OBJDIR)\nsDirectoryIndexStream.obj \
.\$(OBJDIR)\nsStreamLoader.obj \
.\$(OBJDIR)\nsProtocolProxyService.obj \
$(NULL)
INCS = $(INCS) \
-I$(DEPTH)\dist\include \
$(NULL)
include <$(DEPTH)\config\rules.mak>
install:: $(LIBRARY)
$(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
clobber::
rm -f $(DIST)\lib\$(LIBRARY_NAME).lib

View File

@@ -1,476 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsAsyncStreamListener.h"
#include "nsIBufferInputStream.h"
#include "nsString.h"
#include "nsCRT.h"
#include "nsIEventQueueService.h"
#include "nsIIOService.h"
#include "nsIServiceManager.h"
#include "nsIChannel.h"
#include "prlog.h"
static NS_DEFINE_CID(kEventQueueService, NS_EVENTQUEUESERVICE_CID);
#if defined(PR_LOGGING)
PRLogModuleInfo* gStreamEventLog = 0;
#endif
////////////////////////////////////////////////////////////////////////////////
class nsStreamListenerEvent
{
public:
nsStreamListenerEvent(nsAsyncStreamObserver* listener,
nsIChannel* channel, nsISupports* context);
virtual ~nsStreamListenerEvent();
nsresult Fire(nsIEventQueue* aEventQ);
NS_IMETHOD HandleEvent() = 0;
protected:
static void PR_CALLBACK HandlePLEvent(PLEvent* aEvent);
static void PR_CALLBACK DestroyPLEvent(PLEvent* aEvent);
nsAsyncStreamObserver* mListener;
nsIChannel* mChannel;
nsISupports* mContext;
PLEvent * mEvent;
};
////////////////////////////////////////////////////////////////////////////////
nsStreamListenerEvent::nsStreamListenerEvent(nsAsyncStreamObserver* listener,
nsIChannel* channel, nsISupports* context)
: mListener(listener), mChannel(channel), mContext(context), mEvent(nsnull)
{
MOZ_COUNT_CTOR(nsStreamListenerEvent);
NS_IF_ADDREF(mListener);
NS_IF_ADDREF(mChannel);
NS_IF_ADDREF(mContext);
}
nsStreamListenerEvent::~nsStreamListenerEvent()
{
MOZ_COUNT_DTOR(nsStreamListenerEvent);
NS_IF_RELEASE(mListener);
NS_IF_RELEASE(mChannel);
NS_IF_RELEASE(mContext);
if (nsnull != mEvent)
{
delete mEvent;
mEvent = nsnull;
}
}
void PR_CALLBACK nsStreamListenerEvent::HandlePLEvent(PLEvent* aEvent)
{
nsStreamListenerEvent * ev =
(nsStreamListenerEvent *) PL_GetEventOwner(aEvent);
NS_ASSERTION(nsnull != ev,"null event.");
nsresult rv = ev->HandleEvent();
//
// If the consumer fails, then cancel the transport. This is necessary
// in case where the socket transport is blocked waiting for room in the
// pipe, but the consumer fails without consuming all the data.
//
// Unless the transport is cancelled, it will block forever, waiting for
// the pipe to empty...
//
if (NS_FAILED(rv)) {
nsresult cancelRv = ev->mChannel->Cancel(rv);
NS_ASSERTION(NS_SUCCEEDED(cancelRv), "Cancel failed");
}
}
void PR_CALLBACK nsStreamListenerEvent::DestroyPLEvent(PLEvent* aEvent)
{
nsStreamListenerEvent * ev =
(nsStreamListenerEvent *) PL_GetEventOwner(aEvent);
NS_ASSERTION(nsnull != ev,"null event.");
delete ev;
}
nsresult
nsStreamListenerEvent::Fire(nsIEventQueue* aEventQueue)
{
NS_PRECONDITION(nsnull != aEventQueue, "nsIEventQueue for thread is null");
NS_PRECONDITION(nsnull == mEvent, "Init plevent only once.");
mEvent = new PLEvent;
PL_InitEvent(mEvent,
this,
(PLHandleEventProc) nsStreamListenerEvent::HandlePLEvent,
(PLDestroyEventProc) nsStreamListenerEvent::DestroyPLEvent);
PRStatus status = aEventQueue->PostEvent(mEvent);
return status == PR_SUCCESS ? NS_OK : NS_ERROR_FAILURE;
}
////////////////////////////////////////////////////////////////////////////////
NS_IMPL_THREADSAFE_ISUPPORTS2(nsAsyncStreamObserver,
nsIAsyncStreamObserver,
nsIStreamObserver)
NS_IMPL_ADDREF_INHERITED(nsAsyncStreamListener, nsAsyncStreamObserver);
NS_IMPL_RELEASE_INHERITED(nsAsyncStreamListener, nsAsyncStreamObserver);
NS_IMETHODIMP
nsAsyncStreamListener::QueryInterface(REFNSIID aIID, void** aInstancePtr)
{
if (!aInstancePtr) return NS_ERROR_NULL_POINTER;
if (aIID.Equals(NS_GET_IID(nsIAsyncStreamListener))) {
*aInstancePtr = NS_STATIC_CAST(nsIAsyncStreamListener*, this);
NS_ADDREF_THIS();
return NS_OK;
}
if (aIID.Equals(NS_GET_IID(nsIStreamListener))) {
*aInstancePtr = NS_STATIC_CAST(nsIStreamListener*, this);
NS_ADDREF_THIS();
return NS_OK;
}
return nsAsyncStreamObserver::QueryInterface(aIID, aInstancePtr);
}
NS_IMETHODIMP
nsAsyncStreamObserver::Init(nsIStreamObserver* aObserver, nsIEventQueue* aEventQ)
{
nsresult rv = NS_OK;
mReceiver = aObserver;
NS_WITH_SERVICE(nsIEventQueueService, eventQService, kEventQueueService, &rv);
if (NS_FAILED(rv))
return rv;
rv = eventQService->ResolveEventQueue(aEventQ, getter_AddRefs(mEventQueue));
return rv;
}
////////////////////////////////////////////////////////////////////////////////
//
// OnStartRequest...
//
////////////////////////////////////////////////////////////////////////////////
class nsOnStartRequestEvent : public nsStreamListenerEvent
{
public:
nsOnStartRequestEvent(nsAsyncStreamObserver* listener,
nsIChannel* channel, nsISupports* context)
: nsStreamListenerEvent(listener, channel, context) {}
virtual ~nsOnStartRequestEvent() {}
NS_IMETHOD HandleEvent();
};
NS_IMETHODIMP
nsOnStartRequestEvent::HandleEvent()
{
#if defined(PR_LOGGING)
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("netlibEvent: Handle Start [event=%x]", this));
#endif
nsIStreamObserver* receiver = (nsIStreamObserver*)mListener->GetReceiver();
nsresult status;
nsresult rv = mChannel->GetStatus(&status);
NS_ASSERTION(NS_SUCCEEDED(rv), "GetStatus failed");
if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(status)) {
rv = receiver->OnStartRequest(mChannel, mContext);
}
else {
NS_WARNING("not calling OnStartRequest");
}
return rv;
}
NS_IMETHODIMP
nsAsyncStreamObserver::OnStartRequest(nsIChannel* channel, nsISupports* context)
{
nsresult rv;
nsOnStartRequestEvent* event =
new nsOnStartRequestEvent(this, channel, context);
if (event == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
#if defined(PR_LOGGING)
PLEventQueue *equeue;
mEventQueue->GetPLEventQueue(&equeue);
char ts[80];
sprintf(ts, "nsAsyncStreamObserver: Start [this=%lx queue=%lx",
(long)this, (long)equeue);
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("nsAsyncStreamObserver: Start [this=%x queue=%x event=%x]",
this, equeue, event));
#endif
rv = event->Fire(mEventQueue);
if (NS_FAILED(rv)) goto failed;
return rv;
failed:
delete event;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
//
// OnStopRequest
//
////////////////////////////////////////////////////////////////////////////////
class nsOnStopRequestEvent : public nsStreamListenerEvent
{
public:
nsOnStopRequestEvent(nsAsyncStreamObserver* listener,
nsISupports* context, nsIChannel* channel)
: nsStreamListenerEvent(listener, channel, context),
mStatus(NS_OK), mMessage(nsnull) {}
virtual ~nsOnStopRequestEvent();
nsresult Init(nsresult status, const PRUnichar* aMsg);
NS_IMETHOD HandleEvent();
protected:
nsresult mStatus;
PRUnichar* mMessage;
};
nsOnStopRequestEvent::~nsOnStopRequestEvent()
{
}
nsresult
nsOnStopRequestEvent::Init(nsresult status, const PRUnichar* aMsg)
{
mStatus = status;
mMessage = (PRUnichar*)aMsg;
return NS_OK;
}
NS_IMETHODIMP
nsOnStopRequestEvent::HandleEvent()
{
#if defined(PR_LOGGING)
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("netlibEvent: Handle Stop [event=%x]", this));
#endif
nsIStreamObserver* receiver = (nsIStreamObserver*)mListener->GetReceiver();
nsresult status = NS_OK;
nsresult rv = mChannel->GetStatus(&status);
NS_ASSERTION(NS_SUCCEEDED(rv), "GetStatus failed");
//
// If the consumer returned a failure code, then pass it out in the
// OnStopRequest(...) notification...
//
if (NS_SUCCEEDED(rv) && NS_FAILED(status)) {
mStatus = status;
}
return receiver->OnStopRequest(mChannel, mContext, mStatus, mMessage);
}
NS_IMETHODIMP
nsAsyncStreamObserver::OnStopRequest(nsIChannel* channel, nsISupports* context,
nsresult aStatus,
const PRUnichar* aMsg)
{
nsresult rv;
//
// Fire the OnStopRequest(...) regardless of what the current
// Status is...
//
nsOnStopRequestEvent* event =
new nsOnStopRequestEvent(this, context, channel);
if (event == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = event->Init(aStatus, aMsg);
if (NS_FAILED(rv)) goto failed;
#if defined(PR_LOGGING)
PLEventQueue *equeue;
mEventQueue->GetPLEventQueue(&equeue);
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("nsAsyncStreamObserver: Stop [this=%x queue=%x event=%x]",
this, equeue, event));
#endif
rv = event->Fire(mEventQueue);
if (NS_FAILED(rv)) goto failed;
return rv;
failed:
delete event;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
//
// OnDataAvailable
//
////////////////////////////////////////////////////////////////////////////////
class nsOnDataAvailableEvent : public nsStreamListenerEvent
{
public:
nsOnDataAvailableEvent(nsAsyncStreamObserver* listener,
nsIChannel* channel, nsISupports* context)
: nsStreamListenerEvent(listener, channel, context),
mIStream(nsnull), mLength(0) {}
virtual ~nsOnDataAvailableEvent();
nsresult Init(nsIInputStream* aIStream, PRUint32 aSourceOffset,
PRUint32 aLength);
NS_IMETHOD HandleEvent();
protected:
nsIInputStream* mIStream;
PRUint32 mSourceOffset;
PRUint32 mLength;
};
nsOnDataAvailableEvent::~nsOnDataAvailableEvent()
{
NS_RELEASE(mIStream);
}
nsresult
nsOnDataAvailableEvent::Init(nsIInputStream* aIStream, PRUint32 aSourceOffset,
PRUint32 aLength)
{
mSourceOffset = aSourceOffset;
mLength = aLength;
mIStream = aIStream;
NS_ADDREF(mIStream);
return NS_OK;
}
NS_IMETHODIMP
nsOnDataAvailableEvent::HandleEvent()
{
#if defined(PR_LOGGING)
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("netlibEvent: Handle Data [event=%x]", this));
#endif
nsIStreamListener* receiver = (nsIStreamListener*)mListener->GetReceiver();
nsresult status;
nsresult rv = mChannel->GetStatus(&status);
NS_ASSERTION(NS_SUCCEEDED(rv), "GetStatus failed");
//
// Only send OnDataAvailable(... ) notifications if all previous calls
// have succeeded...
//
if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(status)) {
rv = receiver->OnDataAvailable(mChannel, mContext,
mIStream, mSourceOffset, mLength);
}
else {
NS_WARNING("not calling OnDataAvailable");
}
return rv;
}
NS_IMETHODIMP
nsAsyncStreamListener::OnDataAvailable(nsIChannel* channel, nsISupports* context,
nsIInputStream *aIStream,
PRUint32 aSourceOffset,
PRUint32 aLength)
{
nsresult rv;
nsOnDataAvailableEvent* event =
new nsOnDataAvailableEvent(this, channel, context);
if (event == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
rv = event->Init(aIStream, aSourceOffset, aLength);
if (NS_FAILED(rv)) goto failed;
#if defined(PR_LOGGING)
PLEventQueue *equeue;
mEventQueue->GetPLEventQueue(&equeue);
if (!gStreamEventLog)
gStreamEventLog = PR_NewLogModule("netlibStreamEvent");
PR_LOG(gStreamEventLog, PR_LOG_DEBUG,
("nsAsyncStreamObserver: Data [this=%x queue=%x event=%x]",
this, equeue, event));
#endif
rv = event->Fire(mEventQueue);
if (NS_FAILED(rv)) goto failed;
return rv;
failed:
delete event;
return rv;
}
////////////////////////////////////////////////////////////////////////////////
NS_METHOD
nsAsyncStreamObserver::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAsyncStreamObserver* l = new nsAsyncStreamObserver();
if (l == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(l);
nsresult rv = l->QueryInterface(aIID, aResult);
NS_RELEASE(l);
return rv;
}
NS_METHOD
nsAsyncStreamListener::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAsyncStreamListener* l = new nsAsyncStreamListener();
if (l == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(l);
nsresult rv = l->QueryInterface(aIID, aResult);
NS_RELEASE(l);
return rv;
}
////////////////////////////////////////////////////////////////////////////////

View File

@@ -1,108 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#ifndef nsAsyncStreamListener_h__
#define nsAsyncStreamListener_h__
#include "nsIStreamListener.h"
#include "nsCOMPtr.h"
#include "nsIEventQueue.h"
#include "nsIStreamObserver.h"
#include "nsIStreamListener.h"
////////////////////////////////////////////////////////////////////////////////
class nsAsyncStreamObserver : public nsIAsyncStreamObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISTREAMOBSERVER
NS_DECL_NSIASYNCSTREAMOBSERVER
// nsAsyncStreamObserver methods:
nsAsyncStreamObserver()
{
NS_INIT_REFCNT();
}
virtual ~nsAsyncStreamObserver() {}
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
nsISupports* GetReceiver() { return mReceiver.get(); }
protected:
nsCOMPtr<nsIEventQueue> mEventQueue;
nsCOMPtr<nsIStreamObserver> mReceiver;
};
////////////////////////////////////////////////////////////////////////////////
class nsAsyncStreamListener : public nsAsyncStreamObserver,
public nsIAsyncStreamListener
{
public:
NS_DECL_ISUPPORTS_INHERITED
// nsIStreamListener methods:
NS_IMETHOD OnStartRequest(nsIChannel* channel,
nsISupports* context)
{
return nsAsyncStreamObserver::OnStartRequest(channel, context);
}
NS_IMETHOD OnStopRequest(nsIChannel* channel,
nsISupports* context,
nsresult aStatus,
const PRUnichar* aMsg)
{
return nsAsyncStreamObserver::OnStopRequest(channel, context, aStatus, aMsg);
}
NS_IMETHOD OnDataAvailable(nsIChannel* channel, nsISupports* context,
nsIInputStream *aIStream,
PRUint32 aSourceOffset,
PRUint32 aLength);
// nsIAsyncStreamListener methods:
NS_IMETHOD Init(nsIStreamListener* aListener, nsIEventQueue* aEventQ) {
return nsAsyncStreamObserver::Init(aListener, aEventQ);
}
// nsAsyncStreamListener methods:
nsAsyncStreamListener() {
MOZ_COUNT_CTOR(nsAsyncStreamListener);
}
virtual ~nsAsyncStreamListener() {
MOZ_COUNT_DTOR(nsAsyncStreamListener);
}
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
};
////////////////////////////////////////////////////////////////////////////////
#endif // nsAsyncStreamListener_h__

View File

@@ -1,522 +0,0 @@
/* -*- 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.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 Andreas Otte.
*
* Contributor(s):
*/
#include "nsAuthURLParser.h"
#include "nsURLHelper.h"
#include "nsCRT.h"
#include "nsString.h"
#include "prprf.h"
NS_IMPL_THREADSAFE_ISUPPORTS(nsAuthURLParser, NS_GET_IID(nsIURLParser))
nsAuthURLParser::~nsAuthURLParser()
{
}
NS_METHOD
nsAuthURLParser::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAuthURLParser* p = new nsAuthURLParser();
if (p == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(p);
nsresult rv = p->QueryInterface(aIID, aResult);
NS_RELEASE(p);
return rv;
}
nsresult
nsAuthURLParser::ParseAtScheme(const char* i_Spec, char* *o_Scheme,
char* *o_Username, char* *o_Password,
char* *o_Host, PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
NS_PRECONDITION( (nsnull != i_Spec), "Parse called on empty url!");
if (!i_Spec)
return NS_ERROR_MALFORMED_URI;
int len = PL_strlen(i_Spec);
if (len >= 2 && *i_Spec == '/' && *(i_Spec+1) == '/') // No Scheme
{
rv = ParseAtPreHost(i_Spec, o_Username, o_Password, o_Host, o_Port,
o_Path);
return rv;
}
static const char delimiters[] = "/:@?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a host
{
rv = ExtractString((char*)i_Spec, o_Host, len);
ToLowerCase(*o_Host);
return rv;
} else
len = PL_strlen(brk);
switch (*brk)
{
case '/' :
case '?' :
// If the URL starts with a slash then everything is a path
if (brk == i_Spec)
{
rv = ParseAtPath(brk, o_Path);
return rv;
}
else // The first part is host, so its host/path
{
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPath(brk, o_Path);
return rv;
}
break;
case ':' :
if (len >= 2 && *(brk+1) == '/') {
// Standard http://... or malformed http:/...
rv = ExtractString((char*)i_Spec, o_Scheme, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Scheme);
rv = ParseAtPreHost(brk+1, o_Username, o_Password, o_Host,
o_Port, o_Path);
return rv;
} else {
// Could be host:port, so try conversion to number
PRInt32 port = ExtractPortFrom(brk+1);
if (port > 0)
{
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Host);
rv = ParseAtPort(brk+1, o_Port, o_Path);
return rv;
} else {
// No, it's not a number try scheme:host...
rv = ExtractString((char*)i_Spec, o_Scheme,
(brk - i_Spec));
if (NS_FAILED(rv))
return rv;
ToLowerCase(*o_Scheme);
rv = ParseAtPreHost(brk+1, o_Username, o_Password, o_Host,
o_Port, o_Path);
return rv;
}
}
break;
case '@' :
rv = ParseAtPreHost(i_Spec, o_Username, o_Password, o_Host,
o_Port, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsAuthURLParser::ParseAtPreHost(const char* i_Spec, char* *o_Username,
char* *o_Password, char* *o_Host,
PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
// Skip leading two slashes
char* fwdPtr= (char*) i_Spec;
if (fwdPtr && (*fwdPtr != '\0') && (*fwdPtr == '/'))
fwdPtr++;
if (fwdPtr && (*fwdPtr != '\0') && (*fwdPtr == '/'))
fwdPtr++;
static const char delimiters[] = "/:@?";
char* brk = PL_strpbrk(fwdPtr, delimiters);
char* brk2 = nsnull;
if (!brk)
{
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
char* e_PreHost = nsnull;
switch (*brk)
{
case ':' :
// this maybe the : of host:port or username:password
// look if the next special char is @
brk2 = PL_strpbrk(brk+1, delimiters);
if (!brk2)
{
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
switch (*brk2)
{
case '@' :
rv = ExtractString(fwdPtr, &e_PreHost, (brk2 - fwdPtr));
if (NS_FAILED(rv)) {
CRTFREEIF(e_PreHost);
return rv;
}
rv = ParsePreHost(e_PreHost,o_Username,o_Password);
CRTFREEIF(e_PreHost);
if (NS_FAILED(rv))
return rv;
rv = ParseAtHost(brk2+1, o_Host, o_Port, o_Path);
break;
default:
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
return rv;
}
break;
case '@' :
rv = ExtractString(fwdPtr, &e_PreHost, (brk - fwdPtr));
if (NS_FAILED(rv)) {
CRTFREEIF(e_PreHost);
return rv;
}
rv = ParsePreHost(e_PreHost,o_Username,o_Password);
CRTFREEIF(e_PreHost);
if (NS_FAILED(rv))
return rv;
rv = ParseAtHost(brk+1, o_Host, o_Port, o_Path);
break;
default:
rv = ParseAtHost(fwdPtr, o_Host, o_Port, o_Path);
}
return rv;
}
nsresult
nsAuthURLParser::ParseAtHost(const char* i_Spec, char* *o_Host,
PRInt32 *o_Port, char* *o_Path)
{
nsresult rv = NS_OK;
int len = PL_strlen(i_Spec);
static const char delimiters[] = ":/?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a host
{
rv = ExtractString((char*)i_Spec, o_Host, len);
if (PL_strlen(*o_Host)==0) {
return NS_ERROR_MALFORMED_URI;
}
ToLowerCase(*o_Host);
return rv;
}
switch (*brk)
{
case '/' :
case '?' :
// Get the Host, the rest is Path
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
if (PL_strlen(*o_Host)==0) {
return NS_ERROR_MALFORMED_URI;
}
ToLowerCase(*o_Host);
rv = ParseAtPath(brk, o_Path);
return rv;
break;
case ':' :
// Get the Host
rv = ExtractString((char*)i_Spec, o_Host, (brk - i_Spec));
if (NS_FAILED(rv))
return rv;
if (PL_strlen(*o_Host)==0) {
return NS_ERROR_MALFORMED_URI;
}
ToLowerCase(*o_Host);
rv = ParseAtPort(brk+1, o_Port, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsAuthURLParser::ParseAtPort(const char* i_Spec, PRInt32 *o_Port,
char* *o_Path)
{
nsresult rv = NS_OK;
static const char delimiters[] = "/?"; //this order is optimized.
char* brk = PL_strpbrk(i_Spec, delimiters);
if (!brk) // everything is a Port
{
if (PL_strlen(i_Spec)==0) {
*o_Port = -1;
return NS_OK;
} else {
*o_Port = ExtractPortFrom(i_Spec);
if (*o_Port <= 0)
return NS_ERROR_MALFORMED_URI;
else
return NS_OK;
}
}
char* e_Port = nsnull;
switch (*brk)
{
case '/' :
case '?' :
// Get the Port, the rest is Path
rv = ExtractString((char*)i_Spec, &e_Port, brk-i_Spec);
if (NS_FAILED(rv)) {
CRTFREEIF(e_Port);
return rv;
}
if (PL_strlen(e_Port)==0) {
*o_Port = -1;
} else {
*o_Port = ExtractPortFrom(e_Port);
if (*o_Port <= 0)
return NS_ERROR_MALFORMED_URI;
}
CRTFREEIF(e_Port);
rv = ParseAtPath(brk, o_Path);
return rv;
break;
default:
NS_ASSERTION(0, "This just can't be!");
break;
}
return NS_OK;
}
nsresult
nsAuthURLParser::ParseAtPath(const char* i_Spec, char* *o_Path)
{
// Just write the path and check for a starting /
nsCAutoString dir;
if ('/' != *i_Spec)
dir += "/";
dir += i_Spec;
*o_Path = dir.ToNewCString();
return (*o_Path ? NS_OK : NS_ERROR_OUT_OF_MEMORY);
}
nsresult
nsAuthURLParser::ParseAtDirectory(const char* i_Path, char* *o_Directory,
char* *o_FileBaseName, char* *o_FileExtension,
char* *o_Param, char* *o_Query, char* *o_Ref)
{
// Cleanout
CRTFREEIF(*o_Directory);
CRTFREEIF(*o_FileBaseName);
CRTFREEIF(*o_FileExtension);
CRTFREEIF(*o_Param);
CRTFREEIF(*o_Query);
CRTFREEIF(*o_Ref);
nsresult rv = NS_OK;
// Parse the Path into its components
if (!i_Path)
{
DupString(o_Directory, "/");
return (o_Directory ? NS_OK : NS_ERROR_OUT_OF_MEMORY);
}
char* dirfile = nsnull;
char* options = nsnull;
int len = PL_strlen(i_Path);
/* Factor out the optionpart with ;?# */
static const char delimiters[] = ";?#"; // for param, query and ref
char* brk = PL_strpbrk(i_Path, delimiters);
if (!brk) // Everything is just path and filename
{
DupString(&dirfile, i_Path);
}
else
{
int dirfileLen = brk - i_Path;
ExtractString((char*)i_Path, &dirfile, dirfileLen);
len -= dirfileLen;
ExtractString((char*)i_Path + dirfileLen, &options, len);
brk = options;
}
/* now that we have broken up the path treat every part differently */
/* first dir+file */
char* file;
int dlen = PL_strlen(dirfile);
if (dlen == 0)
{
DupString(o_Directory, "/");
file = dirfile;
} else {
CoaleseDirs(dirfile);
// Get length again
dlen = PL_strlen(dirfile);
// First find the last slash
file = PL_strrchr(dirfile, '/');
if (!file)
{
DupString(o_Directory, "/");
file = dirfile;
}
// If its not the same as the first slash then extract directory
if (file != dirfile)
{
ExtractString(dirfile, o_Directory, (file - dirfile)+1);
} else {
DupString(o_Directory, "/");
}
}
/* Extract FileBaseName and FileExtension */
if (dlen > 0) {
// Look again if there was a slash
char* slash = PL_strrchr(dirfile, '/');
char* e_FileName = nsnull;
if (slash) {
if (dirfile+dlen-1>slash)
ExtractString(slash+1, &e_FileName, dlen-(slash-dirfile+1));
} else {
// Use the full String as Filename
ExtractString(dirfile, &e_FileName, dlen);
}
rv = ParseFileName(e_FileName,o_FileBaseName,o_FileExtension);
CRTFREEIF(e_FileName);
}
// Now take a look at the options. "#" has precedence over "?"
// which has precedence over ";"
if (options) {
// Look for "#" first. Everything following it is in the ref
brk = PL_strchr(options, '#');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Ref, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
// Now look for "?"
brk = PL_strchr(options, '?');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Query, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
// Now look for ';'
brk = PL_strchr(options, ';');
if (brk) {
int pieceLen = len - (brk + 1 - options);
ExtractString(brk+1, o_Param, pieceLen);
len -= pieceLen + 1;
*brk = '\0';
}
}
nsCRT::free(dirfile);
nsCRT::free(options);
return rv;
}
nsresult
nsAuthURLParser::ParsePreHost(const char* i_PreHost, char* *o_Username,
char* *o_Password)
{
nsresult rv = NS_OK;
if (!i_PreHost) {
*o_Username = nsnull;
*o_Password = nsnull;
return rv;
}
// Search for :
static const char delimiters[] = ":";
char* brk = PL_strpbrk(i_PreHost, delimiters);
if (brk)
{
rv = ExtractString((char*)i_PreHost, o_Username, (brk - i_PreHost));
if (NS_FAILED(rv))
return rv;
rv = ExtractString(brk+1, o_Password,
(i_PreHost+PL_strlen(i_PreHost) - brk - 1));
} else {
CRTFREEIF(*o_Password);
rv = DupString(o_Username, i_PreHost);
}
return rv;
}
nsresult
nsAuthURLParser::ParseFileName(const char* i_FileName, char* *o_FileBaseName,
char* *o_FileExtension)
{
nsresult rv = NS_OK;
if (!i_FileName) {
*o_FileBaseName = nsnull;
*o_FileExtension = nsnull;
return rv;
}
// Search for FileExtension
// Search for last .
// Ignore . at the beginning
char* brk = PL_strrchr(i_FileName+1, '.');
if (brk)
{
rv = ExtractString((char*)i_FileName, o_FileBaseName,
(brk - i_FileName));
if (NS_FAILED(rv))
return rv;
rv = ExtractString(brk + 1, o_FileExtension,
(i_FileName+PL_strlen(i_FileName) - brk - 1));
} else {
rv = DupString(o_FileBaseName, i_FileName);
}
return rv;
}

View File

@@ -1,51 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#ifndef nsAuthURLParser_h__
#define nsAuthURLParser_h__
#include "nsIURLParser.h"
#include "nsIURI.h"
#include "nsAgg.h"
#include "nsCRT.h"
class nsAuthURLParser : public nsIURLParser
{
public:
NS_DECL_ISUPPORTS
///////////////////////////////////////////////////////////////////////////
// nsAuthURLParser methods:
nsAuthURLParser() {
NS_INIT_REFCNT();
}
virtual ~nsAuthURLParser();
static NS_METHOD
Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
///////////////////////////////////////////////////////////////////////////
// nsIURLParser methods:
NS_DECL_NSIURLPARSER
};
#endif // nsAuthURLParser_h__

View File

@@ -1,318 +0,0 @@
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* 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):
*/
#include "nsBufferedStreams.h"
#include "nsCRT.h"
////////////////////////////////////////////////////////////////////////////////
// nsBufferedStream
nsBufferedStream::nsBufferedStream()
: mBuffer(nsnull),
mBufferStartOffset(0),
mCursor(0),
mFillPoint(0),
mStream(nsnull)
{
NS_INIT_REFCNT();
}
nsBufferedStream::~nsBufferedStream()
{
Close();
}
NS_IMPL_THREADSAFE_ISUPPORTS2(nsBufferedStream,
nsIBaseStream,
nsISeekableStream);
nsresult
nsBufferedStream::Init(nsIBaseStream* stream, PRUint32 bufferSize)
{
NS_ASSERTION(stream, "need to supply a stream");
NS_ASSERTION(mStream == nsnull, "already inited");
mStream = stream;
NS_ADDREF(mStream);
mBufferSize = bufferSize;
mBufferStartOffset = 0;
mCursor = 0;
mBuffer = new char[bufferSize];
if (mBuffer == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
NS_IMETHODIMP
nsBufferedStream::Close()
{
nsresult rv = NS_OK;
if (mStream) {
rv = mStream->Close();
NS_RELEASE(mStream);
mStream = nsnull;
delete[] mBuffer;
mBuffer = nsnull;
mBufferSize = 0;
mBufferStartOffset = 0;
mCursor = 0;
}
return rv;
}
NS_IMETHODIMP
nsBufferedStream::Seek(PRInt32 whence, PRInt32 offset)
{
if (mStream == nsnull)
return NS_BASE_STREAM_CLOSED;
// If the underlying stream isn't a random access store, then fail early.
// We could possibly succeed for the case where the seek position denotes
// something that happens to be read into the buffer, but that would make
// the failure data-dependent.
nsresult rv;
nsCOMPtr<nsISeekableStream> ras = do_QueryInterface(mStream, &rv);
if (NS_FAILED(rv)) return rv;
PRInt32 absPos;
switch (whence) {
case nsISeekableStream::NS_SEEK_SET:
absPos = offset;
break;
case nsISeekableStream::NS_SEEK_CUR:
absPos = mBufferStartOffset + mCursor + offset;
break;
case nsISeekableStream::NS_SEEK_END:
absPos = -1;
break;
default:
NS_NOTREACHED("bogus seek whence parameter");
return NS_ERROR_UNEXPECTED;
}
if ((PRInt32)mBufferStartOffset <= absPos
&& absPos < (PRInt32)(mBufferStartOffset + mFillPoint)) {
mCursor = absPos - mBufferStartOffset;
return NS_OK;
}
rv = Flush();
if (NS_FAILED(rv)) return rv;
rv = ras->Seek(whence, offset);
if (NS_FAILED(rv)) return rv;
if (absPos == -1) {
// then we had the SEEK_END case, above
rv = ras->Tell(&mBufferStartOffset);
if (NS_FAILED(rv)) return rv;
}
else {
mBufferStartOffset = absPos;
}
mCursor = 0;
mFillPoint = 0;
return Fill();
}
NS_IMETHODIMP
nsBufferedStream::Tell(PRUint32 *result)
{
if (mStream == nsnull)
return NS_BASE_STREAM_CLOSED;
*result = mBufferStartOffset + mCursor;
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
// nsBufferedInputStream
NS_IMPL_ISUPPORTS_INHERITED2(nsBufferedInputStream,
nsBufferedStream,
nsIInputStream,
nsIBufferedInputStream);
NS_METHOD
nsBufferedInputStream::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
NS_ENSURE_NO_AGGREGATION(aOuter);
nsBufferedInputStream* stream = new nsBufferedInputStream();
if (stream == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(stream);
nsresult rv = stream->QueryInterface(aIID, aResult);
NS_RELEASE(stream);
return rv;
}
NS_IMETHODIMP
nsBufferedInputStream::Init(nsIInputStream* stream, PRUint32 bufferSize)
{
return nsBufferedStream::Init(stream, bufferSize);
}
NS_IMETHODIMP
nsBufferedInputStream::Close()
{
return nsBufferedStream::Close();
}
NS_IMETHODIMP
nsBufferedInputStream::Available(PRUint32 *result)
{
*result = mFillPoint - mCursor;
return NS_OK;
}
NS_IMETHODIMP
nsBufferedInputStream::Read(char * buf, PRUint32 count, PRUint32 *result)
{
nsresult rv = NS_OK;
PRUint32 read = 0;
while (count > 0) {
PRUint32 amt = PR_MIN(count, mFillPoint - mCursor);
if (amt > 0) {
nsCRT::memcpy(buf, mBuffer + mCursor, amt);
read += amt;
count -= amt;
mCursor += amt;
}
else {
rv = Fill();
if (NS_FAILED(rv)) break;
}
}
*result = read;
return (read > 0 || rv == NS_BASE_STREAM_CLOSED) ? NS_OK : rv;
}
NS_IMETHODIMP
nsBufferedInputStream::Fill()
{
nsresult rv;
PRUint32 rem = mFillPoint - mCursor;
if (rem > 0) {
// slide the remainder down to the start of the buffer
// |<------------->|<--rem-->|<--->|
// b c f s
nsCRT::memcpy(mBuffer, mBuffer + mCursor, rem);
}
mBufferStartOffset += mCursor;
mFillPoint = rem;
mCursor = 0;
PRUint32 amt;
rv = Source()->Read(mBuffer + mFillPoint, mBufferSize - mFillPoint, &amt);
if (NS_FAILED(rv)) return rv;
mFillPoint += amt;
return amt > 0 ? NS_OK : NS_BASE_STREAM_CLOSED;
}
////////////////////////////////////////////////////////////////////////////////
// nsBufferedOutputStream
NS_IMPL_ISUPPORTS_INHERITED2(nsBufferedOutputStream,
nsBufferedStream,
nsIOutputStream,
nsIBufferedOutputStream);
NS_METHOD
nsBufferedOutputStream::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult)
{
NS_ENSURE_NO_AGGREGATION(aOuter);
nsBufferedOutputStream* stream = new nsBufferedOutputStream();
if (stream == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
NS_ADDREF(stream);
nsresult rv = stream->QueryInterface(aIID, aResult);
NS_RELEASE(stream);
return rv;
}
NS_IMETHODIMP
nsBufferedOutputStream::Init(nsIOutputStream* stream, PRUint32 bufferSize)
{
mFillPoint = bufferSize; // always fill to the end for buffered output streams
return nsBufferedStream::Init(stream, bufferSize);
}
NS_IMETHODIMP
nsBufferedOutputStream::Close()
{
nsresult rv1, rv2;
rv1 = Flush();
// If we fail to Flush all the data, then we close anyway and drop the
// remaining data in the buffer. We do this because it's what Unix does
// for fclose and close. However, we report the error from Flush anyway.
rv2 = nsBufferedStream::Close();
if (NS_FAILED(rv1)) return rv1;
return rv2;
}
NS_IMETHODIMP
nsBufferedOutputStream::Write(const char *buf, PRUint32 count, PRUint32 *result)
{
nsresult rv = NS_OK;
PRUint32 written = 0;
while (count > 0) {
PRUint32 amt = PR_MIN(count, mFillPoint - mCursor);
if (amt > 0) {
nsCRT::memcpy(mBuffer + mCursor, buf + written, amt);
written += amt;
count -= amt;
mCursor += amt;
}
else {
rv = Flush();
if (NS_FAILED(rv)) break;
}
}
*result = written;
return (written > 0) ? NS_OK : rv;
}
NS_IMETHODIMP
nsBufferedOutputStream::Flush(void)
{
nsresult rv;
PRUint32 amt;
rv = Sink()->Write(mBuffer, mCursor, &amt);
if (NS_FAILED(rv)) return rv;
mBufferStartOffset += amt;
if (mCursor == amt) {
mCursor = 0;
return NS_OK; // flushed everything
}
// slide the remainder down to the start of the buffer
// |<-------------->|<---|----->|
// b a c s
PRUint32 rem = mCursor - amt;
nsCRT::memcpy(mBuffer, mBuffer + amt, rem);
mCursor = rem;
return NS_ERROR_FAILURE; // didn't flush all
}
////////////////////////////////////////////////////////////////////////////////

Some files were not shown because too many files have changed in this diff Show More