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
104 changed files with 5324 additions and 17710 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,74 +0,0 @@
#! gmake
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################

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 = protocol client
include $(topsrcdir)/config/rules.mk

View File

@@ -1,3 +0,0 @@
cmtclist.h
cmtcmn.h
cmtjs.h

View File

@@ -1,74 +0,0 @@
#! gmake
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
include config.mk
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################

View File

@@ -1,70 +0,0 @@
#! gmake
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
LIBRARY_NAME = cmt
EXPORTS = \
cmtcmn.h \
cmtjs.h \
cmtclist.h \
$(NULL)
MODULE = security
CSRCS = cmtinit.c \
cmtssl.c \
cmtutils.c \
cmtcert.c \
cmthash.c \
cmtpkcs7.c \
cmtres.c \
cmtjs.c \
cmtevent.c \
cmtpasswd.c \
cmtadvisor.c \
cmtrng.c \
cmtsdr.c \
$(NULL)
EXTRA_DSO_LDOPTS += -L$(DIST)/bin -lprotocol
include $(topsrcdir)/config/rules.mk

View File

@@ -1,99 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#ifdef XP_MAC
#include "cmtmac.h"
#endif
CMTStatus CMT_SecurityAdvisor(PCMT_CONTROL control, CMTSecurityAdvisorData* data, CMUint32 *resID)
{
CMTItem message = {0, NULL, 0};
SecurityAdvisorRequest request;
SingleNumMessage reply;
if (!control) {
return CMTFailure;
}
if (!data) {
return CMTFailure;
}
request.infoContext = data->infoContext;
request.resID = data->resID;
request.hostname = data->hostname;
request.senderAddr = data->senderAddr;
request.encryptedP7CInfo = data->encryptedP7CInfo;
request.signedP7CInfo = data->signedP7CInfo;
request.decodeError = data->decodeError;
request.verifyError = data->verifyError;
request.encryptthis = data->encryptthis;
request.signthis = data->signthis;
request.numRecipients = data->numRecipients;
request.recipients = data->recipients;
message.type = SSM_REQUEST_MESSAGE | SSM_SECURITY_ADVISOR;
if (CMT_EncodeMessage(SecurityAdvisorRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_SECURITY_ADVISOR)) {
goto loser;
}
/* Decode the message */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*resID = reply.value;
return CMTSuccess;
loser:
if (message.data) {
free(message.data);
}
return CMTFailure;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,111 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef cmtclist_h___
#define cmtclist_h___
typedef struct CMTCListStr CMTCList;
/*
** Circular linked list
*/
struct CMTCListStr {
CMTCList *next;
CMTCList *prev;
};
/*
** Insert element "_e" into the list, before "_l".
*/
#define CMT_INSERT_BEFORE(_e,_l) \
(_e)->next = (_l); \
(_e)->prev = (_l)->prev; \
(_l)->prev->next = (_e); \
(_l)->prev = (_e); \
/*
** Insert element "_e" into the list, after "_l".
*/
#define CMT_INSERT_AFTER(_e,_l) \
(_e)->next = (_l)->next; \
(_e)->prev = (_l); \
(_l)->next->prev = (_e); \
(_l)->next = (_e); \
/*
** Append an element "_e" to the end of the list "_l"
*/
#define CMT_APPEND_LINK(_e,_l) CMT_INSERT_BEFORE(_e,_l)
/*
** Insert an element "_e" at the head of the list "_l"
*/
#define CMT_INSERT_LINK(_e,_l) CMT_INSERT_AFTER(_e,_l)
/* Return the head/tail of the list */
#define CMT_LIST_HEAD(_l) (_l)->next
#define CMT_LIST_TAIL(_l) (_l)->prev
/*
** Remove the element "_e" from it's circular list.
*/
#define CMT_REMOVE_LINK(_e) \
(_e)->prev->next = (_e)->next; \
(_e)->next->prev = (_e)->prev; \
/*
** Remove the element "_e" from it's circular list. Also initializes the
** linkage.
*/
#define CMT_REMOVE_AND_INIT_LINK(_e) \
(_e)->prev->next = (_e)->next; \
(_e)->next->prev = (_e)->prev; \
(_e)->next = (_e); \
(_e)->prev = (_e); \
/*
** Return non-zero if the given circular list "_l" is empty, zero if the
** circular list is not empty
*/
#define CMT_CLIST_IS_EMPTY(_l) \
((_l)->next == (_l))
/*
** Initialize a circular list
*/
#define CMT_INIT_CLIST(_l) \
(_l)->next = (_l); \
(_l)->prev = (_l); \
#define CMT_INIT_STATIC_CLIST(_l) \
{(_l), (_l)}
#endif /* cmtclist_h___ */

File diff suppressed because it is too large Load Diff

View File

@@ -1,480 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include <string.h>
#ifdef XP_UNIX
#include <sys/time.h>
#endif
/* Typedefs */
typedef void (*taskcompleted_handler_fn)(CMUint32 resourceID, CMUint32 numReqProcessed, CMUint32 resultCode, void* data);
CMTStatus CMT_SetUIHandlerCallback(PCMT_CONTROL control,
uiHandlerCallback_fn f, void *data)
{
return CMT_RegisterEventHandler(control, SSM_UI_EVENT, 0,
(void_fun)f, data);
}
void CMT_SetFilePathPromptCallback(PCMT_CONTROL control,
filePathPromptCallback_fn f, void* arg)
{
control->userFuncs.promptFilePath = f;
control->userFuncs.filePromptArg = arg;
}
void CMT_SetPromptCallback(PCMT_CONTROL control,
promptCallback_fn f, void *arg)
{
control->userFuncs.promptCallback = f;
control->userFuncs.promptArg = arg;
}
void CMT_SetSavePrefsCallback(PCMT_CONTROL control, savePrefsCallback_fn f)
{
control->userFuncs.savePrefs = f;
}
CMTStatus CMT_RegisterEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID, void_fun handler,
void* data)
{
PCMT_EVENT ptr;
/* This is the first connection */
if (control->cmtEventHandlers == NULL) {
control->cmtEventHandlers = ptr =
(PCMT_EVENT)calloc(sizeof(CMT_EVENT), 1);
if (!ptr) {
goto loser;
}
} else {
/* Look for another event handler of the same type. Make sure the
event handler with a rsrcid of 0 is farther down the list so
that it doesn't get chosen when there's an event handler for
a specific rsrcid.
*/
for (ptr=control->cmtEventHandlers; ptr != NULL; ptr = ptr->next) {
if (ptr->type == type && resourceID != 0) {
/* So we've got an event handler that wants to over-ride
an existing event handler. We'll put it before the one
that's already here.
*/
if (ptr->previous == NULL) {
/* We're going to insert at the front of the list*/
control->cmtEventHandlers = ptr->previous =
(PCMT_EVENT)calloc(sizeof(CMT_EVENT), 1);
if (ptr->previous == NULL) {
goto loser;
}
ptr->previous->next = ptr;
ptr = control->cmtEventHandlers;
} else {
/* We want to insert in the middle of the list */
PCMT_EVENT tmpEvent;
tmpEvent = (PCMT_EVENT)calloc(sizeof(CMT_EVENT), 1);
if (tmpEvent == NULL) {
goto loser;
}
tmpEvent->previous = ptr->previous;
ptr->previous->next = tmpEvent;
tmpEvent->next = ptr;
ptr->previous = tmpEvent;
ptr = tmpEvent;
}
break;
}
if (ptr->next == NULL) break;
}
if (ptr == NULL) {
goto loser;
}
if (ptr->next == NULL) {
/* We're adding the event handler at the end of the list. */
ptr->next = (PCMT_EVENT)calloc(sizeof(CMT_EVENT), 1);
if (!ptr->next) {
goto loser;
}
/* Fix up the pointers */
ptr->next->previous = ptr;
ptr = ptr->next;
}
}
/* Fill in the data */
ptr->type = type;
ptr->resourceID = resourceID;
ptr->handler = handler;
ptr->data = data;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_UnregisterEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID)
{
PCMT_EVENT ptr, pptr = NULL;
for (ptr = control->cmtEventHandlers; ptr != NULL;
pptr = ptr, ptr = ptr->next) {
if ((ptr->type == type) && (ptr->resourceID == resourceID)) {
if (pptr == NULL) {
/* node is at head */
control->cmtEventHandlers = ptr->next;
if (control->cmtEventHandlers != NULL) {
control->cmtEventHandlers->previous = NULL;
}
free(ptr);
return CMTSuccess;
}
/* node is elsewhere */
pptr->next = ptr->next;
if (ptr->next != NULL) {
ptr->next->previous = pptr;
}
free(ptr);
return CMTSuccess;
}
}
return CMTFailure;
}
PCMT_EVENT CMT_GetEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID)
{
PCMT_EVENT ptr;
for (ptr = control->cmtEventHandlers; ptr != NULL; ptr = ptr->next) {
if ((ptr->type == type) && ((ptr->resourceID == resourceID) ||
!ptr->resourceID)) {
return ptr;
}
}
return NULL;
}
PCMT_EVENT CMT_GetFirstEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID)
{
PCMT_EVENT ptr;
for (ptr = control->cmtEventHandlers; ptr != NULL; ptr = ptr->next) {
if ((ptr->type == type) && ((ptr->resourceID == resourceID) ||
!ptr->resourceID)) {
return ptr;
}
}
return NULL;
}
PCMT_EVENT CMT_GetNextEventHandler(PCMT_CONTROL control, PCMT_EVENT e)
{
PCMT_EVENT ptr;
for (ptr = control->cmtEventHandlers; ptr != NULL || ptr == e;
ptr = ptr->next) {
}
for (; ptr != NULL; ptr = ptr->next) {
if ((ptr->type == e->type) && ((ptr->resourceID == e->resourceID) ||
!ptr->resourceID)) {
return ptr;
}
}
return NULL;
}
void CMT_ProcessEvent(PCMT_CONTROL cm_control)
{
CMTSocket sock;
CMTItem eventData={ 0, NULL, 0 };
/* Get the control socket */
sock = cm_control->sock;
/* Acquire a lock on the control connection */
CMT_LOCK(cm_control->mutex);
/* Do another select here to be sure
that the socket is readable */
if (cm_control->sockFuncs.select(&sock, 1, 1) != sock) {
/* There's no event. */
goto done;
}
/* Read the event */
if (CMT_ReceiveMessage(cm_control, &eventData) == CMTFailure) {
goto done;
}
CMT_UNLOCK(cm_control->mutex);
/* Dispatch the event */
CMT_DispatchEvent(cm_control, &eventData);
return;
done:
/* Release the lock on the control connection */
CMT_UNLOCK(cm_control->mutex);
}
void CMT_EventLoop(PCMT_CONTROL cm_control)
{
CMTSocket sock;
/* Get the control socket */
sock = cm_control->sock;
CMT_ReferenceControlConnection(cm_control);
/* Select on the control socket to see if it's readable */
while(cm_control->sockFuncs.select(&sock, 1, 0)) {
CMT_ProcessEvent(cm_control);
}
CMT_CloseControlConnection(cm_control);
return;
}
void
CMT_PromptUser(PCMT_CONTROL cm_control, CMTItem *eventData)
{
char *promptReply = NULL;
CMTItem response={ 0, NULL, 0 };
PromptRequest request;
PromptReply reply;
void * clientContext;
/* Decode the message */
if (CMT_DecodeMessage(PromptRequestTemplate, &request, eventData) != CMTSuccess) {
goto loser;
}
/* Copy the client context to a pointer */
clientContext = CMT_CopyItemToPtr(request.clientContext);
if (cm_control->userFuncs.promptCallback == NULL) {
goto loser;
}
promptReply =
cm_control->userFuncs.promptCallback(cm_control->userFuncs.promptArg,
request.prompt, clientContext, 1);
response.type = SSM_EVENT_MESSAGE | SSM_PROMPT_EVENT;
if (!promptReply) {
/* the user canceled the prompt or other errors occurred */
reply.cancel = CM_TRUE;
}
else {
/* note that this includes an empty string (zero length) password */
reply.cancel = CM_FALSE;
}
reply.resID = request.resID;
reply.promptReply = promptReply;
/* Encode the message */
if (CMT_EncodeMessage(PromptReplyTemplate, &response, &reply) != CMTSuccess) {
goto loser;
}
CMT_TransmitMessage(cm_control, &response);
loser:
if (promptReply != NULL) {
cm_control->userFuncs.userFree(promptReply);
}
return;
}
void CMT_GetFilePath(PCMT_CONTROL cm_control, CMTItem * eventData)
{
char *fileName=NULL;
CMTItem response = { 0, NULL, 0 };
FilePathRequest request;
FilePathReply reply;
/* Decode the request */
if (CMT_DecodeMessage(FilePathRequestTemplate, &request, eventData) != CMTSuccess) {
goto loser;
}
if (cm_control->userFuncs.promptFilePath == NULL) {
goto loser;
}
fileName =
cm_control->userFuncs.promptFilePath(cm_control->userFuncs.filePromptArg,
request.prompt, request.fileRegEx,
request.getExistingFile);
response.type = SSM_EVENT_MESSAGE | SSM_FILE_PATH_EVENT;
reply.resID = request.resID;
reply.filePath = fileName;
/* Encode the reply */
if (CMT_EncodeMessage(FilePathReplyTemplate, &response, &reply) != CMTSuccess) {
goto loser;
}
CMT_TransmitMessage(cm_control, &response);
cm_control->userFuncs.userFree(fileName);
loser:
return;
}
void CMT_SavePrefs(PCMT_CONTROL cm_control, CMTItem* eventData)
{
SetPrefListMessage request;
int i;
/* decode the request */
if (CMT_DecodeMessage(SetPrefListMessageTemplate, &request, eventData) !=
CMTSuccess) {
return;
}
if (cm_control->userFuncs.savePrefs == NULL) {
/* callback was not registered: bail */
return;
}
cm_control->userFuncs.savePrefs(request.length,
(CMTSetPrefElement*)request.list);
for (i = 0; i < request.length; i++) {
if (request.list[i].key != NULL) {
free(request.list[i].key);
}
if (request.list[i].value != NULL) {
free(request.list[i].value);
}
}
return;
}
void CMT_DispatchEvent(PCMT_CONTROL cm_control, CMTItem * eventData)
{
CMUint32 eventType;
CMTItem msgCopy;
/* Init the msgCopy */
msgCopy.data = 0;
/* Get the event type */
if ((eventData->type & SSM_CATEGORY_MASK) != SSM_EVENT_MESSAGE) {
/* Somehow there was a message on the socket that was not
* an event message. Dropping it on the floor.
*/
goto loser;
}
eventType = (eventData->type & SSM_TYPE_MASK);
/* We must now dispatch the event based on it's type */
switch (eventType) {
case SSM_UI_EVENT:
{
PCMT_EVENT p;
UIEvent event;
void * clientContext = NULL;
/* Copy the message to allow a second try with the old format */
msgCopy.len = eventData->len;
msgCopy.data = calloc(msgCopy.len, 1);
if (msgCopy.data) {
memcpy(msgCopy.data, eventData->data, eventData->len);
}
/* Get the event data first */
if (CMT_DecodeMessage(UIEventTemplate, &event, eventData) != CMTSuccess) {
/* Attempt to decode using the old format. Modal is True */
if (!msgCopy.data ||
CMT_DecodeMessage(OldUIEventTemplate, &event, &msgCopy) != CMTSuccess) {
goto loser;
}
/* Set default modal value */
event.isModal = CM_TRUE;
}
/* Convert the client context to a pointer */
clientContext = CMT_CopyItemToPtr(event.clientContext);
/* Call any handlers for this event */
p = CMT_GetEventHandler(cm_control, eventType, event.resourceID);
if (!p) {
goto loser;
}
(*(uiHandlerCallback_fn)(p->handler))(event.resourceID,
clientContext, event.width,
event.height, event.isModal, event.url,
p->data);
break;
}
case SSM_TASK_COMPLETED_EVENT:
{
PCMT_EVENT p;
TaskCompletedEvent event;
/* Get the event data */
if (CMT_DecodeMessage(TaskCompletedEventTemplate, &event, eventData) != CMTSuccess) {
goto loser;
}
/* Call handler for this event */
p = CMT_GetEventHandler(cm_control, eventType, event.resourceID);
if (!p) {
goto loser;
}
(*(taskcompleted_handler_fn)(p->handler))(event.resourceID,
event.numTasks,
event.result, p->data);
break;
}
case SSM_AUTH_EVENT:
CMT_ServicePasswordRequest(cm_control, eventData);
break;
case SSM_FILE_PATH_EVENT:
CMT_GetFilePath(cm_control, eventData);
break;
case SSM_PROMPT_EVENT:
CMT_PromptUser(cm_control, eventData);
break;
case SSM_SAVE_PREF_EVENT:
CMT_SavePrefs(cm_control, eventData);
break;
default:
break;
}
loser:
free(eventData->data);
free(msgCopy.data);
return;
}

View File

@@ -1,216 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef XP_MAC
#include "macsocket.h"
#include "string.h"
#else
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include <errno.h>
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "rsrcids.h"
CMTStatus CMT_HashCreate(PCMT_CONTROL control, CMUint32 algID,
CMUint32 * connID)
{
CMTItem message;
SingleNumMessage request;
DataConnectionReply reply;
/* Check passed in parameters */
if (!control) {
goto loser;
}
/* Set up the request */
request.value = algID;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION | SSM_HASH_STREAM;
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the response */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION | SSM_HASH_STREAM)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
CMTSocket sock;
sock = control->sockFuncs.socket(0);
if(sock == NULL) {
goto loser;
}
if (control->sockFuncs.connect(sock, reply.port, NULL) != CMTSuccess) {
goto loser;
}
/* Send the hello message */
control->sockFuncs.send(sock, control->nonce.data, control->nonce.len);
/* Save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID)
!= CMTSuccess) {
goto loser;
}
/* Set the connection ID */
*connID = reply.connID;
return CMTSuccess;
}
loser:
*connID = 0;
return CMTFailure;
}
CMTStatus CMT_HASH_Destroy(PCMT_CONTROL control, CMUint32 connectionID)
{
if (!control) {
goto loser;
}
/* Get the cotext implementation data */
if (CMT_CloseDataConnection(control, connectionID) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_HASH_Begin(PCMT_CONTROL control, CMUint32 connectionID)
{
return CMTSuccess;
}
CMTStatus CMT_HASH_Update(PCMT_CONTROL control, CMUint32 connectionID, const unsigned char * buf, CMUint32 len)
{
CMTSocket sock;
CMUint32 sent;
/* Do some parameter checking */
if (!control || !buf) {
goto loser;
}
/* Get the data socket */
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
/* Write the data to the socket */
sent = CMT_WriteThisMany(control, sock, (void*)buf, len);
if (sent != len) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_HASH_End(PCMT_CONTROL control, CMUint32 connectionID,
unsigned char * result, CMUint32 * resultlen,
CMUint32 maxLen)
{
CMTItem hash = { 0, NULL, 0 };
/* Do some parameter checking */
if (!control || !result || !resultlen) {
goto loser;
}
/* Close the connection */
if (CMT_CloseDataConnection(control, connectionID) == CMTFailure) {
goto loser;
}
/* Get the context info */
if (CMT_GetStringAttribute(control, connectionID, SSM_FID_HASHCONN_RESULT,
&hash) == CMTFailure) {
goto loser;
}
if (!hash.data) {
goto loser;
}
*resultlen = hash.len;
if (hash.len > maxLen) {
memcpy(result, hash.data, maxLen);
} else {
memcpy(result, hash.data, hash.len);
}
if (hash.data) {
free(hash.data);
}
return CMTSuccess;
loser:
if (hash.data) {
free(hash.data);
}
return CMTFailure;
}

View File

@@ -1,56 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef __CMTIMPL_H_
#define __CMTIMPL_H_
typedef unsigned long CMT_HANDLE;
struct _CMTControl {
CMT_HANDLE channelID;
int socketID;
CMTStatus (* cmtEventCallback)(struct _CMTControl * control,
CMTItem * event, void * arg);
void * cmtEventCallbackArg;
struct _CMTData * cmtDataConnection;
} _CMTControl;
struct _CMTData {
CMT_HANDLE channelID;
int socketID;
struct _CMTData * next;
struct _CMTData * previous;
};
#endif /*__CMTIMPL_H_*/

View File

@@ -1,484 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifdef XP_UNIX
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <netinet/tcp.h>
#else
#ifdef XP_MAC
#include <Events.h> // for WaitNextEvent
#else /* Windows */
#include <windows.h>
#include <winsock.h>
#include <direct.h>
#include <sys/stat.h>
#endif
#endif
#include "messages.h"
#include "cmtcmn.h"
#include "cmtutils.h"
#include <string.h>
#ifdef XP_UNIX
#define DIRECTORY_SEPARATOR '/'
#elif defined WIN32
#define DIRECTORY_SEPARATOR '\\'
#elif defined XP_MAC
#define DIRECTORY_SEPARATOR ':'
#endif
/* Local defines */
#define CARTMAN_PORT 11111
#define MAX_PATH_LEN 256
/* write to the cmnav.log */
#if 0
#define LOG(x); do { FILE *f; f=fopen("cmnav.log","a+"); if (f) { \
fprintf(f, x); fclose(f); } } while(0);
#define LOG_S(x); do { FILE *f; f=fopen("cmnav.log","a+"); if (f) { \
fprintf(f, "%s", x); fclose(f); } } while(0);
#define ASSERT(x); if (!(x)) { LOG("ASSERT:"); LOG(#x); LOG("\n"); exit(-1); }
#else
#define LOG(x); ;
#define LOG_S(x); ;
#define ASSERT(x); ;
#endif
static char*
getCurrWorkDir(char *buf, int maxLen)
{
#if defined WIN32
return _getcwd(buf, maxLen);
#elif defined XP_UNIX
return getcwd(buf, maxLen);
#else
return NULL;
#endif
}
static void
setWorkingDir(char *path)
{
#if defined WIN32
_chdir(path);
#elif defined XP_UNIX
chdir(path);
#else
return;
#endif
}
static CMTStatus
launch_psm(char *executable)
{
char command[MAX_PATH_LEN];
#ifdef WIN32
STARTUPINFO sui;
PROCESS_INFORMATION pi;
UNALIGNED long *posfhnd;
int i;
char *posfile;
sprintf(command,"%s > psmlog", executable);
ZeroMemory( &sui, sizeof(sui) );
sui.cb = sizeof(sui);
sui.cbReserved2 = (WORD)(sizeof( int ) + (3 * (sizeof( char ) +
sizeof( long ))));
sui.lpReserved2 = calloc( sui.cbReserved2, 1 );
*((UNALIGNED int *)(sui.lpReserved2)) = 3;
posfile = (char *)(sui.lpReserved2 + sizeof( int ));
posfhnd = (UNALIGNED long *)(sui.lpReserved2 + sizeof( int ) +
(3 * sizeof( char )));
for ( i = 0, posfile = (char *)(sui.lpReserved2 + sizeof( int )),
posfhnd = (UNALIGNED long *)(sui.lpReserved2 + sizeof( int ) + (3 * sizeof( char ))) ;
i < 3 ; i++, posfile++, posfhnd++ ) {
*posfile = 0;
*posfhnd = (long)INVALID_HANDLE_VALUE;
}
/* Now, fire up PSM */
if (!CreateProcess(NULL, command, NULL, NULL, TRUE, DETACHED_PROCESS,
NULL, NULL, &sui, &pi)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
#elif defined XP_UNIX
sprintf(command,"./%s &", executable);
if (system(command) == -1) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
#else
return CMTFailure;
#endif
}
PCMT_CONTROL CMT_EstablishControlConnection(char *inPath,
CMT_SocketFuncs *sockFuncs,
CMT_MUTEX *mutex)
{
PCMT_CONTROL control;
char *executable;
char *newWorkingDir;
char oldWorkingDir[MAX_PATH_LEN];
int i;
char *path = NULL;
size_t stringLen;
/* On the Mac, we do special magic in the Seamonkey PSM component, so
if PSM isn't launched by the time we reach this point, we're not doing well. */
#ifndef XP_MAC
struct stat stbuf;
/*
* Create our own copy of path.
* I'd like to do a straight strdup here, but that caused problems
* for https.
*/
stringLen = strlen(inPath);
path = (char*) malloc(stringLen+1);
memcpy(path, inPath, stringLen);
path[stringLen] = '\0';
control = CMT_ControlConnect(mutex, sockFuncs);
if (control != NULL) {
return control;
}
/*
* We have to try to launch it now, so it better be a valid
* path.
*/
if (stat(path, &stbuf) == -1) {
goto loser;
}
/*
* Now we have to parse the path and launch the psm server.
*/
executable = strrchr(path, DIRECTORY_SEPARATOR);
if (executable != NULL) {
*executable = '\0';
executable ++;
newWorkingDir = path;
} else {
executable = path;
newWorkingDir = NULL;
}
if (getCurrWorkDir(oldWorkingDir, MAX_PATH_LEN) == NULL) {
goto loser;
}
setWorkingDir(newWorkingDir);
if (launch_psm(executable) != CMTSuccess) {
goto loser;
}
setWorkingDir(oldWorkingDir);
#endif
/*
* Now try to connect to the psm server. We will try to connect
* a maximum of 30 times and then give up.
*/
#ifdef WIN32
for (i=0; i<30; i++) {
Sleep(1000);
control = CMT_ControlConnect(mutex, sockFuncs);
if (control != NULL) {
break;
}
}
#elif defined XP_UNIX
i = 0;
while (i<1000) {
i += sleep(10);
control = CMT_ControlConnect(mutex, sockFuncs);
if (control != NULL) {
break;
}
}
#elif defined(XP_MAC)
for (i=0; i<30; i++)
{
EventRecord theEvent;
WaitNextEvent(0, &theEvent, 30, NULL);
control = CMT_ControlConnect(mutex, sockFuncs);
if (control != NULL)
break;
}
#else
/*
* Figure out how to sleep for a while first
*/
for (i=0; i<30; i++) {
control = CMT_ControlConnect(mutex, sockFuncs);
if (control!= NULL) {
break;
}
}
#endif
if (control == NULL) {
goto loser;
}
if (path) {
free (path);
}
return control;
loser:
if (control != NULL) {
CMT_CloseControlConnection(control);
}
if (path) {
free(path);
}
return NULL;
}
PCMT_CONTROL CMT_ControlConnect(CMT_MUTEX *mutex, CMT_SocketFuncs *sockFuncs)
{
PCMT_CONTROL control = NULL;
CMTSocket sock=NULL;
#ifdef XP_UNIX
int unixSock = 1;
char path[20];
#else
int unixSock = 0;
char *path=NULL;
#endif
if (sockFuncs == NULL) {
return NULL;
}
#ifdef XP_UNIX
sprintf(path, "/tmp/.nsmc-%d", (int)geteuid());
#endif
sock = sockFuncs->socket(unixSock);
if (sock == NULL) {
LOG("Could not create a socket to connect to Control Connection.\n");
goto loser;
}
/* Connect to the psm process */
if (sockFuncs->connect(sock, CARTMAN_PORT, path)) {
LOG("Could not connect to Cartman\n");
goto loser;
}
#ifdef XP_UNIX
if (sockFuncs->verify(sock) != CMTSuccess) {
goto loser;
}
#endif
LOG("Connected to Cartman\n");
/* fill in the CMTControl struct */
control = (PCMT_CONTROL)calloc(sizeof(CMT_CONTROL), 1);
if (control == NULL ) {
goto loser;
}
control->sock = sock;
if (mutex != NULL) {
control->mutex = (CMT_MUTEX*)calloc(sizeof(CMT_MUTEX),1);
if (control->mutex == NULL) {
goto loser;
}
*control->mutex = *mutex;
}
memcpy(&control->sockFuncs, sockFuncs, sizeof(CMT_SocketFuncs));
control->refCount = 1;
goto done;
loser:
if (control != NULL) {
free(control);
}
if (sock != NULL) {
sockFuncs->close(sock);
}
control = NULL;
done:
return control;
}
CMTStatus CMT_CloseControlConnection(PCMT_CONTROL control)
{
/* XXX Don't know what to do here yet */
if (control != NULL) {
CMInt32 refCount;
CMT_LOCK(control->mutex);
control->refCount--;
refCount = control->refCount;
CMT_UNLOCK(control->mutex);
if (refCount <= 0) {
if (control->mutex != NULL) {
free (control->mutex);
}
control->sockFuncs.close(control->sock);
free(control);
}
}
return CMTSuccess;
}
CMTStatus CMT_Hello(PCMT_CONTROL control, CMUint32 version, char* profile,
char* profileDir)
{
CMTItem message;
PCMT_EVENT eventHandler;
CMBool doesUI;
HelloRequest request;
HelloReply reply;
/* Check the passed parameters */
if (!control) {
return CMTFailure;
}
if (!profile) {
return CMTFailure;
}
if (!profileDir) {
return CMTFailure;
}
/* Create the hello message */
eventHandler = CMT_GetEventHandler(control, SSM_UI_EVENT, 0);
doesUI = (eventHandler == NULL) ? CM_FALSE : CM_TRUE;
/* Setup the request struct */
request.version = version;
request.policy = 0; /* no more policy */
request.doesUI = doesUI;
request.profile = profile;
request.profileDir = profileDir;
message.type = SSM_REQUEST_MESSAGE | SSM_HELLO_MESSAGE;
if (CMT_EncodeMessage(HelloRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_HELLO_MESSAGE)) {
goto loser;
}
/* Decode the message */
if (CMT_DecodeMessage(HelloReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Successful response */
if (reply.result == 0) {
/* Save the nonce value */
control->sessionID = reply.sessionID;
control->protocolVersion = reply.version;
control->port = reply.httpPort;
control->nonce = reply.nonce;
control->policy = reply.policy;
control->serverStringVersion = reply.stringVersion;
/* XXX Free the messages */
return CMTSuccess;
}
loser:
/* XXX Free the messages */
return CMTFailure;
}
CMTStatus CMT_PassAllPrefs(PCMT_CONTROL control, int num,
CMTSetPrefElement* list)
{
SetPrefListMessage request;
SingleNumMessage reply;
CMTItem message;
if ((control == NULL) || (list == NULL)) {
return CMTFailure;
}
/* pack the request */
request.length = num;
request.list = (SetPrefElement*)list;
if (CMT_EncodeMessage(SetPrefListMessageTemplate, &message, &request) !=
CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_PREF_ACTION;
/* send the message */
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PREF_ACTION)) {
goto loser;
}
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
/* don't really need to check the return value */
return CMTSuccess;
loser:
return CMTFailure;
}
char* CMT_GetServerStringVersion(PCMT_CONTROL control)
{
if (control == NULL) {
return NULL;
}
return control->serverStringVersion;
}

View File

@@ -1,556 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "cmtutils.h"
#include "cmtjs.h"
#include "messages.h"
CMTStatus
CMT_GenerateKeyPair(PCMT_CONTROL control, CMUint32 keyGenContext,
CMUint32 mechType, CMTItem *param, CMUint32 keySize,
CMUint32 *keyPairId)
{
CMTItem message;
CMTStatus rv;
KeyPairGenRequest request = {0, 0, 0, {0, NULL, 0}};
SingleNumMessage reply;
if (!control) {
return CMTFailure;
}
request.keyGenCtxtID = keyGenContext;
request.genMechanism = mechType;
if (param) {
request.params = *param;
}
request.keySize = keySize;
/* Encode the message */
if (CMT_EncodeMessage(KeyPairGenRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_CREATE_KEY_PAIR;
/* Send the message and get the response */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION | SSM_CREATE_KEY_PAIR)) {
goto loser;
}
/* Decode the message */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*keyPairId = reply.value;
return CMTSuccess;
loser:
*keyPairId = 0;
return CMTFailure;
}
CMTStatus
CMT_CreateNewCRMFRequest(PCMT_CONTROL control, CMUint32 keyPairID,
SSMKeyGenType keyGenType, CMUint32 *reqID)
{
CMTItem message;
CMTStatus rv;
SingleNumMessage request;
SingleNumMessage reply;
if (!control) {
return CMTFailure;
}
request.value = keyPairID;
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_CRMF_ACTION |
SSM_CREATE_CRMF_REQ;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_CRMF_ACTION | SSM_CREATE_CRMF_REQ)) {
goto loser;
}
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*reqID = reply.value;
rv = CMT_SetNumericAttribute(control, *reqID, SSM_FID_CRMFREQ_KEY_TYPE,
keyGenType);
if (rv != CMTSuccess) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_EncodeCRMFRequest(PCMT_CONTROL control, CMUint32 *crmfReqID,
CMUint32 numRequests, char ** der)
{
CMTItem message;
CMTStatus rv;
EncodeCRMFReqRequest request;
SingleItemMessage reply;
if (!control) {
return CMTFailure;
}
request.numRequests = numRequests;
request.reqIDs = (long *) crmfReqID;
/* Encode the request */
if (CMT_EncodeMessage(EncodeCRMFReqRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_CRMF_ACTION | SSM_DER_ENCODE_REQ;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_CRMF_ACTION | SSM_DER_ENCODE_REQ)) {
goto loser;
}
/* XXX Should this be a string? Decode the message */
if (CMT_DecodeMessage(SingleItemMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*der = (char *) reply.item.data;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_ProcessCMMFResponse(PCMT_CONTROL control, char *nickname,
char *certRepString, CMBool doBackup,
void *clientContext)
{
CMTItem message;
CMTStatus rv;
CMMFCertResponseRequest request;
if(!control) {
return CMTFailure;
}
request.nickname = nickname;
request.base64Der = certRepString;
request.doBackup = doBackup;
request.clientContext = CMT_CopyPtrToItem(clientContext);
/* Encode the request */
if (CMT_EncodeMessage(CMMFCertResponseRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_CRMF_ACTION | SSM_PROCESS_CMMF_RESP;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_CRMF_ACTION | SSM_PROCESS_CMMF_RESP)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_CreateResource(PCMT_CONTROL control, SSMResourceType resType,
CMTItem *params, CMUint32 *rsrcId, CMUint32 *errorCode)
{
CMTItem message;
CMTStatus rv;
CreateResourceRequest request = {0, {0, NULL, 0}};
CreateResourceReply reply;
request.type = resType;
if (params) {
request.params = *params;
}
/* Encode the request */
if (CMT_EncodeMessage(CreateResourceRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_CREATE_RESOURCE;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_CREATE_RESOURCE)) {
goto loser;
}
/* Decode the message */
if (CMT_DecodeMessage(CreateResourceReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*rsrcId = reply.resID;
*errorCode = reply.result;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_SignText(PCMT_CONTROL control, CMUint32 resID, char* stringToSign, char* hostName, char* caOption, CMInt32 numCAs, char** caNames)
{
CMTItem message;
SignTextRequest request;
/* So some basic parameter checking */
if (!control || !stringToSign) {
goto loser;
}
/* Set up the request */
request.resID = resID;
request.stringToSign = stringToSign;
request.hostName = hostName;
request.caOption = caOption;
request.numCAs = numCAs;
request.caNames = caNames;
/* Encode the message */
if (CMT_EncodeMessage(SignTextRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_FORMSIGN_ACTION | SSM_SIGN_TEXT;
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_FORMSIGN_ACTION | SSM_SIGN_TEXT)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_ProcessChallengeResponse(PCMT_CONTROL control, char *challengeString,
char **responseString)
{
CMTItem message;
CMTStatus rv;
SingleStringMessage request;
SingleStringMessage reply;
/* Set the request */
request.string = challengeString;
/* Encode the request */
if (CMT_EncodeMessage(SingleStringMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_CRMF_ACTION | SSM_CHALLENGE;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_CRMF_ACTION | SSM_CHALLENGE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(SingleStringMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*responseString = reply.string;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_FinishGeneratingKeys(PCMT_CONTROL control, CMUint32 keyGenContext)
{
CMTItem message;
CMTStatus rv;
SingleNumMessage request;
/* Set up the request */
request.value = keyGenContext;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_FINISH_KEY_GEN;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the reply */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION | SSM_FINISH_KEY_GEN)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_GetLocalizedString(PCMT_CONTROL control,
SSMLocalizedString whichString,
char **localizedString)
{
CMTItem message;
CMTStatus rv;
SingleNumMessage request;
GetLocalizedTextReply reply;
/* Set up the request */
request.value = whichString;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_LOCALIZED_TEXT;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_LOCALIZED_TEXT)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(GetLocalizedTextReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
if (reply.whichString != whichString) {
goto loser;
}
*localizedString = reply.localizedString;
return CMTSuccess;
loser:
*localizedString = NULL;
return rv;
}
CMTStatus
CMT_AddNewModule(PCMT_CONTROL control,
char *moduleName,
char *libraryPath,
unsigned long pubMechFlags,
unsigned long pubCipherFlags)
{
CMTItem message;
CMTStatus rv;
AddNewSecurityModuleRequest request;
SingleNumMessage reply;
/* Set up the request */
request.moduleName = moduleName;
request.libraryPath = libraryPath;
request.pubMechFlags = pubMechFlags;
request.pubCipherFlags = pubCipherFlags;
/* Encode the request */
if (CMT_EncodeMessage(AddNewSecurityModuleRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_ADD_NEW_MODULE;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION | SSM_ADD_NEW_MODULE)) {
goto loser;
}
/* Decode the response */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
return (CMTStatus) reply.value;
loser:
return CMTFailure;
}
CMTStatus
CMT_DeleteModule(PCMT_CONTROL control,
char *moduleName,
int *moduleType)
{
CMTItem message;
CMTStatus rv;
SingleStringMessage request;
SingleNumMessage reply;
/* Set up the request */
request.string = moduleName;
/* Encode the request */
if (CMT_EncodeMessage(SingleStringMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_DEL_MODULE;
/* Send the message */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION | SSM_DEL_MODULE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*moduleType = reply.value;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_LogoutAllTokens(PCMT_CONTROL control)
{
CMTItem message;
CMTStatus rv;
message.type = SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION | SSM_LOGOUT_ALL;
message.data = NULL;
message.len = 0;
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) {
return rv;
}
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION |
SSM_LOGOUT_ALL)) {
return CMTFailure;
}
return CMTSuccess;
}
CMTStatus CMT_GetSSLCapabilities(PCMT_CONTROL control, CMInt32 *capabilites)
{
SingleNumMessage reply;
CMTItem message;
CMTStatus rv;
message.type = (SSM_REQUEST_MESSAGE | SSM_PKCS11_ACTION |
SSM_ENABLED_CIPHERS);
message.data = NULL;
message.len = 0;
rv = CMT_SendMessage(control, &message);
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_PKCS11_ACTION |
SSM_ENABLED_CIPHERS)) {
goto loser;
}
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply,
&message) != CMTSuccess) {
goto loser;
}
*capabilites = reply.value;
return CMTSuccess;
loser:
return CMTFailure;
}

View File

@@ -1,555 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef _CMTJS_H_
#define _CMTJS_H_
#include "cmtcmn.h"
#include "ssmdefs.h"
#include "rsrcids.h"
/*
* Define some constants.
*/
/*
* These defines are used in conjuction with the function
* CMT_AddNewModule.
*/
#define PUBLIC_MECH_RSA_FLAG 0x00000001ul
#define PUBLIC_MECH_DSA_FLAG 0x00000002ul
#define PUBLIC_MECH_RC2_FLAG 0x00000004ul
#define PUBLIC_MECH_RC4_FLAG 0x00000008ul
#define PUBLIC_MECH_DES_FLAG 0x00000010ul
#define PUBLIC_MECH_DH_FLAG 0x00000020ul
#define PUBLIC_MECH_FORTEZZA_FLAG 0x00000040ul
#define PUBLIC_MECH_RC5_FLAG 0x00000080ul
#define PUBLIC_MECH_SHA1_FLAG 0x00000100ul
#define PUBLIC_MECH_MD5_FLAG 0x00000200ul
#define PUBLIC_MECH_MD2_FLAG 0x00000400ul
#define PUBLIC_MECH_RANDOM_FLAG 0x08000000ul
#define PUBLIC_MECH_FRIENDLY_FLAG 0x10000000ul
#define PUBLIC_OWN_PW_DEFAULTS 0X20000000ul
#define PUBLIC_DISABLE_FLAG 0x40000000ul
/*
* This is the lone supported constant for the Cipher flag
* for CMT_AddNewModule
*/
#define PUBLIC_CIPHER_FORTEZZA_FLAG 0x00000001ul
CMT_BEGIN_EXTERN_C
/*
* FUNCTION: CMT_GenerateKeyPair
* -----------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* keyGenContext
* The Resource ID of a key gen context to use for creating the
* key pair.
* mechType
* A PKCS11 mechanism used to generate the key pair. Valid values are:
* CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000
* CKM_DSA_KEY_PAIR_GEN 0x00000010
* The definition of these values can be found at
* http://www.rsa.com/rsalabs/pubs/pkcs11.html
* The psm module currently supports v2.01 of PKCS11
* params
* This parameter will be used to pass parameters to the Key Pair
* generation process. Currently this feature is not supported, so
* pass in NULL for this parameter.
* keySize
* The size (in bits) of the key to generate.
* keyPairId
* A pointer to pre-allocated memory where the function can place
* the value of the resource ID of the key pair that gets created.
*
* NOTES:
* This function will send a message to the psm server requesting that
* a public/private key pair be generated. The key gen context will queue
* the request. You can send as many key gen requests as you want with a
* given key gen context. After sending all the key gen requests, the user
* must call CMT_FinishGeneratingKeys so that the key gen context actually
* generates the keys.
*
* RETURN:
* A return value of CMTSuccess indicates the request for key generation
* was queued successfully and the corresponding resource ID can be found
* at *keyPairId. Any other return value indicates an error and the value
* at *keyPairId should be ignored.
*/
CMTStatus
CMT_GenerateKeyPair(PCMT_CONTROL control, CMUint32 keyGenContext,
CMUint32 mechType, CMTItem *params, CMUint32 keySize,
CMUint32 *keyPairId);
/*
* FUNCTION: CMT_FinishGeneratingKeys
* ----------------------------------
* INPUTS
* control
* The Control Connection that has already established a connection
* with the psm server.
* keyGenContext
* The resource ID of the key gen context which should finish
* generating its key pairs.
* NOTES
* This function will send a message to the psm server notifying the key
* gen context with the resource ID of keyGenContext to finish generating
* all of the key gen requests it has queued up. After each key gen has
* finished, the psm server will send a SSM_TASK_COMPLETED_EVENT. So in order
* to detect when all of the key gens are done, the user should register
* an event handler. See comments for CMT_RegisterEventHandler for information
* on how to successfully register event handler callbacks. You must register
* the event handler with keyGenContext as the target resource ID for this
* to work correctly.
*
* RETURN:
* A return value of CMTSuccess indicates the key gen context has started to
* generate the key pairs in its queue. Any other return value indicates an
* error and the key pairs will not be generated.
*/
CMTStatus
CMT_FinishGeneratingKeys(PCMT_CONTROL control, CMUint32 keyGenContext);
/*
* FUNCTION: CMT_CreateNewCRMFRequest
* ----------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* keyPairID
* The resource ID of the key pair that should be associated with
* the CRMF request created. At the time this function is called,
* key pair should have already been created.
* keyGenType
* An enumeration that explains how the key pair will be used.
* Look at the definition of SSMKeyGenType in ssmdefs.h for valid
* values and their affects on the request.
* reqID
* A pointer to a pre-allocatd chunk of memory where the library
* can place the resource ID of the new CRMF request.
* NOTES:
* This function sends a message to the psm server requesting that a new
* CRMF resource object be created. Each CRMF request must be associated with
* a public/private key pair, that is why the keyPairID parameter exists.
* The keyGenType parameter is used to initialize the request, eg set the
* correct keyUsage extension.
*
* Before encoding a CRMF request, the user will want to set the appropriate
* attributes to build up the request. The supported attributes are:
*
* Attribute Enumeration Attribute Type What value means
* --------------------- -------------- ----------------
* SSM_FID_CRMFREQ_REGTOKEN String The value to encode as
* the registration token
* value for the request.
*
* SSM_FID_CRMFREQ_AUTHENTICATOR String The value to encode as
* authenticator control
* in the request.
*
* SSM_FID_DN String The RFC1485 formatted
* DN to include in the
* CRMF request.
*
* For information on how to properly set the attribute of a resource, refer
* to the comments for the functions CMT_SetNumericAttribute and
* CMT_SetStringAttribute.
*
* RETURN:
* A return value of CMTSuccess indicates a new CRMF resource was created by
* the psm server and has the resource ID placed at *reqID. Any other return
* value indicates an error and the value at *reqID should be ignored.
*/
CMTStatus
CMT_CreateNewCRMFRequest(PCMT_CONTROL control, CMUint32 keyPairID,
SSMKeyGenType keyGenType, CMUint32 *reqID);
/*
* FUNCTION: CMT_EncodeCRMFRequest
* ------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* crmfReqID
* An array of resource ID's for CRMF objects to be encoded.
* numRequests
* The length of the array crmfReqID that is passed in.
* der
* A pointer to a pre-allocated pointer for a char* where the library
* can place the final DER-encoding of the requests.
* NOTES
* This function will send a message to the psm server requesting that
* a number of CRMF requests be encoded into their appropriate DER
* representation. The DER that is sent back will be of the type
* CertReqMessages as define in the internet draft for CRMF. To look at the
* draft, visit the following URL:
* http://search.ietf.org/internet-drafts/internet-draft-ietf-pkix-crmf-01.txt
*
* RETURN:
* A return value of CMTSuccess indicates psm successfully encoded the requests
* and placed the base64 DER encoded request at *der. Any other return value
* indicates an error and the value at *der should be ignored.
*/
CMTStatus
CMT_EncodeCRMFRequest(PCMT_CONTROL control, CMUint32 *crmfReqID,
CMUint32 numRequests, char ** der);
/*
* FUNCTION: CMT_ProcessCMMFResponse
* ---------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* nickname
* The nickname that should be associated with the certificate
* contained in the CMMF Response.
* certRepString
* This is the base 64 encoded CertRepContent that issues a certificate.
* The psm server will decode the base 64 data and then parse the
* CertRepContent.
* doBackup
* A boolean value indicating whether or not psm should initiate the
* process of backing up the newly issued certificate into a PKCS-12
* file.
* clientContext
* Client supplied data pointer that is returned to the client during
* a UI event.
* NOTES:
* This function takes a CertRepContent as defined in the CMMF internet draft
* (http://search.ietf.org/internet-drafts/draft-ietf-pkix-cmmf-02.txt) and
* imports the certificate into the user's database. The certificate will have
* the string value of nickanme as it's nickname when added to the database
* unless another certificate with that same Distinguished Name (DN) already
* exists in the database, in which case the nickname of the certificate that
* already exists will be used. If the value passed in for doBackup is
* non-zero, then the psm server will initiate the process of backing up the
* certificate(s) that were just imported.
*
* RETURN:
* A return value of CMTSuccess indicates the certificate(s) were successfully
* added to the database. Any other return value means the certificate(s) could
* not be successfully added to the database.
*/
CMTStatus
CMT_ProcessCMMFResponse(PCMT_CONTROL control, char *nickname,
char *certRepString, CMBool doBackup,
void *clientContext);
/*
* FUNCTION: CMT_CreateResource
* ----------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* resType
* The enumeration representing the resource type to create.
* params
* A resource dependent binary string that will be sent to the psm
* server. Each resource will expect a binary string it defines.
* rsrcId
* A pointer to a pre-allocated chunk of memory where the library
* can place the resource ID of the newly created resource.
* errorCode
* A pointer to a pre-allocated chunk of memory where the library
* can place the errorCode returned by the psm server after creating
* the resource.
* NOTES:
* This function sends a message to the psm server requesting that a new
* resource be created. The params parameter depends on the type of resource
* being created. Below is a table detailing the format of the params for
* a given resource type. Only the resource types listed below can be created
* by calling this function.
*
* Resource Type constant Value for params
* ------------------------------ ----------------
* SSM_RESTYPE_KEYGEN_CONTEXT NULL
* SSM_RESTYPE_SECADVISOR_CONTEXT NULL
* SSM_RESTYPE_SIGNTEXT NULL
*
* RETURN
* A return value of CMTSuccess means the psm server received the request and
* processed the create resource create. If the value at *errorCode is zero,
* then the value at *rsrcId is the resource ID of the newly created resource.
* Otherwise, creating the new resource failed and *errorCode contains the
* error code returned by the psm server. ???What are the return values and
* what do they mean. Any other return value indicates there was an error
* in the communication with the psm server and the values at *rsrcId and
* *errorCode should be ignored.
*/
CMTStatus
CMT_CreateResource(PCMT_CONTROL control, SSMResourceType resType,
CMTItem *params, CMUint32 *rsrcId, CMUint32 *errorCode);
/*
* FUNCTION: CMT_SignText
* ----------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* resID
* The resource ID of an SSMSignTextResource.
* stringToSign
* The string that the psm server should sign.
* hostName
* The host name of the site that is requesting a string to be
* signed. This is used for displaying the UI that tells the user
* a web site has requested the use sign some text.
* caOption
* If the value is "auto" then psm will select the certificate
* to use for signing automatically.
* If the value is "ask" then psm will display a list of
* certificates for signing.
* numCAs
* The number of CA names included in the array caNames passed in as
* the last parameter to this function.
* caNames
* An array of CA Names to use for filtering the user certs to use
* for signing the text.
* NOTES
* This function will sign the text passed via the parameter stringToSign.
* The function will also cause the psm server to send some UI notifying the
* user that a site has requested the user sign some text. The hostName
* parameter is used in the UI to inform the user which site is requesting
* the signed text. The caOption is used to determine if the psm server
* should automatically select which personal cert to use in signing the
* text. The caNames array is ussed to narrow down the field of personal
* certs to use when signing the text. In other words, only personal certs
* trusted by the CA's passed in will be used.
*
* RETURN
* If the function returns CMTSuccess, that indicates the psm server
* successfully signed the text. The signed text can be retrieved by
* calling CMT_GetStringResource and passing in SSM_FID_SIGNTEXT_RESULT
* as the field ID. Any other return value indicates an error meaning the
* string was not signed successfully.
*/
CMTStatus
CMT_SignText(PCMT_CONTROL control, CMUint32 resID, char* stringToSign,
char* hostName, char *caOption, CMInt32 numCAs, char** caNames);
/*
* FUNCTION: CMT_ProcessChallengeResponse
* --------------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* challengeString
* The base64 encoded Challenge string received as the
* Proof-Of-Possession Challenge in response to CRMF request that
* specified Challenge-Reponse as the method for Proof-Of-Possession.
* responseString
* A pointer to pre-allocated char* where the library can place a
* copy of the bas64 encoded response to the challenge presented.
* NOTES
* This function takes the a challenge--that is encrypted with the public key
* of a certificate we created--and decrypts it with the private key we
* generated. The format of the challenge is as follows:
*
* Challenge ::= SEQUENCE {
* owf AlgorithmIdentifier OPTIONAL,
* -- MUST be present in the first Challenge; MAY be omitted in any
* -- subsequent Challenge in POPODecKeyChallContent (if omitted,
* -- then the owf used in the immediately preceding Challenge is
* -- to be used).
* witness OCTET STRING,
* -- the result of applying the one-way function (owf) to a
* -- randomly-generated INTEGER, A. [Note that a different
* -- INTEGER MUST be used for each Challenge.]
* sender GeneralName,
* -- the name of the sender.
* key OCTET STRING,
* -- the public key used to encrypt the challenge. This will allow
* -- the client to find the appropriate key to do the decryption.
* challenge OCTET STRING
* -- the encryption (under the public key for which the cert.
* -- request is being made) of Rand, where Rand is specified as
* -- Rand ::= SEQUENCE {
* -- int INTEGER,
* -- - the randomly-generated INTEGER A (above)
* -- senderHash OCTET STRING
* -- - the result of applying the one-way function (owf) to
* -- - the sender's general name
* -- }
* -- the size of "int" must be small enough such that "Rand" can be
* -- contained within a single PKCS #1 encryption block.
* }
* This challenge is based on the Challenge initially defined in the CMMF
* internet draft, but differs in that this structure includes the sender
* as part of the challenge along with the public key and includes a has
* of the sender in the encrypted Rand structure. The reason for including
* the key is to facilitate looking up the key that should be used to
* decipher the challenge. Including the hash of the sender in the encrypted
* Rand structure makes the challenge smaller and allows it to fit in
* one RSA block.
*
* The response is of the type POPODecKeyRespContent as defined in the CMMF
* internet draft.
*
* RETURN
* A return value of CMTSuccess indicates psm successfully parsed and processed
* the challenge and created a response. The base64 encoded response to the
* challenge is placed at *responseString. Any other return value indicates
* an error and the value at *responseString should be ignored.
*/
CMTStatus
CMT_ProcessChallengeResponse(PCMT_CONTROL control, char *challengeString,
char **responseString);
/*
* FUNCTION: CMT_GetLocalizedString
* --------------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* whichString
* The enumerated value corresponding to the localized string to
* retrieve from the psm server
* localizedString
* A pointer to a pre-allocated char* where the library can place
* copy of the localized string retrieved from the psm server.
* NOTES
* This function retrieves a localized string from the psm server. These
* strings are useful for strings that aren't localized in the client
* making use of the psm server, but need to be displayed by the user. Look
* in protocol.h for the enumerations of the localized strings that can
* be fetched from psm via this method.
*
* RETURN
* A return value of CMTSuccess indicates the localized string was retrieved
* successfully and the localized value is located at *localizedString. Any
* other return value indicates an error and the value at *localizedString
* should be ignored.
*/
CMTStatus
CMT_GetLocalizedString(PCMT_CONTROL control,
SSMLocalizedString whichString,
char **localizedString);
/*
* FUNCTION: CMT_DeleteModule
* --------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* moduleName
* The name of the PKCS11 module to delete.
* moduleType
* A pointer to a pre-allocated integer where the library can place
* a value that tells what the type of module was deleted.
* NOTES
* This function will send a message to the psm server requesting the server
* delete a PKCS-11 module stored in psm's security module database. moduleName
* is the value passed in as moduleName when the module was added to the
* security module database of psm.
* The values that may be returned by psm for moduleType are:
*
* 0 The module was an external module developped by a third party
* that was added to the psm security module.
*
* 1 The module deleted was the internal PKCS-11 module that comes
* built in with the psm server.
*
* 2 The module that was deleted was the FIPS internal module.
*
* RETURN
* A return value of CMTSuccess indicates the security module was successfully
* delete from the psm security module database and the value at *moduleType
* will tell what type of module was deleted.
* Any other return value indicates an error and the value at *moduleType
* should be ignored.
*/
CMTStatus
CMT_DeleteModule(PCMT_CONTROL control,
char *moduleName,
int *moduleType);
/*
* FUNCTION: CMT_AddNewModule
* --------------------------
* INPUTS:
* control
* The Control Connection that has already established a connection
* with the psm server.
* moduleName
* The name to be associated with the module once it is added to
* the psm security module database.
* libraryPath
* The path to the library to be loaded. The library should be
* loadable at run-time.
* pubMechFlags
* A bit vector indicating all cryptographic mechanisms that should
* be turned on by default. This module will become the default
* handler for the mechanisms that are set by this bit vector.
* pubCipherFlags
* A bit vector indicating all SSL or S/MIME cipher functions
* supported by the module. Most modules will pas in 0x0 for this
* parameter.
* NOTES:
* This function sends a message to the psm server and requests the .so
* file on UNIX or .dll file on Windows be loaded as a PKCS11 module and
* be stored in the psm security module database. The module will be stored
* with the name moduleName that is passed in and will always expect the
* library to live at the path passed in via the parameter libraryPath.
* The pubMechFlags tell the psm server how this module should be used.
* Valid values are the #define constants defined at the beginning of
* this file.
*
* RETURN
* A return value of CMTSuccess indicates the module was successfully loaded
* and placed in the security module database of psm. Any other return value
* indicates an error and means the module was not loaded successfully and
* not stored in the psm server's security module database.
*/
CMTStatus
CMT_AddNewModule(PCMT_CONTROL control,
char *moduleName,
char *libraryPath,
unsigned long pubMechFlags,
unsigned long pubCipherFlags);
CMT_END_EXTERN_C
#endif /*_CMTJS_H_*/

View File

@@ -1,75 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "cmtmac.h"
#include "macsocket.h"
#include "stdlib.h"
#ifndef XP_MAC
#error Link with the builtin strdup() on your platform.
#endif
static void
my_strcpy(char *dest, const char *source)
{
char *i = dest;
const char *j = source;
while(*j)
*i++ = *j++;
*i = '\0';
}
static int
my_strlen(const char *str)
{
const char *c = str;
int i = 0;
while(*c++ != '\0')
i++;
return i;
}
char * strdup(const char *oldstr)
{
/* used to keep the mac client library from referring to strdup elsewhere */
char *newstr;
newstr = (char *) malloc(my_strlen(oldstr)+1);
if (newstr)
my_strcpy(newstr, oldstr);
return newstr;
}

View File

@@ -1,40 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef __CMTMAC_H__
#define __CMTMAC_H__
char * strdup(const char *str);
#endif

View File

@@ -1,119 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/************************************************************************
* Code to handle password requests from the the PSM module.
*
************************************************************************
*/
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
void CMT_SetAppFreeCallback(PCMT_CONTROL control,
applicationFreeCallback_fn f)
{
control->userFuncs.userFree = f;
}
void CMT_ServicePasswordRequest(PCMT_CONTROL cm_control, CMTItem * requestData)
{
CMTItem response = {0, NULL, 0};
PasswordRequest request;
PasswordReply reply;
void * clientContext;
/********************************************
* What we trying to do here:
* 1) Throw up a dialog box and request a password.
* 2) Create a message and send it to the PSM module.
********************************************
*/
/* Decode the request */
if (CMT_DecodeMessage(PasswordRequestTemplate, &request, requestData) != CMTSuccess) {
goto loser;
}
/* Copy the client context to a pointer */
clientContext = CMT_CopyItemToPtr(request.clientContext);
if (cm_control->userFuncs.promptCallback == NULL) {
goto loser;
}
reply.passwd =
cm_control->userFuncs.promptCallback(cm_control->userFuncs.promptArg,
request.prompt, clientContext, 1);
reply.tokenID = request.tokenKey;
if (!reply.passwd) {
/* the user cancelled the prompt or other errors occurred */
reply.result = -1;
}
else {
/* note that this includes an empty string (zero length password) */
reply.result = 0;
}
/* Encode the reply */
if (CMT_EncodeMessage(PasswordReplyTemplate, &response, &reply) != CMTSuccess) {
goto loser;
}
/* Set the message response type */
response.type = SSM_EVENT_MESSAGE | SSM_AUTH_EVENT;
CMT_TransmitMessage(cm_control, &response);
goto done;
loser:
/* something has gone wrong */
done:
/*clean up anyway */
/* We can't just free up memory allocated by the host
application because the versions of free may not match up.
When you run the plug-in with an optimized older browser,
you'll see tons of Asserts (why they still have asserts in an
optimized build is a different question, but without them
I wouldn't have figured out this problem) about a pointer not
being a valid heap pointer and eventually crash. This was
the offending free line.
So we need to call a function within the browser that
calls the free linked in with it. js_free is
such a function. But this is extremely ugly.
*/
if (reply.passwd)
cm_control->userFuncs.userFree(reply.passwd);
if (request.prompt)
free(request.prompt);
return;
}

View File

@@ -1,636 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#else
#ifdef XP_MAC
#include "macsocket.h"
#else /* Windows */
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include <errno.h>
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "rsrcids.h"
typedef struct _CMTP7Private {
CMTPrivate priv;
CMTP7ContentCallback cb;
void *cb_arg;
} CMTP7Private;
CMTStatus CMT_PKCS7DecoderStart(PCMT_CONTROL control, void* clientContext, CMUint32 * connectionID, CMInt32 * result,
CMTP7ContentCallback cb, void *cb_arg)
{
CMTItem message;
CMTStatus rv;
CMTP7Private *priv=NULL;
SingleItemMessage request;
DataConnectionReply reply;
/* Check passed in parameters */
if (!control) {
goto loser;
}
request.item = CMT_CopyPtrToItem(clientContext);
/* Encode message */
if (CMT_EncodeMessage(SingleItemMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION | SSM_PKCS7DECODE_STREAM;
/* Send the message. */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION | SSM_PKCS7DECODE_STREAM)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
CMTSocket sock;
priv = (CMTP7Private *)malloc(sizeof(CMTP7Private));
if (priv == NULL)
goto loser;
priv->priv.dest = (CMTReclaimFunc) free;
priv->cb = cb;
priv->cb_arg = cb_arg;
sock = control->sockFuncs.socket(0);
if (sock == NULL) {
goto loser;
}
if (control->sockFuncs.connect(sock, (short)reply.port,
NULL) != CMTSuccess) {
goto loser;
}
if (control->sockFuncs.send(sock, control->nonce.data,
control->nonce.len) != control->nonce.len){
goto loser;
}
/* Save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID)
!= CMTSuccess) {
goto loser;
}
*connectionID = reply.connID;
rv = CMT_SetPrivate(control, reply.connID, &priv->priv);
if (rv != CMTSuccess)
goto loser;
return CMTSuccess;
}
loser:
if (priv) {
free(priv);
}
*result = reply.result;
return CMTFailure;
}
CMTStatus CMT_PKCS7DecoderUpdate(PCMT_CONTROL control, CMUint32 connectionID, const char * buf, CMUint32 len)
{
CMUint32 sent;
CMTP7Private *priv;
unsigned long nbytes;
char read_buf[128];
CMTSocket sock, ctrlsock, selSock, sockArr[2];
/* Do some parameter checking */
if (!control || !buf) {
goto loser;
}
/* Get the data socket */
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
priv = (CMTP7Private *)CMT_GetPrivate(control, connectionID);
if (priv == NULL)
goto loser;
/* Write the data to the socket */
sent = CMT_WriteThisMany(control, sock, (void*)buf, len);
if (sent != len) {
goto loser;
}
ctrlsock = control->sock;
sockArr[0] = ctrlsock;
sockArr[1] = sock;
while ((selSock = control->sockFuncs.select(sockArr,2,1)))
{
if (selSock == ctrlsock) {
CMT_ProcessEvent(control);
} else {
nbytes = control->sockFuncs.recv(sock, read_buf, sizeof(read_buf));
if (nbytes == -1) {
goto loser;
}
if (nbytes == 0) {
break;
}
priv->cb(priv->cb_arg, read_buf, nbytes);
}
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7DecoderFinish(PCMT_CONTROL control, CMUint32 connectionID,
CMUint32 * resourceID)
{
CMTP7Private *priv;
long nbytes;
char buf[128];
CMTSocket sock, ctrlsock, selSock, sockArr[2];
/* Do some parameter checking */
if (!control) {
goto loser;
}
priv = (CMTP7Private *)CMT_GetPrivate(control, connectionID);
if (priv == NULL)
goto loser;
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
ctrlsock = control->sock;
/* drain socket before we close it */
control->sockFuncs.shutdown(sock);
sockArr[0] = sock;
sockArr[1] = ctrlsock;
/* Let's see if doing a poll first gets rid of a weird bug where we
* lock up the client.
*/
#ifndef XP_MAC
if (control->sockFuncs.select(sockArr,2,1) != NULL)
#endif
{
while (1) {
selSock = control->sockFuncs.select(sockArr,2,0);
if (selSock == ctrlsock) {
CMT_ProcessEvent(control);
} else if (selSock == sock) {
nbytes = control->sockFuncs.recv(sock, buf, sizeof(buf));
if (nbytes < 0) {
goto loser;
} else if (nbytes == 0) {
break;
}
priv->cb(priv->cb_arg, buf, nbytes);
}
}
}
if (CMT_CloseDataConnection(control, connectionID) == CMTFailure) {
goto loser;
}
/* Get the PKCS7 content info */
if (CMT_GetRIDAttribute(control, connectionID, SSM_FID_P7CONN_CONTENT_INFO,
resourceID) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
if (control) {
CMT_CloseDataConnection(control, connectionID);
}
return CMTFailure;
}
CMTStatus CMT_PKCS7DestroyContentInfo(PCMT_CONTROL control, CMUint32 resourceID)
{
if (!control) {
goto loser;
}
/* Delete the resource */
if (CMT_DestroyResource(control, resourceID, SSM_FID_P7CONN_CONTENT_INFO) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7VerifyDetachedSignature(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 certUsage, CMUint32 hashAlgID, CMUint32 keepCerts, CMTItem* digest, CMInt32 * result)
{
CMTItem message;
VerifyDetachedSigRequest request;
SingleNumMessage reply;
/* Do some parameter checking */
if (!control || !digest || !result) {
goto loser;
}
/* Set the request */
request.pkcs7ContentID = resourceID;
request.certUsage = certUsage;
request.hashAlgID = hashAlgID;
request.keepCert = (CMBool) keepCerts;
request.hash = *digest;
/* Encode the request */
if (CMT_EncodeMessage(VerifyDetachedSigRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_OBJECT_SIGNING | SSM_VERIFY_DETACHED_SIG;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_OBJECT_SIGNING |SSM_VERIFY_DETACHED_SIG)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*result = reply.value;
return CMTSuccess;
loser:
*result = reply.value;
return CMTFailure;
}
CMTStatus CMT_PKCS7VerifySignature(PCMT_CONTROL control, CMUint32 pubKeyAlgID,
CMTItem *pubKeyParams, CMTItem *signerPubKey,
CMTItem *computedHash, CMTItem *signature,
CMInt32 *result)
{
return CMTFailure;
}
CMTStatus CMT_CreateSigned(PCMT_CONTROL control, CMUint32 scertRID,
CMUint32 ecertRID, CMUint32 dig_alg,
CMTItem *digest, CMUint32 *ciRID, CMInt32 *errCode)
{
CMTItem message;
CreateSignedRequest request;
CreateContentInfoReply reply;
/* Do some parameter checking */
if (!control || !scertRID || !ecertRID || !digest || !ciRID) {
goto loser;
}
/* Set the request */
request.scertRID = scertRID;
request.ecertRID = ecertRID;
request.dig_alg = dig_alg;
request.digest = *digest;
/* Encode the request */
if (CMT_EncodeMessage(CreateSignedRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_OBJECT_SIGNING | SSM_CREATE_SIGNED;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_OBJECT_SIGNING | SSM_CREATE_SIGNED)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(CreateContentInfoReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*ciRID = reply.ciRID;
if (reply.result == 0) {
return CMTSuccess;
}
loser:
if (CMT_DecodeMessage(CreateContentInfoReplyTemplate, &reply, &message) == CMTSuccess) {
*errCode = reply.errorCode;
} else {
*errCode = 0;
}
return CMTFailure;
}
CMTStatus CMT_CreateEncrypted(PCMT_CONTROL control, CMUint32 scertRID,
CMUint32 *rcertRIDs, CMUint32 *ciRID)
{
CMTItem message;
CMInt32 nrcerts;
CreateEncryptedRequest request;
CreateContentInfoReply reply;
/* Do some parameter checking */
if (!control || !scertRID || !rcertRIDs || !ciRID) {
goto loser;
}
/* Calculate the number of certs */
for (nrcerts =0; rcertRIDs[nrcerts] != 0; nrcerts++) {
/* Nothing */
;
}
/* Set up the request */
request.scertRID = scertRID;
request.nrcerts = nrcerts;
request.rcertRIDs = (long *) rcertRIDs;
/* Encode the request */
if (CMT_EncodeMessage(CreateEncryptedRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_OBJECT_SIGNING | SSM_CREATE_ENCRYPTED;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message response type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_OBJECT_SIGNING | SSM_CREATE_ENCRYPTED)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(CreateContentInfoReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*ciRID = reply.ciRID;
if (reply.result == 0) {
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7EncoderStart(PCMT_CONTROL control, CMUint32 ciRID,
CMUint32 *connectionID, CMTP7ContentCallback cb,
void *cb_arg)
{
CMTItem message;
CMTStatus rv;
CMTP7Private *priv;
PKCS7DataConnectionRequest request;
DataConnectionReply reply;
/* Check passed in parameters */
if (!control || !ciRID) {
goto loser;
}
/* Set up the request */
request.resID = ciRID;
request.clientContext.len = 0;
request.clientContext.data = NULL;
/* Encode the request */
if (CMT_EncodeMessage(PKCS7DataConnectionRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION | SSM_PKCS7ENCODE_STREAM;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION | SSM_PKCS7ENCODE_STREAM)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
CMTSocket sock;
priv = (CMTP7Private *)malloc(sizeof(CMTP7Private));
if (priv == NULL)
goto loser;
priv->priv.dest = (CMTReclaimFunc) free;
priv->cb = cb;
priv->cb_arg = cb_arg;
sock = control->sockFuncs.socket(0);
if (sock == NULL) {
goto loser;
}
if (control->sockFuncs.connect(sock, (short)reply.port,
NULL) != CMTSuccess) {
goto loser;
}
if (control->sockFuncs.send(sock, control->nonce.data,
control->nonce.len) != control->nonce.len) {
goto loser;
}
/* Save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID)
!= CMTSuccess) {
goto loser;
}
*connectionID = reply.connID;
rv = CMT_SetPrivate(control, reply.connID, &priv->priv);
if (rv != CMTSuccess)
goto loser;
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7EncoderUpdate(PCMT_CONTROL control, CMUint32 connectionID,
const char *buf, CMUint32 len)
{
CMUint32 sent;
CMTP7Private *priv;
unsigned long nbytes;
char read_buf[128];
CMTSocket sock, ctrlsock, sockArr[2], selSock;
/* Do some parameter checking */
if (!control || !connectionID || !buf) {
goto loser;
}
/* Get the data socket */
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
priv = (CMTP7Private *)CMT_GetPrivate(control, connectionID);
if (priv == NULL)
goto loser;
/* Write the data to the socket */
sent = CMT_WriteThisMany(control, sock, (void*)buf, len);
if (sent != len) {
goto loser;
}
ctrlsock = control->sock;
sockArr[0] = ctrlsock;
sockArr[1] = sock;
while ((selSock = control->sockFuncs.select(sockArr, 2, 1)) != NULL)
{
if (selSock == ctrlsock) {
CMT_ProcessEvent(control);
} else {
nbytes = control->sockFuncs.recv(sock, read_buf, sizeof(read_buf));
if (nbytes == -1) {
goto loser;
} else if (nbytes == 0) {
break;
} else {
priv->cb(priv->cb_arg, read_buf, nbytes);
}
}
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_PKCS7EncoderFinish(PCMT_CONTROL control, CMUint32 connectionID)
{
CMTP7Private *priv;
unsigned long nbytes;
char buf[128];
CMTSocket sock, ctrlsock, sockArr[2], selSock;
/* Do some parameter checking */
if (!control) {
goto loser;
}
priv = (CMTP7Private *)CMT_GetPrivate(control, connectionID);
if (priv == NULL)
goto loser;
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
ctrlsock = control->sock;
sockArr[0] = ctrlsock;
sockArr[1] = sock;
control->sockFuncs.shutdown(sock);
while (1) {
selSock = control->sockFuncs.select(sockArr, 2, 0);
if (selSock == ctrlsock) {
CMT_ProcessEvent(control);
} else if (selSock == sock) {
nbytes = control->sockFuncs.recv(sock, buf, sizeof(buf));
if (nbytes < 0) {
goto loser;
} else if (nbytes == 0) {
break;
} else {
priv->cb(priv->cb_arg, buf, nbytes);
}
}
}
if (CMT_CloseDataConnection(control, connectionID) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
if (control) {
CMT_CloseDataConnection(control, connectionID);
}
return CMTFailure;
}

View File

@@ -1,479 +0,0 @@
/* -*- mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef XP_MAC
#include "macsocket.h"
#else
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include <errno.h>
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include <string.h>
CMTStatus CMT_GetNumericAttribute(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 fieldID, CMInt32 *value)
{
CMTItem message;
GetAttribRequest request;
GetAttribReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.resID = resourceID;
request.fieldID = fieldID;
/* Encode the request */
if (CMT_EncodeMessage(GetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_NUMERIC_ATTRIBUTE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_NUMERIC_ATTRIBUTE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(GetAttribReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
*value = reply.value.u.numeric;
/* Success */
if (reply.result == 0) {
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_SetNumericAttribute(PCMT_CONTROL control, CMUint32 resourceID,
CMUint32 fieldID, CMInt32 value)
{
CMTItem message;
SetAttribRequest request;
if (!control) {
goto loser;
}
/* Set the request */
request.resID = resourceID;
request.fieldID = fieldID;
request.value.type = SSM_NUMERIC_ATTRIBUTE;
request.value.u.numeric = value;
/* Encode the message */
if (CMT_EncodeMessage(SetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION |
SSM_SET_ATTRIBUTE | SSM_NUMERIC_ATTRIBUTE;
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_SET_ATTRIBUTE | SSM_NUMERIC_ATTRIBUTE)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus
CMT_PadStringValue(CMTItem *dest, CMTItem src)
{
dest->data = NewArray(unsigned char, src.len+1);
if (dest->data == NULL) {
return CMTFailure;
}
memcpy(dest->data, src.data, src.len);
dest->data[src.len] = '\0';
dest->len = src.len;
free(src.data);
return CMTSuccess;
}
CMTStatus CMT_GetStringAttribute(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 fieldID, CMTItem *value)
{
CMTItem message;
GetAttribRequest request;
GetAttribReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.resID = resourceID;
request.fieldID = fieldID;
/* Encode the request */
if (CMT_EncodeMessage(GetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_STRING_ATTRIBUTE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_STRING_ATTRIBUTE)) {
goto loser;
}
/* Decode the response */
if (CMT_DecodeMessage(GetAttribReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
return CMT_PadStringValue(value, reply.value.u.string);
}
loser:
return CMTFailure;
}
CMTStatus
CMT_SetStringAttribute(PCMT_CONTROL control, CMUint32 resourceID,
CMUint32 fieldID, CMTItem *value)
{
CMTItem message;
SetAttribRequest request;
if (!control) {
goto loser;
}
/* Set up the request */
request.resID = resourceID;
request.fieldID = fieldID;
request.value.type = SSM_STRING_ATTRIBUTE;
request.value.u.string = *value;
/* Encode the request */
if (CMT_EncodeMessage(SetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION |
SSM_SET_ATTRIBUTE | SSM_STRING_ATTRIBUTE;
/* Send the message */
if (CMT_SendMessage(control, &message) != CMTSuccess) {
goto loser;
}
/* Validate the message request type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_SET_ATTRIBUTE | SSM_STRING_ATTRIBUTE)) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_DuplicateResource(PCMT_CONTROL control, CMUint32 resourceID,
CMUint32 *newResID)
{
CMTItem message;
SingleNumMessage request;
DupResourceReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.value = resourceID;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_DUPLICATE_RESOURCE;
/* Send the mesage */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_DUPLICATE_RESOURCE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(DupResourceReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
*newResID = reply.resID;
return CMTSuccess;
}
loser:
*newResID = 0;
return CMTFailure;
}
CMTStatus CMT_DestroyResource(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 resourceType)
{
CMTItem message;
DestroyResourceRequest request;
SingleNumMessage reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.resID = resourceID;
request.resType = resourceType;
/* Encode the message */
if (CMT_EncodeMessage(DestroyResourceRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_DESTROY_RESOURCE;
/* Send the message */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_DESTROY_RESOURCE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.value == 0) {
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_PickleResource(PCMT_CONTROL control, CMUint32 resourceID, CMTItem * pickledResource)
{
CMTItem message;
SingleNumMessage request;
PickleResourceReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.value = resourceID;
/* Encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_CONSERVE_RESOURCE | SSM_PICKLE_RESOURCE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_CONSERVE_RESOURCE | SSM_PICKLE_RESOURCE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(PickleResourceReplyTemplate, &reply,&message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
*pickledResource = reply.blob;
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_UnpickleResource(PCMT_CONTROL control, CMUint32 resourceType, CMTItem pickledResource, CMUint32 * resourceID)
{
CMTItem message;
UnpickleResourceRequest request;
UnpickleResourceReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set up the request */
request.resourceType = resourceType;
request.resourceData = pickledResource;
/* Encode the request */
if (CMT_EncodeMessage(UnpickleResourceRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_CONSERVE_RESOURCE | SSM_UNPICKLE_RESOURCE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_CONSERVE_RESOURCE | SSM_UNPICKLE_RESOURCE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(UnpickleResourceReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
*resourceID = reply.resID;
return CMTSuccess;
}
loser:
*resourceID = 0;
return CMTFailure;
}
CMTStatus CMT_GetRIDAttribute(PCMT_CONTROL control, CMUint32 resourceID, CMUint32 fieldID, CMUint32 *value)
{
CMTItem message;
GetAttribRequest request;
GetAttribReply reply;
/* Do some parameter checking */
if (!control) {
goto loser;
}
/* Set the request */
request.resID = resourceID;
request.fieldID = fieldID;
/* Encode the message */
if (CMT_EncodeMessage(GetAttribRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_RID_ATTRIBUTE;
/* Send the mesage and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message response type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION | SSM_GET_ATTRIBUTE | SSM_RID_ATTRIBUTE)) {
goto loser;
}
/* Decode the reply */
if (CMT_DecodeMessage(GetAttribReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
*value = reply.value.u.rid;
return CMTSuccess;
}
loser:
return CMTFailure;
}

View File

@@ -1,270 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/*
cmtrng.c -- Support for PSM random number generator and the seeding
thereof with data from the client.
Created by mwelch 1999 Oct 21
*/
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "rsrcids.h"
#include <string.h>
CMTStatus
CMT_EnsureInitializedRNGBuf(PCMT_CONTROL control)
{
if (control->rng.outBuf == NULL)
{
control->rng.outBuf = (char *) calloc(RNG_OUT_BUFFER_LEN, sizeof(char));
if (control->rng.outBuf == NULL)
goto loser;
control->rng.validOutBytes = 0;
control->rng.out_cur = control->rng.outBuf;
control->rng.out_end = control->rng.out_cur + RNG_OUT_BUFFER_LEN;
control->rng.inBuf = (char *) calloc(RNG_IN_BUFFER_LEN, sizeof(char));
if (control->rng.outBuf == NULL)
goto loser;
}
return CMTSuccess;
loser:
if (control->rng.outBuf != NULL)
{
free(control->rng.outBuf);
control->rng.outBuf = NULL;
}
if (control->rng.inBuf != NULL)
{
free(control->rng.inBuf);
control->rng.inBuf = NULL;
}
return CMTFailure;
}
size_t
CMT_RequestPSMRandomData(PCMT_CONTROL control,
void *buf, CMUint32 maxbytes)
{
SingleNumMessage req;
SingleItemMessage reply;
CMTItem message;
size_t rv = 0;
/* Parameter checking */
if (!control || !buf || (maxbytes == 0))
goto loser;
/* Initialization. */
memset(&reply, 0, sizeof(SingleItemMessage));
/* Ask PSM for the data. */
req.value = maxbytes;
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &req) != CMTSuccess)
goto loser;
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_MISC_ACTION | SSM_MISC_GET_RNG_DATA;
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure)
goto loser;
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_MISC_ACTION | SSM_MISC_GET_RNG_DATA))
goto loser;
/* Decode message */
if (CMT_DecodeMessage(SingleItemMessageTemplate, &reply, &message) != CMTSuccess)
goto loser;
/* Success - fill the return buf with what we got */
if (reply.item.len > maxbytes)
reply.item.len = maxbytes;
memcpy(buf, reply.item.data, reply.item.len);
rv = reply.item.len;
loser:
if (reply.item.data)
free(reply.item.data);
if (message.data)
free(message.data);
return rv;
}
size_t
CMT_GenerateRandomBytes(PCMT_CONTROL control,
void *buf, CMUint32 maxbytes)
{
CMUint32 remaining = maxbytes;
CMT_RNGState *rng = &(control->rng);
char *walk = (char *) buf;
/* Is there already enough in the incoming cache? */
while(remaining > rng->validInBytes)
{
/* Get what we have on hand. */
memcpy(walk, rng->in_cur, rng->validInBytes);
walk += rng->validInBytes;
remaining -= rng->validInBytes;
/* Request a buffer from PSM. */
rng->validInBytes = CMT_RequestPSMRandomData(control,
rng->inBuf,
RNG_IN_BUFFER_LEN);
if (rng->validInBytes == 0)
return (maxbytes - remaining); /* call failed */
rng->in_cur = rng->inBuf;
}
if (remaining > 0)
{
memcpy(walk, rng->in_cur, remaining);
rng->in_cur += remaining;
rng->validInBytes -= remaining;
}
return maxbytes;
}
void
cmt_rng_xor(void *dstBuf, void *srcBuf, int len)
{
unsigned char *s = (unsigned char*) srcBuf;
unsigned char *d = (unsigned char*) dstBuf;
unsigned char tmp;
int i;
for(i=0; i<len; i++, s++, d++)
{
tmp = *d;
/* I wish C had circular shift operators. So do others on the team. */
tmp = ((tmp << 1) | (tmp >> 7));
*d = tmp ^ *s;
}
}
CMTStatus
CMT_RandomUpdate(PCMT_CONTROL control, void *data, size_t numbytes)
{
size_t dataLeft = numbytes, cacheLeft;
char *walk = (char *) data;
if (CMT_EnsureInitializedRNGBuf(control) != CMTSuccess)
goto loser;
/* If we have more than what the buffer can handle, wrap around. */
cacheLeft = (control->rng.out_end - control->rng.out_cur);
while (dataLeft >= cacheLeft)
{
cmt_rng_xor(control->rng.out_cur, walk, cacheLeft);
walk += cacheLeft;
dataLeft -= cacheLeft;
control->rng.out_cur = control->rng.outBuf;
/* Max out used space */
control->rng.validOutBytes = cacheLeft = RNG_OUT_BUFFER_LEN;
}
/*
We now have less seed data available than we do space in the buf.
Write what we have and update validOutBytes if we're not looping already.
*/
cmt_rng_xor(control->rng.out_cur, walk, dataLeft);
control->rng.out_cur += dataLeft;
if (control->rng.validOutBytes < RNG_OUT_BUFFER_LEN)
control->rng.validOutBytes += dataLeft;
return CMTSuccess;
loser:
return CMTFailure;
}
size_t
CMT_GetNoise(PCMT_CONTROL control, void *buf, CMUint32 maxbytes)
{
/* ### mwelch - GetNoise and GenerateRandomBytes can be the
same function now, because presumably the RNG is being
seeded with environmental noise on the PSM end before we
make any of these requests */
return CMT_GenerateRandomBytes(control, buf, maxbytes);
}
CMTStatus
CMT_FlushPendingRandomData(PCMT_CONTROL control)
{
CMTItem message;
memset(&message, 0, sizeof(CMTItem));
if (CMT_EnsureInitializedRNGBuf(control) != CMTSuccess)
return CMTFailure; /* couldn't initialize RNG buffer */
if (control->rng.validOutBytes == 0)
return CMTSuccess; /* no random data available == we're flushed */
/* We have random data available. Send this to PSM.
We're sending an event, so no reply is needed. */
message.type = SSM_EVENT_MESSAGE
| SSM_MISC_ACTION
| SSM_MISC_PUT_RNG_DATA;
message.len = control->rng.validOutBytes;
message.data = (unsigned char *) calloc(message.len, sizeof(char));
if (!message.data)
goto loser;
memcpy(message.data, control->rng.outBuf, message.len);
if (CMT_TransmitMessage(control, &message) == CMTFailure)
goto loser;
/* Clear the RNG ring buffer, we've used that data */
control->rng.out_cur = control->rng.outBuf;
control->rng.validOutBytes = 0;
/* zero the buffer, because we XOR in new data */
memset(control->rng.outBuf, 0, RNG_OUT_BUFFER_LEN);
goto done;
loser:
if (message.data)
free(message.data);
return CMTFailure;
done:
return CMTSuccess;
}

View File

@@ -1,237 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/*
cmtsdr.c -- Support for the Secret Decoder Ring, which provides
encryption and decryption using stored keys.
Created by thayes 18 April 2000
*/
#include "stddef.h"
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "protocolshr.h"
#include "rsrcids.h"
#include <string.h>
#undef PROCESS_LOCALLY
/* Encryption result - contains the key id and the resulting data */
/* An empty key id indicates that NO encryption was performed */
typedef struct EncryptionResult
{
CMTItem keyid;
CMTItem data;
} EncryptionResult;
/* Constants for testing */
static const char *kPrefix = "Encrypted:";
static CMTItem
CMT_CopyDataToItem(const unsigned char *data, CMUint32 len)
{
CMTItem item;
item.data = (unsigned char*) calloc(len, 1);
item.len = len;
memcpy(item.data, data, len);
return item;
}
static CMTStatus
tmp_SendMessage(PCMT_CONTROL control, CMTItem *message)
{
#ifndef PROCESS_LOCALLY
return CMT_SendMessage(control, message);
#else
if (message->type == SSM_SDR_ENCRYPT_REQUEST)
return CMT_DoEncryptionRequest(message);
else if (message->type == SSM_SDR_DECRYPT_REQUEST)
return CMT_DoDecryptionRequest(message);
return CMTFailure;
#endif
}
/* End test code */
CMTStatus
CMT_SDREncrypt(PCMT_CONTROL control, void *ctx,
const unsigned char *key, CMUint32 keyLen,
const unsigned char *data, CMUint32 dataLen,
unsigned char **result, CMUint32 *resultLen)
{
CMTStatus rv = CMTSuccess;
CMTItem message;
EncryptRequestMessage request;
SingleItemMessage reply;
/* Fill in the request */
request.keyid = CMT_CopyDataToItem(key, keyLen);
request.data = CMT_CopyDataToItem(data, dataLen);
request.ctx = CMT_CopyPtrToItem(ctx);
reply.item.data = 0;
reply.item.len = 0;
message.data = 0;
message.len = 0;
/* Encode */
rv = CMT_EncodeMessage(EncryptRequestTemplate, &message, &request);
if (rv != CMTSuccess) {
goto loser;
}
message.type = SSM_SDR_ENCRYPT_REQUEST;
/* Send */
/* if (CMT_SendMessage(control, &message) != CMTSuccess) goto loser; */
rv = tmp_SendMessage(control, &message);
if (rv != CMTSuccess) goto loser;
if (message.type != SSM_SDR_ENCRYPT_REPLY) { rv = CMTFailure; goto loser; }
rv = CMT_DecodeMessage(SingleItemMessageTemplate, &reply, &message);
if (rv != CMTSuccess)
goto loser;
*result = reply.item.data;
*resultLen = reply.item.len;
reply.item.data = 0;
loser:
if (message.data) free(message.data);
if (request.keyid.data) free(request.keyid.data);
if (request.data.data) free(request.data.data);
if (request.ctx.data) free(request.ctx.data);
if (reply.item.data) free(reply.item.data);
return rv; /* need return value */
}
CMTStatus
CMT_SDRDecrypt(PCMT_CONTROL control, void *ctx,
const unsigned char *data, CMUint32 dataLen,
unsigned char **result, CMUint32 *resultLen)
{
CMTStatus rv;
CMTItem message;
DecryptRequestMessage request;
SingleItemMessage reply;
/* Fill in the request */
request.data = CMT_CopyDataToItem(data, dataLen);
request.ctx = CMT_CopyPtrToItem(ctx);
reply.item.data = 0;
reply.item.len = 0;
message.data = 0;
message.len = 0;
/* Encode */
rv = CMT_EncodeMessage(DecryptRequestTemplate, &message, &request);
if (rv != CMTSuccess) {
goto loser;
}
message.type = SSM_SDR_DECRYPT_REQUEST;
/* Send */
/* if (CMT_SendMessage(control, &message) != CMTSuccess) goto loser; */
rv = tmp_SendMessage(control, &message);
if (rv != CMTSuccess) goto loser;
if (message.type != SSM_SDR_DECRYPT_REPLY) { rv = CMTFailure; goto loser; }
rv = CMT_DecodeMessage(SingleItemMessageTemplate, &reply, &message);
if (rv != CMTSuccess)
goto loser;
*result = reply.item.data;
*resultLen = reply.item.len;
reply.item.data = 0;
loser:
if (message.data) free(message.data);
if (request.data.data) free(request.data.data);
if (request.ctx.data) free(request.ctx.data);
if (reply.item.data) free(reply.item.data);
return rv; /* need return value */
}
CMTStatus
CMT_SDRChangePassword(PCMT_CONTROL control, void *ctx)
{
CMTStatus rv = CMTSuccess;
CMTItem message;
SingleItemMessage request;
SingleNumMessage reply;
/* Fill in the request */
request.item = CMT_CopyPtrToItem(ctx);
message.data = 0;
message.len = 0;
/* Encode */
rv = CMT_EncodeMessage(SingleItemMessageTemplate, &message, &request);
if (rv != CMTSuccess) {
goto loser;
}
message.type = (SSM_REQUEST_MESSAGE|SSM_MISC_ACTION|SSM_MISC_UI|SSM_UI_CHANGE_PASSWORD);
/* Send */
rv = CMT_SendMessage(control, &message);
if (rv != CMTSuccess) goto loser;
if (message.type !=
(SSM_REPLY_OK_MESSAGE|SSM_MISC_ACTION|SSM_MISC_UI|SSM_UI_CHANGE_PASSWORD)) {
rv = CMTFailure;
goto loser;
}
rv = CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message);
if (rv != CMTSuccess)
goto loser;
loser:
if (request.item.data) free(request.item.data);
if (message.data) free(message.data);
return rv; /* need return value */
}

View File

@@ -1,467 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef XP_MAC
#else /* windows */
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include <errno.h>
#include "cmtcmn.h"
#include "cmtutils.h"
#include "messages.h"
#include "rsrcids.h"
CMTStatus CMT_OpenSSLConnection(PCMT_CONTROL control, CMTSocket sock,
SSMSSLConnectionRequestType flags,
CMUint32 port, char * hostIP,
char * hostName, CMBool forceHandshake, void* clientContext)
{
CMTItem message;
SSLDataConnectionRequest request;
DataConnectionReply reply;
CMUint32 sent;
/* Do some parameter checking */
if (!control || !hostIP || !hostName) {
goto loser;
}
request.flags = flags;
request.port = port;
request.hostIP = hostIP;
request.hostName = hostName;
request.forceHandshake = forceHandshake;
request.clientContext = CMT_CopyPtrToItem(clientContext);
/* Encode message */
if (CMT_EncodeMessage(SSLDataConnectionRequestTemplate, &message, &request) != CMTSuccess) {
goto loser;
}
/* Set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION | SSM_SSL_CONNECTION;
/* Send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* Validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION | SSM_SSL_CONNECTION)) {
goto loser;
}
/* Decode message */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) != CMTSuccess) {
goto loser;
}
/* Success */
if (reply.result == 0) {
if (control->sockFuncs.connect(sock, reply.port, NULL) != CMTSuccess) {
goto loser;
}
sent = CMT_WriteThisMany(control, sock, control->nonce.data,
control->nonce.len);
if (sent != control->nonce.len) {
goto loser;
}
/* Save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID)
!= CMTSuccess) {
goto loser;
}
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_GetSSLDataErrorCode(PCMT_CONTROL control, CMTSocket sock,
CMInt32* errorCode)
{
CMUint32 connID;
if (!control || !errorCode) {
goto loser;
}
/* get the data connection */
if (CMT_GetDataConnectionID(control, sock, &connID) != CMTSuccess) {
goto loser;
}
/* get the PR error */
if (CMT_GetNumericAttribute(control, connID, SSM_FID_SSLDATA_ERROR_VALUE,
errorCode) != CMTSuccess) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_ReleaseSSLSocketStatus(PCMT_CONTROL control, CMTSocket sock)
{
CMUint32 connectionID;
if (!control || !sock) {
goto loser;
}
if (CMT_GetDataConnectionID(control, sock, &connectionID) != CMTSuccess) {
goto loser;
}
if (CMT_SetNumericAttribute(control, connectionID,
SSM_FID_SSLDATA_DISCARD_SOCKET_STATUS,
0) != CMTSuccess) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_GetSSLSocketStatus(PCMT_CONTROL control, CMTSocket sock,
CMTItem* pickledStatus, CMInt32* level)
{
CMUint32 connectionID;
SingleNumMessage request;
CMTItem message;
PickleSecurityStatusReply reply;
if (!control || !pickledStatus || !level) {
goto loser;
}
/* get the data connection */
if (CMT_GetDataConnectionID(control, sock, &connectionID) != CMTSuccess) {
goto loser;
}
/* set up the request */
request.value = connectionID;
/* encode the request */
if (CMT_EncodeMessage(SingleNumMessageTemplate, &message, &request) !=
CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION |
SSM_CONSERVE_RESOURCE | SSM_PICKLE_SECURITY_STATUS;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_CONSERVE_RESOURCE | SSM_PICKLE_SECURITY_STATUS)) {
goto loser;
}
/* decode the reply */
if (CMT_DecodeMessage(PickleSecurityStatusReplyTemplate, &reply, &message)
!= CMTSuccess) {
goto loser;
}
/* success */
if (reply.result == 0) {
*pickledStatus = reply.blob;
*level = reply.securityLevel;
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_OpenTLSConnection(PCMT_CONTROL control, CMTSocket sock,
CMUint32 port, char* hostIP, char* hostName)
{
TLSDataConnectionRequest request;
CMTItem message;
DataConnectionReply reply;
CMUint32 sent;
/* do some parameter checking */
if (!control || !hostIP || !hostName) {
goto loser;
}
request.port = port;
request.hostIP = hostIP;
request.hostName = hostName;
/* encode the message */
if (CMT_EncodeMessage(TLSDataConnectionRequestTemplate, &message, &request)
!= CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION |
SSM_TLS_CONNECTION;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION |
SSM_TLS_CONNECTION)) {
goto loser;
}
/* decode the message */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
/* success */
if (reply.result == 0) {
if (control->sockFuncs.connect(sock, reply.port, NULL) != CMTSuccess) {
goto loser;
}
sent = CMT_WriteThisMany(control, sock, control->nonce.data,
control->nonce.len);
if (sent != control->nonce.len) {
goto loser;
}
/* save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID) != CMTSuccess) {
goto loser;
}
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_TLSStepUp(PCMT_CONTROL control, CMTSocket sock,
void* clientContext)
{
TLSStepUpRequest request;
SingleNumMessage reply;
CMTItem message;
CMUint32 connectionID;
/* check arguments */
if (!control || !sock) {
goto loser;
}
/* get the data connection ID */
if (CMT_GetDataConnectionID(control, sock, &connectionID) != CMTSuccess) {
goto loser;
}
/* set up the request */
request.connID = connectionID;
request.clientContext = CMT_CopyPtrToItem(clientContext);
/* encode the request */
if (CMT_EncodeMessage(TLSStepUpRequestTemplate, &message, &request) !=
CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION | SSM_TLS_STEPUP;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_TLS_STEPUP)) {
goto loser;
}
/* decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
return (CMTStatus) reply.value;
loser:
return CMTFailure;
}
CMTStatus CMT_OpenSSLProxyConnection(PCMT_CONTROL control, CMTSocket sock,
CMUint32 port, char* hostIP,
char* hostName)
{
TLSDataConnectionRequest request;
CMTItem message;
DataConnectionReply reply;
CMUint32 sent;
/* do some parameter checking */
if (!control || !hostIP || !hostName) {
goto loser;
}
request.port = port;
request.hostIP = hostIP;
request.hostName = hostName;
/* encode the message */
if (CMT_EncodeMessage(TLSDataConnectionRequestTemplate, &message, &request)
!= CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_DATA_CONNECTION |
SSM_PROXY_CONNECTION;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_DATA_CONNECTION |
SSM_PROXY_CONNECTION)) {
goto loser;
}
/* decode the message */
if (CMT_DecodeMessage(DataConnectionReplyTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
/* success */
if (reply.result == 0) {
if (control->sockFuncs.connect(sock, reply.port, NULL) != CMTSuccess) {
goto loser;
}
sent = CMT_WriteThisMany(control, sock, control->nonce.data,
control->nonce.len);
if (sent != control->nonce.len) {
goto loser;
}
/* save connection info */
if (CMT_AddDataConnection(control, sock, reply.connID) != CMTSuccess) {
goto loser;
}
return CMTSuccess;
}
loser:
return CMTFailure;
}
CMTStatus CMT_ProxyStepUp(PCMT_CONTROL control, CMTSocket sock,
void* clientContext, char* remoteUrl)
{
ProxyStepUpRequest request;
SingleNumMessage reply;
CMTItem message;
CMUint32 connectionID;
/* check arguments */
if (!control || !sock || !remoteUrl) {
goto loser;
}
/* get the data connection ID */
if (CMT_GetDataConnectionID(control, sock, &connectionID) != CMTSuccess) {
goto loser;
}
/* set up the request */
request.connID = connectionID;
request.clientContext = CMT_CopyPtrToItem(clientContext);
request.url = remoteUrl;
/* encode the request */
if (CMT_EncodeMessage(ProxyStepUpRequestTemplate, &message, &request) !=
CMTSuccess) {
goto loser;
}
/* set the message request type */
message.type = SSM_REQUEST_MESSAGE | SSM_RESOURCE_ACTION |
SSM_PROXY_STEPUP;
/* send the message and get the response */
if (CMT_SendMessage(control, &message) == CMTFailure) {
goto loser;
}
/* validate the message reply type */
if (message.type != (SSM_REPLY_OK_MESSAGE | SSM_RESOURCE_ACTION |
SSM_PROXY_STEPUP)) {
goto loser;
}
/* decode the reply */
if (CMT_DecodeMessage(SingleNumMessageTemplate, &reply, &message) !=
CMTSuccess) {
goto loser;
}
return (CMTStatus) reply.value;
loser:
return CMTFailure;
}

View File

@@ -1,636 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifdef XP_UNIX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef XP_MAC
#include "macsocket.h"
#else /* Windows */
#include <windows.h>
#include <winsock.h>
#endif
#endif
#include "cmtcmn.h"
#include "cmtutils.h"
#include "newproto.h"
#include <string.h>
/* Local defines */
#if 0
#define PSM_WAIT_BEFORE_SLEEP (CM_TicksPerSecond() * 60)
#define PSM_SPINTIME PSM_WAIT_BEFORE_SLEEP
#define PSM_KEEP_CONNECTION_ALIVE (PSM_WAIT_BEFORE_SLEEP * 900)
#endif
/* If you want to dump the messages sent between the plug-in and the PSM
* server, then remove the comment for the appropriate define.
*/
#if 0
#define PRINT_SEND_MESSAGES
#define PRINT_RECEIVE_MESSAGES
#endif
#ifdef PRINT_SEND_MESSAGES
#ifndef DEBUG_MESSAGES
#define DEBUG_MESSAGES
#endif /*DEBUG_MESSAGES*/
#endif /*PRINT_SEND_MESSAGES*/
#ifdef PRINT_RECEIVE_MESSAGES
#ifndef DEBUG_MESSAGES
#define DEBUG_MESSAGES
#endif /*DEBUG_MESSAGES*/
#endif /*PRINT_RECEIVE_MESSAGES*/
#ifdef DEBUG_MESSAGES
#define LOG(x) do { FILE *f; f=fopen("cmnav.log","a+"); if (f) { \
fprintf(f, x); fclose(f); } } while(0);
#define LOG_S(x) do { FILE *f; f=fopen("cmnav.log","a+"); if (f) { \
fprintf(f, "%s", x); fclose(f); } } while(0);
#define ASSERT(x) if (!(x)) { LOG("ASSERT:"); LOG(#x); LOG("\n"); exit(-1); }
#else
#define LOG(x)
#define LOG_S(x)
#define ASSERT(x)
#endif
CMUint32
cmt_Strlen(char *str)
{
CMUint32 len = strlen(str);
return sizeof(CMInt32) + (((len + 3)/4)*4);
}
CMUint32
cmt_Bloblen(CMTItem *blob)
{
return sizeof(CMInt32) + (((blob->len +3)/4)*4);
}
char *
cmt_PackString(char *buf, char *str)
{
CMUint32 len = strlen(str);
CMUint32 networkLen = htonl(len);
CMUint32 padlen = ((len + 3)/4)*4;
memcpy(buf, &networkLen, sizeof(CMUint32));
memcpy(buf + sizeof(CMUint32), str, len);
memset(buf + sizeof(CMUint32) + len, 0, padlen - len);
return buf+sizeof(CMUint32)+padlen;
}
char *
cmt_PackBlob(char *buf, CMTItem *blob)
{
CMUint32 len = blob->len;
CMUint32 networkLen = htonl(len);
CMUint32 padlen = (((blob->len + 3)/4)*4);
*((CMUint32*)buf) = networkLen;
memcpy(buf + sizeof(CMUint32), blob->data, len);
memset(buf + sizeof(CMUint32) + len, 0, padlen - len);
return buf + sizeof(CMUint32) + padlen;
}
char *
cmt_UnpackString(char *buf, char **str)
{
char *p = NULL;
CMUint32 len, padlen;
/* Get the string length */
len = ntohl(*(CMUint32*)buf);
/* Get the padded length */
padlen = ((len + 3)/4)*4;
/* Allocate the string and copy the data */
p = (char *) malloc(len + 1);
if (!p) {
goto loser;
}
/* Copy the data and NULL terminate */
memcpy(p, buf+sizeof(CMUint32), len);
p[len] = 0;
*str = p;
return buf+sizeof(CMUint32)+padlen;
loser:
*str = NULL;
if (p) {
free(p);
}
return buf+sizeof(CMUint32)+padlen;
}
char *
cmt_UnpackBlob(char *buf, CMTItem **blob)
{
CMTItem *p = NULL;
CMUint32 len, padlen;
/* Get the blob length */
len = ntohl(*(CMUint32*)buf);
/* Get the padded length */
padlen = ((len + 3)/4)*4;
/* Allocate the CMTItem for the blob */
p = (CMTItem*)malloc(sizeof(CMTItem));
if (!p) {
goto loser;
}
p->len = len;
p->data = (unsigned char *) malloc(len);
if (!p->data) {
goto loser;
}
/* Copy that data across */
memcpy(p->data, buf+sizeof(CMUint32), len);
*blob = p;
return buf+sizeof(CMUint32)+padlen;
loser:
*blob = NULL;
CMT_FreeMessage(p);
return buf+sizeof(CMUint32)+padlen;
}
#ifdef DEBUG_MESSAGES
void prettyPrintMessage(CMTItem *msg)
{
int numLines = ((msg->len+7)/8);
char curBuffer[9], *cursor, string[2], hexVal[8];
char hexArray[25];
int i, j, numToCopy;
/*Try printing out 8 bytes at a time. */
LOG("\n**********************************************************\n");
LOG("About to pretty Print Message\n\n");
curBuffer[9] = '\0';
hexArray[24] = '\0';
hexVal[2] = '\0';
string[1] = '\0';
LOG("Header Info\n");
LOG("Message Type: ");
sprintf(hexArray, "%lx\n", msg->type);
LOG(hexArray);
LOG("Message Length: ");
sprintf (hexArray, "%ld\n\n", msg->len);
LOG(hexArray);
LOG("Body of Message\n");
for (i=0, cursor=msg->data; i<numLines; i++, cursor+=8) {
/* First copy over the buffer to our local array */
numToCopy = ((msg->len - (unsigned int)((unsigned long)cursor-(unsigned long)msg->data)) < 8) ?
msg->len - (unsigned int)((unsigned long)cursor-(unsigned long)msg->data) : 8;
memcpy(curBuffer, cursor, 8);
for (j=0;j<numToCopy;j++) {
string[0] = curBuffer[j];
if (isprint(curBuffer[j])) {
string[0] = curBuffer[j];
} else {
string[0] = ' ';
}
LOG(string);
}
string[0] = ' ';
for (;j<8;j++) {
LOG(string);
}
LOG("\t");
for (j=0; j<numToCopy; j++) {
sprintf (hexVal,"%.2x", 0x0ff & (unsigned short)curBuffer[j]);
LOG(hexVal);
LOG(" ");
}
LOG("\n");
}
LOG("Done Pretty Printing Message\n");
LOG("**********************************************************\n\n");
}
#endif
CMTStatus CMT_SendMessage(PCMT_CONTROL control, CMTItem* message)
{
CMTStatus status;
CMUint32 msgCategory;
CMBool done = CM_FALSE;
#ifdef PRINT_SEND_MESSAGES
LOG("About to print message sent to PSM\n");
prettyPrintMessage(message);
#endif
/* Acquire lock on the control connection */
CMT_LOCK(control->mutex);
/* Try to send pending random data */
if (message->type != (SSM_REQUEST_MESSAGE | SSM_HELLO_MESSAGE))
{
/* If we've already said hello, then flush random data
just before sending the request. */
status = CMT_FlushPendingRandomData(control);
if (status != CMTSuccess)
goto loser;
}
status = CMT_TransmitMessage(control, message);
if (status != CMTSuccess) {
goto loser;
}
/* We have to deal with other types of data on the socket and */
/* handle them accordingly */
while (!done) {
status = CMT_ReceiveMessage(control, message);
if (status != CMTSuccess) {
goto loser;
}
msgCategory = (message->type & SSM_CATEGORY_MASK);
switch (msgCategory) {
case SSM_REPLY_OK_MESSAGE:
done = CM_TRUE;
break;
case SSM_REPLY_ERR_MESSAGE:
done = CM_TRUE;
break;
case SSM_EVENT_MESSAGE:
CMT_DispatchEvent(control, message);
break;
/* XXX FIX THIS!!! For the moment I'm ignoring all other types */
default:
break;
}
}
/* Release the control connection lock */
CMT_UNLOCK(control->mutex);
return CMTSuccess;
loser:
/* Release the control connection lock */
CMT_UNLOCK(control->mutex);
return CMTFailure;
}
CMTStatus CMT_TransmitMessage(PCMT_CONTROL control, CMTItem * message)
{
CMTMessageHeader header;
CMUint32 sent, rv;
/* Set up the message header */
header.type = htonl(message->type);
header.len = htonl(message->len);
/* Send the message header */
sent = CMT_WriteThisMany(control, control->sock,
(void *)&header, sizeof(CMTMessageHeader));
if (sent != sizeof(CMTMessageHeader)) {
goto loser;
}
/* Send the message body */
sent = CMT_WriteThisMany(control, control->sock, (void *)message->data,
message->len);
if (sent != message->len) {
goto loser;
}
/* Free the buffer */
free(message->data);
message->data = NULL;
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_ReceiveMessage(PCMT_CONTROL control, CMTItem * response)
{
CMTMessageHeader header;
CMUint32 numread, rv;
/* Get the message header */
numread = CMT_ReadThisMany(control, control->sock,
(void *)&header, sizeof(CMTMessageHeader));
if (numread != sizeof(CMTMessageHeader)) {
goto loser;
}
response->type = ntohl(header.type);
response->len = ntohl(header.len);
response->data = (unsigned char *) malloc(response->len);
if (response->data == NULL) {
goto loser;
}
numread = CMT_ReadThisMany(control, control->sock,
(void *)(response->data), response->len);
if (numread != response->len) {
goto loser;
}
#ifdef PRINT_RECEIVE_MESSAGES
LOG("About to print message received from PSM.\n");
prettyPrintMessage(response);
#endif /*PRINT_RECEIVE_MESSAGES*/
return CMTSuccess;
loser:
if (response->data) {
free(response->data);
}
return CMTFailure;
}
CMUint32 CMT_ReadThisMany(PCMT_CONTROL control, CMTSocket sock,
void * buffer, CMUint32 thisMany)
{
CMUint32 total = 0;
while (total < thisMany) {
int got;
got = control->sockFuncs.recv(sock, (void*)((char*)buffer + total),
thisMany-total);
if (got < 0 ) {
break;
}
total += got;
}
return total;
}
CMUint32 CMT_WriteThisMany(PCMT_CONTROL control, CMTSocket sock,
void * buffer, CMUint32 thisMany)
{
CMUint32 total = 0;
while (total < thisMany) {
CMInt32 got;
got = control->sockFuncs.send(sock, (void*)((char*)buffer+total),
thisMany-total);
if (got < 0) {
break;
}
total += got;
}
return total;
}
CMTItem* CMT_ConstructMessage(CMUint32 type, CMUint32 length)
{
CMTItem * p;
p = (CMTItem*)malloc(sizeof(CMTItem));
if (!p) {
goto loser;
}
p->type = type;
p->len = length;
p->data = (unsigned char *) malloc(length);
if (!p->data) {
goto loser;
}
return p;
loser:
CMT_FreeMessage(p);
return NULL;
}
void CMT_FreeMessage(CMTItem * p)
{
if (p != NULL) {
if (p->data != NULL) {
free(p->data);
}
free(p);
}
}
CMTStatus CMT_AddDataConnection(PCMT_CONTROL control, CMTSocket sock,
CMUint32 connectionID)
{
PCMT_DATA ptr;
/* This is the first connection */
if (control->cmtDataConnections == NULL) {
control->cmtDataConnections = ptr =
(PCMT_DATA)calloc(sizeof(CMT_DATA), 1);
if (!ptr) {
goto loser;
}
} else {
/* Position at the last entry */
for (ptr = control->cmtDataConnections; (ptr != NULL && ptr->next
!= NULL); ptr = ptr->next);
ptr->next = (PCMT_DATA)calloc(sizeof(CMT_DATA), 1);
if (!ptr->next) {
goto loser;
}
/* Fix up the pointers */
ptr->next->previous = ptr;
ptr = ptr->next;
}
/* Fill in the data */
ptr->sock = sock;
ptr->connectionID = connectionID;
return CMTSuccess;
loser:
return CMTFailure;
}
int
CMT_DestroyDataConnection(PCMT_CONTROL control, CMTSocket sock)
{
PCMT_DATA ptr, pptr = NULL;
int rv=CMTSuccess;
control->sockFuncs.close(sock);
for (ptr = control->cmtDataConnections; ptr != NULL;
pptr = ptr, ptr = ptr->next) {
if (ptr->sock == sock) {
if (pptr == NULL) {
/* node is at head */
control->cmtDataConnections = ptr->next;
if (ptr->priv != NULL)
ptr->priv->dest(ptr->priv);
free(ptr);
return rv;
}
/* node is elsewhere */
pptr->next = ptr->next;
if (ptr->priv != NULL)
ptr->priv->dest(ptr->priv);
free(ptr);
return rv;
}
}
return rv;
}
CMTStatus CMT_CloseDataConnection(PCMT_CONTROL control, CMUint32 connectionID)
{
/* PCMT_DATA ptr, pptr = NULL; */
CMTSocket sock;
/* int rv;*/
/* Get the socket for this connection */
if (CMT_GetDataSocket(control, connectionID, &sock) == CMTFailure) {
goto loser;
}
/* Free data connection associated with this socket */
if (CMT_DestroyDataConnection(control, sock) == CMTFailure) {
goto loser;
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus CMT_GetDataConnectionID(PCMT_CONTROL control, CMTSocket sock, CMUint32 * connectionID)
{
PCMT_DATA ptr;
for (ptr = control->cmtDataConnections; ptr != NULL; ptr = ptr->next) {
if (ptr->sock == sock) {
*connectionID = ptr->connectionID;
return CMTSuccess;
}
}
return CMTFailure;
}
CMTStatus CMT_GetDataSocket(PCMT_CONTROL control, CMUint32 connectionID, CMTSocket * sock)
{
PCMT_DATA ptr;
for (ptr = control->cmtDataConnections; ptr != NULL; ptr = ptr->next) {
if (ptr->connectionID == connectionID) {
*sock = ptr->sock;
return CMTSuccess;
}
}
return CMTFailure;
}
CMTStatus CMT_SetPrivate(PCMT_CONTROL control, CMUint32 connectionID,
CMTPrivate *cmtpriv)
{
PCMT_DATA ptr;
for (ptr = control->cmtDataConnections; ptr != NULL; ptr = ptr->next) {
if (ptr->connectionID == connectionID) {
ptr->priv = cmtpriv;
return CMTSuccess;
}
}
return CMTFailure;
}
CMTPrivate *CMT_GetPrivate(PCMT_CONTROL control, CMUint32 connectionID)
{
PCMT_DATA ptr;
for (ptr = control->cmtDataConnections; ptr != NULL; ptr = ptr->next) {
if (ptr->connectionID == connectionID) {
return ptr->priv;
}
}
return NULL;
}
void CMT_FreeItem(CMTItem *p)
{
CMT_FreeMessage(p);
}
CMTItem CMT_CopyPtrToItem(void* p)
{
CMTItem value = {0, NULL, 0};
if (!p) {
return value;
}
value.len = sizeof(p);
value.data = (unsigned char *) malloc(value.len);
memcpy(value.data, &p, value.len);
return value;
}
void * CMT_CopyItemToPtr(CMTItem value)
{
void * p = NULL;
if (value.len == sizeof(void*)) {
memcpy(&p, value.data, value.len);
}
return p;
}
CMTStatus CMT_ReferenceControlConnection(PCMT_CONTROL control)
{
CMT_LOCK(control->mutex);
control->refCount++;
CMT_UNLOCK(control->mutex);
return CMTSuccess;
}
void
CMT_LockConnection(PCMT_CONTROL control)
{
CMT_LOCK(control->mutex);
}
void
CMT_UnlockConnection(PCMT_CONTROL control)
{
CMT_UNLOCK(control->mutex);
}

View File

@@ -1,75 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef __CMTUTILS_H__
#define __CMTUTILS_H__
#include "cmtcmn.h"
#define New(type) (type*)malloc(sizeof(type))
#define NewArray(type, size) (type*)malloc(sizeof(type)*(size))
PCMT_EVENT CMT_GetEventHandler(PCMT_CONTROL control, CMUint32 type,
CMUint32 resourceID);
CMUint32 cmt_Strlen(char *str);
char *cmt_PackString(char *buf, char *str);
char *cmt_UnpackString(char *buf, char **str);
CMUint32 cmt_Bloblen(CMTItem* len);
char *cmt_PackBlob(char *buf, CMTItem * blob);
char *cmt_UnpackBlob(char *buf, CMTItem **blob);
CMTStatus CMT_SendMessage(PCMT_CONTROL control, CMTItem* message);
CMTStatus CMT_TransmitMessage(PCMT_CONTROL control, CMTItem * message);
CMTStatus CMT_ReceiveMessage(PCMT_CONTROL control, CMTItem * response);
CMUint32 CMT_ReadThisMany(PCMT_CONTROL control, CMTSocket sock,
void * buffer, CMUint32 thisMany);
CMUint32 CMT_WriteThisMany(PCMT_CONTROL control, CMTSocket sock,
void * buffer, CMUint32 thisMany);
CMTItem* CMT_ConstructMessage(CMUint32 type, CMUint32 length);
void CMT_FreeMessage(CMTItem * p);
CMTStatus CMT_AddDataConnection(PCMT_CONTROL control, CMTSocket sock, CMUint32 connectionID);
CMTStatus CMT_GetDataConnectionID(PCMT_CONTROL control, CMTSocket sock, CMUint32 * connectionID);
CMTStatus CMT_GetDataSocket(PCMT_CONTROL control, CMUint32 connectionID, CMTSocket * sock);
CMTStatus CMT_CloseDataConnection(PCMT_CONTROL control, CMUint32 connectionID);
CMTStatus CMT_SetPrivate(PCMT_CONTROL control, CMUint32 connectionID,
CMTPrivate *cmtpriv);
CMTPrivate *CMT_GetPrivate(PCMT_CONTROL control, CMUint32 connectionID);
void CMT_ServicePasswordRequest(PCMT_CONTROL cm_control, CMTItem * requestData);
void CMT_ProcessEvent(PCMT_CONTROL cm_control);
void CMT_DispatchEvent(PCMT_CONTROL cm_control, CMTItem * eventData);
CMTItem CMT_CopyPtrToItem(void* p);
void * CMT_CopyItemToPtr(CMTItem value);
#endif /* __CMTUTILS_H__ */

View File

@@ -1,44 +0,0 @@
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
#
# Override TARGETS variable so that only static libraries
# are specifed as dependencies within rules.mk.
#
TARGETS = $(LIBRARY)
SHARED_LIBRARY =
IMPORT_LIBRARY =
PURE_LIBRARY =
PROGRAM =

View File

@@ -1,125 +0,0 @@
#//
#// The contents of this file are subject to the Mozilla Public
#// License Version 1.1 (the "License"); you may not use this file
#// except in compliance with the License. You may obtain a copy of
#// the License at http://www.mozilla.org/MPL/
#//
#// Software distributed under the License is distributed on an "AS
#// IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
#// implied. See the License for the specific language governing
#// rights and limitations under the License.
#//
#// The Original Code is the Netscape security libraries.
#//
#// The Initial Developer of the Original Code is Netscape
#// Communications Corporation. Portions created by Netscape are
#// Copyright (C) 1994-2000 Netscape Communications Corporation. All
#// Rights Reserved.
#//
#// Contributor(s):
#//
#// Alternatively, the contents of this file may be used under the
#// terms of the GNU General Public License Version 2 or later (the
#// "GPL"), in which case the provisions of the GPL are applicable
#// instead of those above. If you wish to allow use of your
#// version of this file only under the terms of the GPL and not to
#// allow others to use your version of this file under the MPL,
#// indicate your decision by deleting the provisions above and
#// replace them with the notice and other provisions required by
#// the GPL. If you do not delete the provisions above, a recipient
#// may use your version of this file under either the MPL or the
#// GPL.
#//
IGNORE_MANIFEST=1
#//------------------------------------------------------------------------
#//
#// Makefile to build the ssl library
#//
#//------------------------------------------------------------------------
!if "$(MOZ_BITS)" == "16"
!ifndef MOZ_DEBUG
OPTIMIZER=-Os -UDEBUG -DNDEBUG
!endif
!endif
#//------------------------------------------------------------------------
#//
#// Specify the depth of the current directory relative to the
#// root of NS
#//
#//------------------------------------------------------------------------
DEPTH= ..\..\..\..
!ifndef MAKE_OBJ_TYPE
MAKE_OBJ_TYPE=EXE
!endif
#//------------------------------------------------------------------------
#//
#// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...)
#//
#//------------------------------------------------------------------------
LIBNAME=cmt
PDBFILE=$(LIBNAME).pdb
LINCS = -I$(PUBLIC)\security \
-I$(PUBLIC)\nspr \
-I$(DEPTH)\include \
-I..\include
!ifndef OS_CONFIG
OS_CONFIG = WIN$(MOZ_BITS)
!endif
LCFLAGS = -DEXPORT_VERSION -DLIB_BUILD
#//------------------------------------------------------------------------
#//
#// Define the files necessary to build the target (ie. OBJS)
#//
#//------------------------------------------------------------------------
OBJS= \
.\$(OBJDIR)\cmtinit.obj \
.\$(OBJDIR)\cmtssl.obj \
.\$(OBJDIR)\cmtutils.obj \
.\$(OBJDIR)\cmtpkcs7.obj \
.\$(OBJDIR)\cmthash.obj \
.\$(OBJDIR)\cmtcert.obj \
.\$(OBJDIR)\cmtres.obj \
.\$(OBJDIR)\cmtjs.obj \
.\$(OBJDIR)\cmtevent.obj \
.\$(OBJDIR)\cmtpasswd.obj \
.\$(OBJDIR)\cmtadvisor.obj \
.\$(OBJDIR)\cmtrng.obj \
.\$(OBJDIR)\cmtsdr.obj \
$(NULL)
#//------------------------------------------------------------------------
#//
#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...)
#// (these must be defined before the common makefiles are included)
#//
#//------------------------------------------------------------------------
LIBRARY=.\$(OBJDIR)\$(LIBNAME).lib
#//------------------------------------------------------------------------
#//
#// install headers
#//
#//------------------------------------------------------------------------
INSTALL_DIR=$(PUBLIC)\security
INSTALL_FILE_LIST=cmtcmn.h cmtjs.h cmtclist.h
#//------------------------------------------------------------------------
#//
#// Include the common makefile rules
#//
#//------------------------------------------------------------------------
include <$(DEPTH)/config/rules.mak>
install:: $(LIBRARY)
$(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
export:: INSTALL_FILES

View File

@@ -1,64 +0,0 @@
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
CORE_DEPTH = ../../..
DEPTH = ../../..
EXPORTS = \
cmtcmn.h \
cmtjs.h \
cmtclist.h \
$(NULL)
MODULE = security
CSRCS = cmtinit.c \
cmtssl.c \
cmtutils.c \
cmtcert.c \
cmthash.c \
cmtpkcs7.c \
cmtres.c \
cmtjs.c \
cmtevent.c \
cmtpasswd.c \
cmtadvisor.c \
cmtrng.c \
cmtsdr.c \
$(NULL)
REQUIRES = nspr security
LIBRARY_NAME = cmt
INCLUDES += -I$(CORE_DEPTH)/include

View File

@@ -1,128 +0,0 @@
#! gmake
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
ifneq ($(OS_ARCH), WINNT)
ifeq ($(OS_ARCH), Linux)
# On linux, we link with libstdc++
CPLUSPLUSRUNTIME = -L /usr/lib -lstdc++ -lm
else
# libC, presumably, is what we must link with elsewhere
CPLUSPLUSRUNTIME = -lC -lm
endif
endif
ifeq ($(OS_ARCH), SunOS)
ifeq ($(OS_RELEASE), 5.5.1)
OS_LIBS += -ldl -lsocket -lnsl -lthread -lposix4
endif
ifeq ($(OS_RELEASE), 5.6)
OS_LIBS += -ldl -lsocket -lnsl -lthread -lposix4
endif
endif
ifeq ($(OS_ARCH), Linux)
ifdef USE_PTHREADS
# Replace OS_LIBS, because the order of libpthread, libdl, and libc are
# very important. Otherwise you get horrible crashes.
OS_LIBS = -lpthread -ldl -lc
endif
endif
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################
ifeq ($(OS_ARCH), WINNT)
LDFLAGS += /NODEFAULTLIB:library
endif
EXTRA_LIBS = \
$(DIST)/lib/$(LIB_PREFIX)cmt.$(LIB_SUFFIX) \
$(DIST)/lib/$(LIB_PREFIX)protocol.$(LIB_SUFFIX) \
$(NULL)
ifeq ($(OS_ARCH), WINNT)
EXTRA_LIBS += wsock32.lib \
winmm.lib \
$(NULL)
endif
link:
if test -f $(PROGRAM); then \
echo "rm $(PROGRAM)"; \
rm $(PROGRAM); \
fi; \
gmake \
build_sample:
ifneq ($(OS_ARCH),WINNT)
cd $(CORE_DEPTH)/coreconf; gmake
endif
cd $(CORE_DEPTH)/security; gmake import; gmake export
cd ../../protocol; gmake
cd ..; gmake
gmake

View File

@@ -1,250 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "cmtcmn.h"
#include "appsock.h"
#ifdef XP_UNIX
#include <netinet/tcp.h>
#include <errno.h>
#endif
CMT_SocketFuncs socketFuncs = {
APP_GetSocket,
APP_Connect,
APP_VerifyUnixSocket,
APP_Send,
APP_Select,
APP_Receive,
APP_Shutdown,
APP_Close
};
CMTSocket APP_GetSocket(int unixSock)
{
APPSocket *sock;
int on = 1;
#ifndef XP_UNIX
if (unixSock) {
return NULL;
}
#endif
sock = malloc(sizeof(APPSocket));
if (sock == NULL) {
return NULL;
}
if (unixSock) {
sock->sock = socket(AF_UNIX, SOCK_STREAM, 0);
} else {
sock->sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
if (sock->sock < 0) {
free(sock);
return NULL;
}
if (!unixSock &&
setsockopt(sock->sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&on,
sizeof(on))) {
free(sock);
return NULL;
}
sock->isUnix = unixSock;
#ifdef XP_UNIX
memset (&sock->servAddr, 0, sizeof(struct sockaddr_un));
#endif
return (CMTSocket)sock;
}
CMTStatus APP_Connect(CMTSocket sock, short port, char *path)
{
APPSocket *cmSock = (APPSocket*)sock;
struct sockaddr_in iServAddr;
const struct sockaddr *servAddr;
size_t addrLen;
int error;
if (cmSock->isUnix){
#ifndef XP_UNIX
return CMTFailure;
#else
cmSock->servAddr.sun_family = AF_UNIX;
memcpy(&cmSock->servAddr.sun_path, path, strlen(path)+1);
servAddr = (const struct sockaddr*)&cmSock->servAddr;
addrLen = sizeof(cmSock->servAddr);
#endif
} else {
iServAddr.sin_family = AF_INET;
iServAddr.sin_port = htons(port);
iServAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
servAddr = (const struct sockaddr*)&iServAddr;
addrLen = sizeof(struct sockaddr_in);
}
while (connect(cmSock->sock, servAddr, addrLen) != 0) {
#ifdef WIN32
error = WSAGetLastError();
if (error == WSAEISCONN) {
break;
}
if ((error != WSAEINPROGRESS) && (error != WSAEWOULDBLOCK) &&
(error!= WSAEINVAL)) {
goto loser;
}
#else
error = errno;
if (error == EISCONN) {
break;
}
if (error != EINPROGRESS) {
goto loser;
}
#endif
}
return CMTSuccess;
loser:
return CMTFailure;
}
CMTStatus APP_VerifyUnixSocket(CMTSocket sock)
{
#ifndef XP_UNIX
return CMTFailure;
#else
APPSocket *cmSock = (APPSocket*)sock;
int rv;
struct stat statbuf;
if (!cmSock->isUnix) {
return CMTFailure;
}
rv = stat(cmSock->servAddr.sun_path, &statbuf);
if (rv < 0) {
goto loser;
}
if (statbuf.st_uid != geteuid()) {
goto loser;
}
return CMTSuccess;
loser:
close(cmSock->sock);
free(cmSock);
return CMTFailure;
#endif
}
size_t APP_Send(CMTSocket sock, void *buffer, size_t length)
{
APPSocket *cmSock = (APPSocket*) sock;
return send(cmSock->sock, buffer, length, 0);
}
CMTSocket APP_Select(CMTSocket *socks, int numsocks, int poll)
{
APPSocket **sockArr = (APPSocket**)socks;
SOCKET nsocks = 0;
int i, rv;
struct timeval timeout;
fd_set readfds;
#ifdef WIN32
win_startover:
#endif
FD_ZERO(&readfds);
for (i=0; i<numsocks; i++) {
FD_SET(sockArr[i]->sock, &readfds);
if (sockArr[i]->sock > nsocks) {
nsocks = sockArr[i]->sock;
}
}
if (poll) {
timeout.tv_sec = 0;
timeout.tv_usec = 0;
}
rv = select(nsocks+1, &readfds, NULL, NULL, (poll) ? &timeout : NULL);
#ifdef WIN32
/* XXX Win95/98 Bug (Q177346)
* select() with no timeout might return even if there is no data
* pending or no error has occurred. To get around this problem,
* we loop if these erroneous conditions happen.
*/
if (poll == 0 && rv == 0) {
goto win_startover;
}
#endif
/* Figure out which socket was selected */
if (rv == -1 || rv == 0) {
goto loser;
}
for (i=0; i<numsocks; i++) {
if (FD_ISSET(sockArr[i]->sock, &readfds)) {
return (CMTSocket)sockArr[i];
}
}
loser:
return NULL;
}
size_t APP_Receive(CMTSocket sock, void *buffer, size_t bufSize)
{
APPSocket *cmSock = (APPSocket*)sock;
return recv(cmSock->sock, buffer, bufSize, 0);
}
CMTStatus APP_Shutdown(CMTSocket sock)
{
APPSocket *cmSock = (APPSocket*)sock;
int rv;
rv = shutdown(cmSock->sock, 1);
return (rv == 0) ? CMTSuccess : CMTFailure;
}
CMTStatus APP_Close(CMTSocket sock)
{
APPSocket *cmSock = (APPSocket*)sock;
int rv;
#ifdef XP_UNIX
rv = close(cmSock->sock);
#else
rv = closesocket(cmSock->sock);
#endif
free(cmSock);
return (rv == 0) ? CMTSuccess : CMTFailure;
}

View File

@@ -1,69 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef _APPSOCK_H_
#define _APPSOCK_H_
#include "cmtcmn.h"
#ifdef XP_UNIX
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/stat.h>
typedef int SOCKET;
#endif
typedef struct APPSocketStr {
SOCKET sock;
int isUnix;
#ifdef XP_UNIX
struct sockaddr_un servAddr;
#endif
} APPSocket;
extern CMT_SocketFuncs socketFuncs;
CMTStatus APP_Close(CMTSocket sock);
CMTStatus APP_Shutdown(CMTSocket sock);
size_t APP_Receive(CMTSocket sock, void *buffer, size_t bufSize);
CMTSocket APP_Select(CMTSocket *socks, int numsocks, int poll);
size_t APP_Send(CMTSocket sock, void *buffer, size_t length);
CMTStatus APP_VerifyUnixSocket(CMTSocket sock);
CMTStatus APP_Connect(CMTSocket sock, short port, char *path);
CMTSocket APP_GetSocket(int unixSock);
#endif /* _APPSOCK_H_ */

View File

@@ -1,44 +0,0 @@
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
#
# Override TARGETS variable so that only static libraries
# are specifed as dependencies within rules.mk.
#
TARGETS = $(PROGRAM)
SHARED_LIBRARY =
IMPORT_LIBRARY =
PURE_LIBRARY =
LIBRARY =

View File

@@ -1,52 +0,0 @@
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
CORE_DEPTH = ../../../../..
# MODULE public and private header directories are implicitly REQUIRED.
MODULE = cmtsample
EXPORTS = \
$(NULL)
CSRCS = \
sample.c \
appsock.c \
$(NULL)
INCLUDES += -I../../protocol -I..
# The MODULE is always implicitly required.
# Listing it here in REQUIRES makes it appear twice in the cc command line.
REQUIRES = security
PROGRAM = cmtsample

View File

@@ -1,346 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "cmtcmn.h"
#include "cmtjs.h"
#include "appsock.h"
#include <stdarg.h>
#include <string.h>
#ifdef XP_UNIX
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#ifdef WIN32
#include <direct.h>
#endif
/*
* This is a simple program that tries to detect if the psm server is loaded.
* If the server is not loaded, it will start it. The program will then
* connect to the server and fetch an HTML page from an SSL server.
*
* NOTE: This sample program does not implement a mutex for the libraries.
* If implementing a threaded application, then pass in a mutex structure
* so that connections to the psm server happen in a thread safe manner.
*/
#define NUM_CONNECT_TRIES 10
#define READ_BUFFER_SIZE 1024
void
usage(void)
{
printf("Usage:\n"
"\tcmtsample <secure site>\n\n"
"This program will then echo the retrieved HTML to the screen\n");
}
void
errorMessage(int err,char *msg, ...)
{
va_list args;
va_start(args, msg);
fprintf (stderr, "cmtSample%s: ", (err) ? " error" : "");
vfprintf (stderr, msg, args);
fprintf (stderr, "\n");
va_end(args);
if (err) {
exit (err);
}
}
#ifdef XP_UNIX
#define FILE_PATH_SEPARATOR '/'
#elif defined (WIN32)
#define FILE_PATH_SEPARATOR '\\'
#else
#error Tell me what the file path separator is.
#endif
PCMT_CONTROL
connect_to_psm(void)
{
PCMT_CONTROL control=NULL;
char path[256], *tmp;
#ifdef XP_UNIX
if (getcwd(path,256) == NULL) {
return NULL;
}
#elif defined(WIN32)
if (_getcwd(path,256) == NULL) {
return NULL;
}
#else
#error Teach me how to get the current working directory.
#endif
tmp = &path[strlen(path)];
sprintf(tmp,"%c%s", FILE_PATH_SEPARATOR, "psm");
return CMT_EstablishControlConnection(path, &socketFuncs, NULL);
}
#define HTTPS_STRING "https://"
char*
extract_host_from_url(char *url)
{
char *start, *end, *retString=NULL;
while(isspace(*url)) {
url++;
}
url = strdup(url);
start = strstr(url, HTTPS_STRING);
if (start == NULL) {
return NULL;
}
start += strlen(HTTPS_STRING);
/*
* Figure out the end of the host name.
*/
end = strchr(start, ':');
if (end != NULL) {
*end = '\0';
} else {
end = strchr(start, '/');
if (end != NULL) {
*end = '\0';
} else {
end = strchr(start, ' ');
if (end != NULL) {
*end = '\0';
}
}
}
retString = strdup(start);
return retString;
}
CMUint32
get_port_from_url(char *url)
{
char *colon, *port;
url = strdup(url);
colon = strrchr(url, ':');
if (colon == NULL ||
!isdigit(colon[1])) {
/* Return the default SSL port. */
free(url);
return 443;
}
colon++;
port = colon;
while(isdigit(*colon))
colon++;
colon[1] = '\0';
free(url);
return (CMUint32)atol(port);
}
char*
extract_get_target(char *url)
{
char *slash;
slash = strstr(url, "//");
slash += 2;
slash = strchr(slash, '/');
if (slash != NULL)
return strdup (slash);
else
return strdup ("/");
}
/*
* We'll use this function for prompting for a password.
*/
char*
passwordCallback(void *arg, char *prompt, void *cotext, int isPaswd)
{
char input[256];
printf(prompt);
fgets(input, 256, stdin);
return strdup(input);
}
void
freeCallback(char *userInput)
{
free (userInput);
}
#define NUM_PREFS 2
int
main(int argc, char **argv)
{
PCMT_CONTROL control;
CMTSocket sock, selSock;
char *hostname;
struct hostent *host;
char *ipAddress;
char buffer[READ_BUFFER_SIZE];
size_t bytesRead;
struct sockaddr_in destAddr;
char *getString;
char requestString[256];
char *profile;
CMTSetPrefElement prefs[NUM_PREFS];
char profileDir[256];
#ifdef WIN32
WORD WSAVersion = 0x0101;
WSADATA WSAData;
WSAStartup (WSAVersion, &WSAData);
#endif
if (argc < 2) {
usage();
return 1;
}
errorMessage (0,"cmtsample v1.0");
errorMessage (0,"Will try connecting to site %s", argv[1]);
if (strstr(argv[1], "https://") == NULL) {
errorMessage(2,"%s is not a secure site", argv[1]);
}
control = connect_to_psm();
if (control == NULL) {
errorMessage(3, "Could not connect to the psm server");
}
/*
* Now we have to send the hello message.
*/
#ifdef WIN32
profile = strdup("default");
sprintf(profileDir,"%s", "c:\\default");
#elif defined (XP_UNIX)
profile = getenv("LOGNAME");
sprintf(profileDir, "%s/.netscape", getenv("HOME"));
#else
#error Teach me how to fill in the user profile.
#endif
if (CMT_Hello(control, PROTOCOL_VERSION,
profile, profileDir) != CMTSuccess)
{
errorMessage(10, "Failed to send the Hello Message.");
}
CMT_SetPromptCallback(control, passwordCallback, NULL);
CMT_SetAppFreeCallback(control, freeCallback);
/*
* Now pass along some preferences to psm. We'll pass hard coded
* ones here, but apps should figure out a way to manage their user's
* preferences.
*/
prefs[0].key = "security.enable_ssl2";
prefs[0].value = "true";
prefs[0].type = CMT_PREF_BOOL;
prefs[1].key = "security.enable_ssl3";
prefs[1].value = "true";
prefs[1].type = CMT_PREF_BOOL;
CMT_PassAllPrefs(control, NUM_PREFS, prefs);
hostname = extract_host_from_url(argv[1]);
host = gethostbyname(hostname);
if (host == NULL) {
errorMessage(11, "gethostbyname for %s failed", hostname);
}
if (host->h_length != 4) {
errorMessage(4, "Site %s uses IV v6 socket. Not supported by psm.");
}
/* Create the socket we will use to get the decrypted data back from
* the psm server.
*/
sock = APP_GetSocket(0);
if (sock == NULL) {
errorMessage(5, "Could not create new socket for communication with "
"the psm server.");
}
memcpy(&(destAddr.sin_addr.s_addr), host->h_addr, host->h_length);
ipAddress = inet_ntoa(destAddr.sin_addr);
errorMessage(0, "Mapped %s to the following IP address: %s", argv[1],
ipAddress);
if (CMT_OpenSSLConnection(control, sock, SSM_REQUEST_SSL_DATA_SSL,
get_port_from_url(argv[1]), ipAddress,
hostname, CM_FALSE, NULL) != CMTSuccess) {
errorMessage(6, "Could not open SSL connection to %s.", argv[1]);
}
getString = extract_get_target(argv[1]);
sprintf(requestString,
"GET %s HTTP/1.0\r\n"
"\r\n", getString, hostname);
APP_Send(sock, requestString, strlen(requestString));
/*
* Now all we have to do is sit here and fetch the data from the
* socket.
*/
errorMessage (0, "About to print out the fetched page.");
while ((selSock=APP_Select(&sock, 1, 0)) != NULL) {
if (selSock == sock) {
bytesRead = APP_Receive(sock, buffer, READ_BUFFER_SIZE-1);
if (bytesRead == -1 || bytesRead == 0) {
break;
}
buffer[bytesRead] = '\0';
fprintf(stderr, buffer);
}
}
fprintf(stderr,"\n");
if (bytesRead == -1) {
errorMessage(7, "Error receiving decrypted data from psm.");
}
errorMessage(0, "Successfully read the entire page.");
if (CMT_DestroyDataConnection(control, sock) != CMTSuccess) {
errorMessage(8, "Error destroygin the SSL data connection "
"with the psm server.");
}
if (CMT_CloseControlConnection(control) != CMTSuccess) {
errorMessage(9, "Error closing the control connection.");
}
return 0;
}

View File

@@ -1,99 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "cmt.h"
CMTStatus myCallback(CMTControl * control, CMTItem * event, void * arg);
int main(int argc, char ** argv)
{
CMTItem * msg, * event = NULL;
CMTStatus status;
int socket, datasocket;
int sent;
CMTControl * connect;
char * buffer = "some weird text that I feel like passing to server";
connect = CMT_ControlConnect(myCallback, event);
msg = CMT_ConstructMessage(10);
msg->type = (int)CMTClientMessage;
sprintf((char *)msg->data, "first msg!");
status = CMT_SendMessage(connect, msg, event);
if (status != SECSuccess)
perror("CMT_SendMessage");
CMT_FreeEvent(event);
event = NULL;
sprintf((char *)msg->data, "second msg");
status = CMT_SendMessage(connect, msg, event);
if (status != SECSuccess)
perror("CMT_SendMessage");
datasocket = CMT_DataConnect(connect, NULL);
if (datasocket < 0)
perror("CMT_DataConnect");
sent = write(datasocket, (void *)buffer, strlen(buffer));
sent = write(datasocket, (void *)buffer, strlen(buffer));
close(datasocket);
msg->type = (int)CMTClientMessage;
sprintf((char *)msg->data, "third msg!");
status = CMT_SendMessage(connect, msg, event);
if (status != SECSuccess)
perror("CMT_SendMessage");
status = CMT_CloseControlConnection(connect);
if (status != SECSuccess)
perror("CMT_CloseControl");
CMT_FreeMessage(msg);
CMT_FreeEvent(event);
}
CMTStatus myCallback(CMTControl * control, CMTItem * event, void * arg)
{
if (event)
printf("Event received is : type %d, data %s\n", event->type, event->data);
else printf("No event!\n");
if (arg)
printf("Arg is %s\n", (char *)arg);
else printf("No arg!\n");
return SECSuccess;
}

View File

@@ -1,3 +0,0 @@
#include "MacPrefix.h"

View File

@@ -1,2 +0,0 @@
#include "MacPrefix_debug.h"

View File

@@ -1,27 +0,0 @@
#!nmake
#
# 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=..\..\..
include <$(DEPTH)/config/config.mak>
DIRS = client protocol
include <$(DEPTH)\config\rules.mak>

View File

@@ -1,43 +0,0 @@
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
#
CORE_DEPTH = ../..
DEPTH = ../..
DIRS = protocol client
#
# these dirs are not built at the moment
#
#NOBUILD_DIRS = jar

View File

@@ -1,3 +0,0 @@
obscure.h
rsrcids.h
ssmdefs.h

View File

@@ -1,74 +0,0 @@
#! gmake
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
include config.mk
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################

View File

@@ -1,64 +0,0 @@
#! gmake
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
DEPTH = ../../../..
topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
LIBRARY_NAME = protocol
MODULE = security
EXPORTS = \
protocol.h \
protocolf.h \
protocolport.h \
protocolnspr20.h \
protocolshr.h \
ssmdefs.h \
rsrcids.h \
messages.h \
newproto.h \
$(NULL)
CSRCS = newproto.c \
templates.c \
protocolshr.c \
$(NULL)
include $(topsrcdir)/config/rules.mk

View File

@@ -1,44 +0,0 @@
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
#
# Override TARGETS variable so that only static libraries
# are specifed as dependencies within rules.mk.
#
TARGETS = $(LIBRARY)
SHARED_LIBRARY =
IMPORT_LIBRARY =
PURE_LIBRARY =
PROGRAM =

View File

@@ -1,124 +0,0 @@
#//
#// The contents of this file are subject to the Mozilla Public
#// License Version 1.1 (the "License"); you may not use this file
#// except in compliance with the License. You may obtain a copy of
#// the License at http://www.mozilla.org/MPL/
#//
#// Software distributed under the License is distributed on an "AS
#// IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
#// implied. See the License for the specific language governing
#// rights and limitations under the License.
#//
#// The Original Code is the Netscape security libraries.
#//
#// The Initial Developer of the Original Code is Netscape
#// Communications Corporation. Portions created by Netscape are
#// Copyright (C) 1994-2000 Netscape Communications Corporation. All
#// Rights Reserved.
#//
#// Contributor(s):
#//
#// Alternatively, the contents of this file may be used under the
#// terms of the GNU General Public License Version 2 or later (the
#// "GPL"), in which case the provisions of the GPL are applicable
#// instead of those above. If you wish to allow use of your
#// version of this file only under the terms of the GPL and not to
#// allow others to use your version of this file under the MPL,
#// indicate your decision by deleting the provisions above and
#// replace them with the notice and other provisions required by
#// the GPL. If you do not delete the provisions above, a recipient
#// may use your version of this file under either the MPL or the
#// GPL.
#//
IGNORE_MANIFEST=1
#//------------------------------------------------------------------------
#//
#// Makefile to build the ssl library
#//
#//------------------------------------------------------------------------
!if "$(MOZ_BITS)" == "16"
!ifndef MOZ_DEBUG
OPTIMIZER=-Os -UDEBUG -DNDEBUG
!endif
!endif
#//------------------------------------------------------------------------
#//
#// Specify the depth of the current directory relative to the
#// root of NS
#//
#//------------------------------------------------------------------------
DEPTH= ..\..\..\..
!ifndef MAKE_OBJ_TYPE
MAKE_OBJ_TYPE=EXE
!endif
#//------------------------------------------------------------------------
#//
#// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...)
#//
#//------------------------------------------------------------------------
LIBNAME=protocol
PDBFILE=$(LIBNAME).pdb
LINCS = -I$(PUBLIC)\security \
-I$(PUBLIC)\nspr \
-I$(DEPTH)\include \
-I..\include
!ifndef OS_CONFIG
OS_CONFIG = WIN$(MOZ_BITS)
!endif
LCFLAGS = -DEXPORT_VERSION -DLIB_BUILD
#//------------------------------------------------------------------------
#//
#// Define the files necessary to build the target (ie. OBJS)
#//
#//------------------------------------------------------------------------
OBJS= \
.\$(OBJDIR)\newproto.obj \
.\$(OBJDIR)\templates.obj \
.\$(OBJDIR)\protocolshr.obj \
$(NULL)
#//------------------------------------------------------------------------
#//
#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...)
#// (these must be defined before the common makefiles are included)
#//
#//------------------------------------------------------------------------
LIBRARY=.\$(OBJDIR)\$(LIBNAME).lib
#//------------------------------------------------------------------------
#//
#// install headers
#//
#//------------------------------------------------------------------------
INSTALL_DIR=$(PUBLIC)\security
INSTALL_FILE_LIST= protocol.h \
protocolf.h \
protocolport.h \
protocolnspr20.h \
protocolshr.h \
ssmdefs.h \
rsrcids.h \
messages.h \
newproto.h \
$(NULL)
#//------------------------------------------------------------------------
#//
#// Include the common makefile rules
#//
#//------------------------------------------------------------------------
include <$(DEPTH)/config/rules.mak>
install:: $(LIBRARY)
$(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
export:: INSTALL_FILES

View File

@@ -1,65 +0,0 @@
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Netscape security libraries.
#
# The Initial Developer of the Original Code is Netscape
# Communications Corporation. Portions created by Netscape are
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the
# terms of the GNU General Public License Version 2 or later (the
# "GPL"), in which case the provisions of the GPL are applicable
# instead of those above. If you wish to allow use of your
# version of this file only under the terms of the GPL and not to
# allow others to use your version of this file under the MPL,
# indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by
# the GPL. If you do not delete the provisions above, a recipient
# may use your version of this file under either the MPL or the
# GPL.
#
CORE_DEPTH = ../../..
EXPORTS = \
protocol.h \
protocolf.h \
protocolport.h \
protocolnspr20.h \
protocolshr.h \
ssmdefs.h \
rsrcids.h \
messages.h \
newproto.h \
$(NULL)
MODULE = security
CSRCS = newproto.c \
protocolshr.c \
templates.c \
$(NULL)
ifeq ($(subst /,_,$(shell uname -s)),OS2)
CSRCS += os2_rand.c
endif
# mac_rand.c
# unix_rand.c
# win_rand.c
# prelib.c
REQUIRES = security dbm nspr
LIBRARY_NAME = protocol

View File

@@ -1,620 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef __MESSAGES_H__
#define __MESSAGES_H__
#include "newproto.h"
typedef struct SingleNumMessage {
CMInt32 value;
} SingleNumMessage;
extern CMTMessageTemplate SingleNumMessageTemplate[];
typedef struct SingleStringMessage {
char *string;
} SingleStringMessage;
extern CMTMessageTemplate SingleStringMessageTemplate[];
typedef struct SingleItemMessage {
CMTItem item;
} SingleItemMessage;
extern CMTMessageTemplate SingleItemMessageTemplate[];
typedef struct HelloRequest {
CMInt32 version;
CMInt32 policy;
CMBool doesUI;
char *profile;
char* profileDir;
} HelloRequest;
extern CMTMessageTemplate HelloRequestTemplate[];
typedef struct HelloReply {
CMInt32 result;
CMInt32 sessionID;
CMInt32 version;
CMInt32 httpPort;
CMInt32 policy;
CMTItem nonce;
char *stringVersion;
} HelloReply;
extern CMTMessageTemplate HelloReplyTemplate[];
typedef struct SSLDataConnectionRequest {
CMInt32 flags;
CMInt32 port;
char *hostIP;
char *hostName;
CMBool forceHandshake;
CMTItem clientContext;
} SSLDataConnectionRequest;
extern CMTMessageTemplate SSLDataConnectionRequestTemplate[];
typedef struct TLSDataConnectionRequest {
CMInt32 port;
char* hostIP;
char* hostName;
} TLSDataConnectionRequest;
extern CMTMessageTemplate TLSDataConnectionRequestTemplate[];
typedef struct TLSStepUpRequest {
CMUint32 connID;
CMTItem clientContext;
} TLSStepUpRequest;
extern CMTMessageTemplate TLSStepUpRequestTemplate[];
typedef struct ProxyStepUpRequest {
CMUint32 connID;
CMTItem clientContext;
char* url;
} ProxyStepUpRequest;
extern CMTMessageTemplate ProxyStepUpRequestTemplate[];
typedef struct PKCS7DataConnectionRequest {
CMUint32 resID;
CMTItem clientContext;
} PKCS7DataConnectionRequest;
extern CMTMessageTemplate PKCS7DataConnectionRequestTemplate[];
typedef struct DataConnectionReply {
CMInt32 result;
CMInt32 connID;
CMInt32 port;
} DataConnectionReply;
extern CMTMessageTemplate DataConnectionReplyTemplate[];
typedef struct UIEvent {
CMInt32 resourceID;
CMInt32 width;
CMInt32 height;
CMBool isModal;
char *url;
CMTItem clientContext;
} UIEvent;
extern CMTMessageTemplate UIEventTemplate[];
extern CMTMessageTemplate OldUIEventTemplate[];
typedef struct TaskCompletedEvent {
CMInt32 resourceID;
CMInt32 numTasks;
CMInt32 result;
} TaskCompletedEvent;
extern CMTMessageTemplate TaskCompletedEventTemplate[];
typedef struct VerifyDetachedSigRequest {
CMInt32 pkcs7ContentID;
CMInt32 certUsage;
CMInt32 hashAlgID;
CMBool keepCert;
CMTItem hash;
} VerifyDetachedSigRequest;
extern CMTMessageTemplate VerifyDetachedSigRequestTemplate[];
typedef struct CreateSignedRequest {
CMInt32 scertRID;
CMInt32 ecertRID;
CMInt32 dig_alg;
CMTItem digest;
} CreateSignedRequest;
extern CMTMessageTemplate CreateSignedRequestTemplate[];
typedef struct CreateContentInfoReply {
CMInt32 ciRID;
CMInt32 result;
CMInt32 errorCode;
} CreateContentInfoReply;
extern CMTMessageTemplate CreateContentInfoReplyTemplate[];
typedef struct CreateEncryptedRequest {
CMInt32 scertRID;
CMInt32 nrcerts;
CMInt32 *rcertRIDs;
} CreateEncryptedRequest;
extern CMTMessageTemplate CreateEncryptedRequestTemplate[];
typedef struct CreateResourceRequest {
CMInt32 type;
CMTItem params;
} CreateResourceRequest;
extern CMTMessageTemplate CreateResourceRequestTemplate[];
typedef struct CreateResourceReply {
CMInt32 result;
CMInt32 resID;
} CreateResourceReply;
extern CMTMessageTemplate CreateResourceReplyTemplate[];
typedef struct GetAttribRequest {
CMInt32 resID;
CMInt32 fieldID;
} GetAttribRequest;
extern CMTMessageTemplate GetAttribRequestTemplate[];
typedef struct GetAttribReply {
CMInt32 result;
SSMAttributeValue value;
} GetAttribReply;
extern CMTMessageTemplate GetAttribReplyTemplate[];
typedef struct SetAttribRequest {
CMInt32 resID;
CMInt32 fieldID;
SSMAttributeValue value;
} SetAttribRequest;
extern CMTMessageTemplate SetAttribRequestTemplate[];
typedef struct PickleResourceReply {
CMInt32 result;
CMTItem blob;
} PickleResourceReply;
extern CMTMessageTemplate PickleResourceReplyTemplate[];
typedef struct UnpickleResourceRequest {
CMInt32 resourceType;
CMTItem resourceData;
} UnpickleResourceRequest;
extern CMTMessageTemplate UnpickleResourceRequestTemplate[];
typedef struct UnpickleResourceReply {
CMInt32 result;
CMInt32 resID;
} UnpickleResourceReply;
extern CMTMessageTemplate UnpickleResourceReplyTemplate[];
typedef struct PickleSecurityStatusReply {
CMInt32 result;
CMInt32 securityLevel;
CMTItem blob;
} PickleSecurityStatusReply;
extern CMTMessageTemplate PickleSecurityStatusReplyTemplate[];
typedef struct DupResourceReply {
CMInt32 result;
CMUint32 resID;
} DupResourceReply;
extern CMTMessageTemplate DupResourceReplyTemplate[];
typedef struct DestroyResourceRequest {
CMInt32 resID;
CMInt32 resType;
} DestroyResourceRequest;
extern CMTMessageTemplate DestroyResourceRequestTemplate[];
typedef struct VerifyCertRequest {
CMInt32 resID;
CMInt32 certUsage;
} VerifyCertRequest;
extern CMTMessageTemplate VerifyCertRequestTemplate[];
typedef struct AddTempCertToDBRequest {
CMInt32 resID;
char *nickname;
CMInt32 sslFlags;
CMInt32 emailFlags;
CMInt32 objSignFlags;
} AddTempCertToDBRequest;
extern CMTMessageTemplate AddTempCertToDBRequestTemplate[];
typedef struct MatchUserCertRequest {
CMInt32 certType;
CMInt32 numCANames;
char **caNames;
} MatchUserCertRequest;
extern CMTMessageTemplate MatchUserCertRequestTemplate[];
typedef struct MatchUserCertReply {
CMInt32 numCerts;
CMInt32 *certs;
} MatchUserCertReply;
extern CMTMessageTemplate MatchUserCertReplyTemplate[];
typedef struct EncodeCRMFReqRequest {
CMInt32 numRequests;
CMInt32 * reqIDs;
} EncodeCRMFReqRequest;
extern CMTMessageTemplate EncodeCRMFReqRequestTemplate[];
typedef struct CMMFCertResponseRequest {
char *nickname;
char *base64Der;
CMBool doBackup;
CMTItem clientContext;
} CMMFCertResponseRequest;
extern CMTMessageTemplate CMMFCertResponseRequestTemplate[];
typedef struct PasswordRequest {
CMInt32 tokenKey;
char *prompt;
CMTItem clientContext;
} PasswordRequest;
extern CMTMessageTemplate PasswordRequestTemplate[];
typedef struct PasswordReply {
CMInt32 result;
CMInt32 tokenID;
char * passwd;
} PasswordReply;
extern CMTMessageTemplate PasswordReplyTemplate[];
typedef struct KeyPairGenRequest {
CMInt32 keyGenCtxtID;
CMInt32 genMechanism;
CMInt32 keySize;
CMTItem params;
} KeyPairGenRequest;
extern CMTMessageTemplate KeyPairGenRequestTemplate[];
typedef struct DecodeAndCreateTempCertRequest {
CMInt32 type;
CMTItem cert;
} DecodeAndCreateTempCertRequest;
extern CMTMessageTemplate DecodeAndCreateTempCertRequestTemplate[];
typedef struct GenKeyOldStyleRequest {
char *choiceString;
char *challenge;
char *typeString;
char *pqgString;
} GenKeyOldStyleRequest;
extern CMTMessageTemplate GenKeyOldStyleRequestTemplate[];
typedef struct GenKeyOldStyleTokenRequest {
CMInt32 rid;
CMInt32 numtokens;
char ** tokenNames;
} GenKeyOldStyleTokenRequest;
extern CMTMessageTemplate GenKeyOldStyleTokenRequestTemplate[];
typedef struct GenKeyOldStyleTokenReply {
CMInt32 rid;
CMBool cancel;
char * tokenName;
} GenKeyOldStyleTokenReply;
extern CMTMessageTemplate GenKeyOldStyleTokenReplyTemplate[];
typedef struct GenKeyOldStylePasswordRequest {
CMInt32 rid;
char * tokenName;
CMBool internal;
CMInt32 minpwdlen;
CMInt32 maxpwdlen;
} GenKeyOldStylePasswordRequest;
extern CMTMessageTemplate GenKeyOldStylePasswordRequestTemplate[];
typedef struct GenKeyOldStylePasswordReply {
CMInt32 rid;
CMBool cancel;
char * password;
} GenKeyOldStylePasswordReply;
extern CMTMessageTemplate GenKeyOldStylePasswordReplyTemplate[];
typedef struct GetKeyChoiceListRequest {
char *type;
char *pqgString;
} GetKeyChoiceListRequest;
extern CMTMessageTemplate GetKeyChoiceListRequestTemplate[];
typedef struct GetKeyChoiceListReply {
CMInt32 nchoices;
char **choices;
} GetKeyChoiceListReply;
extern CMTMessageTemplate GetKeyChoiceListReplyTemplate[];
typedef struct AddNewSecurityModuleRequest {
char *moduleName;
char *libraryPath;
CMInt32 pubMechFlags;
CMInt32 pubCipherFlags;
} AddNewSecurityModuleRequest;
extern CMTMessageTemplate AddNewSecurityModuleRequestTemplate[];
typedef struct FilePathRequest {
CMInt32 resID;
char *prompt;
CMBool getExistingFile;
char *fileRegEx;
} FilePathRequest;
extern CMTMessageTemplate FilePathRequestTemplate[];
typedef struct FilePathReply {
CMInt32 resID;
char *filePath;
} FilePathReply;
extern CMTMessageTemplate FilePathReplyTemplate[];
typedef struct PasswordPromptReply {
CMInt32 resID;
char *promptReply;
} PasswordPromptReply;
extern CMTMessageTemplate PasswordPromptReplyTemplate[];
typedef struct SignTextRequest {
CMInt32 resID;
char *stringToSign;
char *hostName;
char *caOption;
CMInt32 numCAs;
char** caNames;
} SignTextRequest;
extern CMTMessageTemplate SignTextRequestTemplate[];
typedef struct GetLocalizedTextReply {
CMInt32 whichString;
char *localizedString;
} GetLocalizedTextReply;
extern CMTMessageTemplate GetLocalizedTextReplyTemplate[];
typedef struct ImportCertReply {
CMInt32 result;
CMInt32 resID;
} ImportCertReply;
extern CMTMessageTemplate ImportCertReplyTemplate[];
typedef struct PromptRequest {
CMInt32 resID;
char *prompt;
CMTItem clientContext;
} PromptRequest;
extern CMTMessageTemplate PromptRequestTemplate[];
typedef struct PromptReply {
CMInt32 resID;
CMBool cancel;
char *promptReply;
} PromptReply;
extern CMTMessageTemplate PromptReplyTemplate[];
typedef struct RedirectCompareReqeust {
CMTItem socketStatus1Data;
CMTItem socketStatus2Data;
} RedirectCompareRequest;
extern CMTMessageTemplate RedirectCompareRequestTemplate[];
typedef struct DecodeAndAddCRLRequest {
CMTItem derCrl;
CMUint32 type;
char *url;
} DecodeAndAddCRLRequest;
extern CMTMessageTemplate DecodeAndAddCRLRequestTemplate[];
typedef struct SecurityAdvisorRequest {
CMInt32 infoContext;
CMInt32 resID;
char * hostname;
char * senderAddr;
CMUint32 encryptedP7CInfo;
CMUint32 signedP7CInfo;
CMInt32 decodeError;
CMInt32 verifyError;
CMBool encryptthis;
CMBool signthis;
CMInt32 numRecipients;
char ** recipients;
} SecurityAdvisorRequest;
extern CMTMessageTemplate SecurityAdvisorRequestTemplate[];
/* "SecurityConfig" javascript related message templates */
typedef struct SCAddTempCertToPermDBRequest {
CMTItem certKey;
char* trustStr;
char* nickname;
} SCAddTempCertToPermDBRequest;
extern CMTMessageTemplate SCAddTempCertToPermDBRequestTemplate[];
typedef struct SCDeletePermCertsRequest {
CMTItem certKey;
CMBool deleteAll;
} SCDeletePermCertsRequest;
extern CMTMessageTemplate SCDeletePermCertsRequestTemplate[];
typedef struct TimeMessage {
CMInt32 year;
CMInt32 month;
CMInt32 day;
CMInt32 hour;
CMInt32 minute;
CMInt32 second;
} TimeMessage;
extern CMTMessageTemplate TimeMessageTemplate[];
typedef struct CertEnumElement {
char* name;
CMTItem certKey;
} CertEnumElement;
typedef struct SCCertIndexEnumReply {
int length;
CertEnumElement* list;
} SCCertIndexEnumReply;
extern CMTMessageTemplate SCCertIndexEnumReplyTemplate[];
/* Test message */
typedef struct TestListElement {
char * name;
char * value;
} TestListElement;
typedef struct TestList {
char *listName;
int numElements;
TestListElement *elements;
} TestList;
extern CMTMessageTemplate TestListTemplate[];
/* Preference-related structs */
typedef struct SetPrefElement {
char* key;
char* value;
CMInt32 type;
} SetPrefElement;
typedef struct SetPrefListMessage {
int length;
SetPrefElement* list;
} SetPrefListMessage;
extern CMTMessageTemplate SetPrefListMessageTemplate[];
typedef struct GetPrefElement {
char* key;
CMInt32 type;
} GetPrefElement;
typedef struct GetPrefListRequest {
int length;
GetPrefElement* list;
} GetPrefListRequest;
extern CMTMessageTemplate GetPrefListRequestTemplate[];
typedef struct GetCertExtension {
CMUint32 resID;
CMUint32 extension;
} GetCertExtension;
extern CMTMessageTemplate GetCertExtensionTemplate[];
typedef struct HTMLCertInfoRequest {
CMUint32 certID;
CMUint32 showImages;
CMUint32 showIssuer;
} HTMLCertInfoRequest;
extern CMTMessageTemplate HTMLCertInfoRequestTemplate[];
typedef struct EncryptRequestMessage
{
CMTItem keyid; /* May have length 0 for default */
CMTItem data;
CMTItem ctx; /* serialized void* ptr */
} EncryptRequestMessage;
extern CMTMessageTemplate EncryptRequestTemplate[];
typedef struct SingleItemMessage EncryptReplyMessage;
#define EncryptReplyTemplate SingleItemMessageTemplate
typedef struct DecryptRequestMessage
{
CMTItem data;
CMTItem ctx; /* serialized void* ptr */
} DecryptRequestMessage;
extern CMTMessageTemplate DecryptRequestTemplate[];
typedef struct SingleItemMessage DecryptReplyMessage;
#define DecryptReplyTemplate SingleItemMessageTemplate
#endif /* __MESSAGES_H__ */

View File

@@ -1,602 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include <string.h>
#include <assert.h>
#ifdef WIN32
#include <winsock.h>
#endif
#ifdef XP_MAC
#include "macsocket.h"
#endif
#include "newproto.h"
char SSMVersionString[] = "1.1";
CMT_Alloc_fn cmt_alloc = malloc;
CMT_Free_fn cmt_free = free;
#define ASSERT(x) assert(x)
#define CM_ntohl ntohl
#define CM_htonl htonl
/*************************************************************
*
* CMT_Init
*
*
************************************************************/
void
CMT_Init(CMT_Alloc_fn allocfn, CMT_Free_fn freefn)
{
cmt_alloc = allocfn;
cmt_free = freefn;
}
static CMTStatus
decode_int(unsigned char **curptr, void *dest, CMInt32 *remaining)
{
CMInt32 datalen = sizeof(CMInt32);
if (*remaining < datalen)
return CMTFailure;
*(CMInt32 *)dest = ntohl(**(CMInt32 **)curptr);
*remaining -= datalen;
*curptr += datalen;
return CMTSuccess;
}
static CMTStatus
decode_string(unsigned char **curptr, CMInt32 *len,
unsigned char **data, CMInt32 *remaining)
{
CMTStatus rv;
CMInt32 datalen;
rv = decode_int(curptr, len, remaining);
if (rv != CMTSuccess)
return CMTFailure;
/* NULL string */
if (*len == 0) {
*data = NULL;
goto done;
}
datalen = (*len + 3) & ~3;
if (*remaining < datalen)
return CMTFailure;
*data = (unsigned char *) cmt_alloc(*len + 1);
if (*data == NULL)
return CMTFailure;
memcpy(*data, *curptr, *len);
(*data)[*len] = 0;
*remaining -= datalen;
*curptr += datalen;
done:
return CMTSuccess;
}
/*************************************************************
* CMT_DecodeMessage
*
* Decode msg into dest as specified by tmpl.
*
************************************************************/
CMTStatus
CMT_DecodeMessage(CMTMessageTemplate *tmpl, void *dest, CMTItem *msg)
{
unsigned char *curptr, *destptr, *list;
void ** ptr;
CMInt32 remaining, len, choiceID = 0, listSize, listCount = 0;
CMBool inChoice = CM_FALSE, foundChoice = CM_FALSE, inList = CM_FALSE;
CMInt32 listItemSize = 0;
CMTStatus rv = CMTSuccess;
CMTMessageTemplate *startOfList, *p;
CMBool inStructList = CM_FALSE;
curptr = msg->data;
remaining = msg->len;
while(tmpl->type != CMT_DT_END) {
/* XXX Maybe this should be a more formal state machine? */
if (inChoice) {
if (tmpl->type == CMT_DT_END_CHOICE) {
if (!foundChoice)
goto loser;
inChoice = CM_FALSE;
foundChoice = CM_FALSE;
tmpl++;
continue;
}
if (choiceID != tmpl->choiceID) {
tmpl++;
continue; /* Not this option */
} else {
foundChoice = CM_TRUE;
}
}
if (inList) {
destptr = &list[listCount * listItemSize];
listCount++;
} else {
if (inStructList) {
destptr = tmpl->offset + list;
} else {
destptr = tmpl->offset + (unsigned char *)dest;
}
}
switch (tmpl->type) {
case CMT_DT_RID:
case CMT_DT_INT:
case CMT_DT_BOOL:
rv = decode_int(&curptr, destptr, &remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_STRING:
rv = decode_string(&curptr, &len, (unsigned char **)destptr,
&remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_ITEM:
rv = decode_string(&curptr, (long *) &((CMTItem *)destptr)->len,
&((CMTItem *)destptr)->data, &remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_LIST:
/* XXX This is too complicated */
rv = decode_int(&curptr, destptr, &remaining);
if (rv != CMTSuccess)
goto loser;
listSize = *(CMInt32 *)destptr;
tmpl++;
if (tmpl->type == CMT_DT_STRING) {
listItemSize = sizeof(unsigned char *);
} else if (tmpl->type == CMT_DT_ITEM) {
listItemSize = sizeof(CMTItem);
} else {
listItemSize = sizeof(CMInt32);
}
if (listSize == 0) {
list = NULL;
} else {
list = (unsigned char *) cmt_alloc(listSize * listItemSize);
}
*(void **)(tmpl->offset + (unsigned char *)dest) = list;
inList = CM_TRUE;
listCount = 0;
break;
case CMT_DT_STRUCT_LIST:
/* XXX This is too complicated */
rv = decode_int(&curptr, destptr, &remaining);
if (rv != CMTSuccess)
goto loser;
listSize = *(CMInt32 *)destptr;
tmpl++;
if (tmpl->type != CMT_DT_STRUCT_PTR) {
goto loser;
}
ptr = (void**)(tmpl->offset + (unsigned char *)dest);
startOfList = tmpl;
p = tmpl;
listItemSize = 0;
while (p->type != CMT_DT_END_STRUCT_LIST) {
if (p->type == CMT_DT_STRING) {
listItemSize += sizeof(unsigned char *);
} else if (p->type == CMT_DT_ITEM) {
listItemSize += sizeof(CMTItem);
} else if (p->type == CMT_DT_INT) {
listItemSize += sizeof(CMInt32);
}
p++;
}
if (listSize == 0) {
list = NULL;
} else {
list = (unsigned char *) cmt_alloc(listSize * listItemSize);
}
*ptr = list;
inStructList = CM_TRUE;
listCount = 0;
break;
case CMT_DT_END_STRUCT_LIST:
listCount++;
if (listCount == listSize) {
inStructList = CM_FALSE;
} else {
list += listItemSize;
tmpl = startOfList;
}
break;
case CMT_DT_CHOICE:
rv = decode_int(&curptr, destptr, &remaining);
if (rv != CMTSuccess)
goto loser;
choiceID = *(CMInt32 *)destptr;
inChoice = CM_TRUE;
foundChoice = CM_FALSE;
break;
case CMT_DT_END_CHOICE: /* Loop should exit before we see these. */
case CMT_DT_END:
default:
ASSERT(0);
break;
}
if (inList) {
if (listCount == listSize) {
inList = CM_FALSE;
tmpl++;
}
} else {
tmpl++;
}
}
loser:
/* Free the data buffer */
if (msg->data) {
cmt_free(msg->data);
msg->data = NULL;
}
return rv;
}
static CMTStatus
calc_msg_len(CMTMessageTemplate *tmpl, void *src, CMInt32 *len_out)
{
CMInt32 len = 0, choiceID = 0, listSize, listItemSize, listCount;
unsigned char *srcptr, *list;
CMBool inChoice = CM_FALSE, inList = CM_FALSE, foundChoice = CM_FALSE;
CMTMessageTemplate *startOfList, *p;
CMBool inStructList = CM_FALSE;
while(tmpl->type != CMT_DT_END) {
if (inChoice) {
if (tmpl->type == CMT_DT_END_CHOICE) {
if (!foundChoice)
goto loser;
inChoice = CM_FALSE;
foundChoice = CM_FALSE;
tmpl++;
continue;
}
if (choiceID != tmpl->choiceID) {
tmpl++;
continue; /* Not this option */
} else {
foundChoice = CM_TRUE;
}
}
if (inList) {
srcptr = &list[listCount * listItemSize];
listCount++;
} else if (inStructList) {
srcptr = tmpl->offset + list;
} else {
srcptr = tmpl->offset + (unsigned char *)src;
}
switch(tmpl->type) {
case CMT_DT_RID:
case CMT_DT_INT:
case CMT_DT_BOOL:
len += sizeof(CMInt32);
break;
case CMT_DT_STRING:
len += sizeof(CMInt32);
/* Non NULL string */
if (*(char**)srcptr) {
len += (strlen(*(char**)srcptr) + 4) & ~3;
}
break;
case CMT_DT_ITEM:
len += sizeof(CMInt32);
len += (((CMTItem *)srcptr)->len + 3) & ~3;
break;
case CMT_DT_LIST:
len += sizeof(CMInt32);
listSize = *(CMInt32 *)srcptr;
tmpl++;
if (tmpl->type == CMT_DT_STRING) {
listItemSize = sizeof(unsigned char *);
} else if (tmpl->type == CMT_DT_ITEM) {
listItemSize = sizeof(CMTItem);
} else {
listItemSize = sizeof(CMInt32);
}
list = *(unsigned char **)(tmpl->offset + (unsigned char *)src);
listCount = 0;
inList = CM_TRUE;
break;
case CMT_DT_STRUCT_LIST:
len += sizeof(CMInt32);
listSize = *(CMInt32 *)srcptr;
tmpl++;
if (tmpl->type != CMT_DT_STRUCT_PTR) {
goto loser;
}
list = *(unsigned char**)(tmpl->offset + (unsigned char*)src);
startOfList = tmpl;
p = tmpl;
listItemSize = 0;
while (p->type != CMT_DT_END_STRUCT_LIST) {
if (p->type == CMT_DT_STRING) {
listItemSize += sizeof(unsigned char *);
} else if (p->type == CMT_DT_ITEM) {
listItemSize += sizeof(CMTItem);
} else if (p->type == CMT_DT_INT) {
listItemSize += sizeof(CMInt32);
}
p++;
}
listCount = 0;
inStructList = CM_TRUE;
break;
case CMT_DT_END_STRUCT_LIST:
listCount++;
if (listCount == listSize) {
inStructList = CM_FALSE;
} else {
list += listItemSize;
tmpl = startOfList;
}
break;
case CMT_DT_CHOICE:
len += sizeof(CMInt32);
choiceID = *(CMInt32 *)srcptr;
inChoice = CM_TRUE;
foundChoice = CM_FALSE;
break;
case CMT_DT_END_CHOICE: /* Loop should exit before we see these. */
case CMT_DT_END:
default:
ASSERT(0);
break;
}
if (inList) {
if (listCount == listSize) {
inList = CM_FALSE;
tmpl++;
}
} else {
tmpl++;
}
}
*len_out = len;
return CMTSuccess;
loser:
return CMTFailure;
}
static CMTStatus
encode_int(unsigned char **curptr, void *src, CMInt32 *remaining)
{
CMInt32 datalen = sizeof(CMInt32);
if (*remaining < datalen)
return CMTFailure;
**(CMInt32 **)curptr = CM_htonl(*(CMInt32 *)src);
*remaining -= datalen;
*curptr += datalen;
return CMTSuccess;
}
static CMTStatus
encode_string(unsigned char **curptr, CMInt32 len,
unsigned char *data, CMInt32 *remaining)
{
CMTStatus rv;
CMInt32 datalen;
rv = encode_int(curptr, &len, remaining);
if (rv != CMTSuccess)
return CMTFailure;
/* NULL string */
if (len == 0) {
goto done;
}
datalen = (len + 3) & ~3;
if (*remaining < datalen)
return CMTFailure;
memcpy(*curptr, data, len);
*remaining -= datalen;
*curptr += datalen;
done:
return CMTSuccess;
}
/*************************************************************
* CMT_EncodeMessage
*
* Encode src into msg as specified by tmpl.
*
************************************************************/
CMTStatus
CMT_EncodeMessage(CMTMessageTemplate *tmpl, CMTItem *msg, void *src)
{
CMInt32 choiceID = 0, listSize, listItemSize, listCount, remaining;
unsigned char *srcptr, *curptr, *list;
CMBool inChoice = CM_FALSE, inList = CM_FALSE, foundChoice = CM_FALSE;
CMTStatus rv = CMTSuccess;
CMTMessageTemplate *startOfList, *p;
CMBool inStructList = CM_FALSE;
rv = calc_msg_len(tmpl, src, (long *) &msg->len);
if (rv != CMTSuccess)
goto loser;
curptr = msg->data = (unsigned char *) cmt_alloc(msg->len);
if(msg->data == NULL)
goto loser;
remaining = msg->len;
while(tmpl->type != CMT_DT_END) {
if (inChoice) {
if (tmpl->type == CMT_DT_END_CHOICE) {
if (!foundChoice)
goto loser;
inChoice = CM_FALSE;
foundChoice = CM_FALSE;
tmpl++;
continue;
}
if (choiceID != tmpl->choiceID) {
tmpl++;
continue; /* Not this option */
} else {
foundChoice = CM_TRUE;
}
}
if (inList) {
srcptr = &list[listCount * listItemSize];
listCount++;
} else {
if (inStructList) {
srcptr = tmpl->offset + list;
} else {
srcptr = tmpl->offset + (unsigned char *)src;
}
}
switch(tmpl->type) {
case CMT_DT_RID:
case CMT_DT_INT:
case CMT_DT_BOOL:
rv = encode_int(&curptr, srcptr, &remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_STRING:
if (*(char**)srcptr) {
/* Non NULL string */
rv = encode_string(&curptr, (long) strlen(*(char**)srcptr),
*(unsigned char**)srcptr, &remaining);
} else {
/* NULL string */
rv = encode_string(&curptr, 0L, *(unsigned char**)srcptr, &remaining);
}
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_ITEM:
rv = encode_string(&curptr, ((CMTItem *)srcptr)->len,
((CMTItem *)srcptr)->data, &remaining);
if (rv != CMTSuccess)
goto loser;
break;
case CMT_DT_LIST:
rv = encode_int(&curptr, srcptr, &remaining);
if (rv != CMTSuccess)
goto loser;
listSize = *(CMInt32 *)srcptr;
tmpl++;
if (tmpl->type == CMT_DT_STRING) {
listItemSize = sizeof(unsigned char *);
} else if (tmpl->type == CMT_DT_ITEM) {
listItemSize = sizeof(CMTItem);
} else {
listItemSize = sizeof(CMInt32);
}
list = *(unsigned char **)(tmpl->offset + (unsigned char *)src);
listCount = 0;
inList = CM_TRUE;
break;
case CMT_DT_STRUCT_LIST:
rv = encode_int(&curptr, srcptr, &remaining);
if (rv != CMTSuccess)
goto loser;
listSize = *(CMInt32 *)srcptr;
tmpl++;
if (tmpl->type != CMT_DT_STRUCT_PTR) {
goto loser;
}
list = *(unsigned char**)(tmpl->offset + (unsigned char*)src);
startOfList = tmpl;
p = tmpl;
listItemSize = 0;
while (p->type != CMT_DT_END_STRUCT_LIST) {
if (p->type == CMT_DT_STRING) {
listItemSize += sizeof(unsigned char *);
} else if (p->type == CMT_DT_ITEM) {
listItemSize += sizeof(CMTItem);
} else if (p->type == CMT_DT_INT) {
listItemSize += sizeof(CMInt32);
}
p++;
}
listCount = 0;
inStructList = CM_TRUE;
break;
case CMT_DT_END_STRUCT_LIST:
listCount++;
if (listCount == listSize) {
inStructList = CM_FALSE;
} else {
list += listItemSize;
tmpl = startOfList;
}
break;
case CMT_DT_CHOICE:
rv = encode_int(&curptr, srcptr, &remaining);
if (rv != CMTSuccess)
goto loser;
choiceID = *(CMInt32 *)srcptr;
inChoice = CM_TRUE;
foundChoice = CM_FALSE;
break;
case CMT_DT_END_CHOICE: /* Loop should exit before we see these. */
case CMT_DT_END:
default:
ASSERT(0);
break;
}
if (inList) {
if (listCount == listSize) {
inList = CM_FALSE;
tmpl++;
}
} else {
tmpl++;
}
}
return CMTSuccess;
loser:
return CMTFailure;
}

View File

@@ -1,102 +0,0 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef __NEWPROTO_H__
#define __NEWPROTO_H__
#include <stdlib.h>
#include "ssmdefs.h"
typedef enum CMTDataType {
CMT_DT_END,
CMT_DT_RID,
CMT_DT_INT,
CMT_DT_BOOL,
CMT_DT_STRING,
CMT_DT_ITEM,
CMT_DT_LIST,
CMT_DT_CHOICE,
CMT_DT_END_CHOICE,
CMT_DT_STRUCT_LIST,
CMT_DT_END_STRUCT_LIST,
CMT_DT_STRUCT_PTR
} CMTDataType;
typedef struct CMTMessageTemplate {
CMTDataType type;
CMUint32 offset;
CMInt32 validator;
CMInt32 choiceID;
} CMTMessageTemplate;
typedef struct CMTMessageHeader {
CMInt32 type;
CMInt32 len;
} CMTMessageHeader;
typedef void *(* CMT_Alloc_fn) (size_t size);
typedef void (* CMT_Free_fn)(void * ptr);
extern CMT_Alloc_fn cmt_alloc;
extern CMT_Free_fn cmt_free;
/*************************************************************
*
* CMT_Init
*
*
************************************************************/
void
CMT_Init(CMT_Alloc_fn allocfn, CMT_Free_fn freefn);
/*************************************************************
* CMT_DecodeMessage
*
* Decode msg into dest as specified by tmpl.
*
************************************************************/
CMTStatus
CMT_DecodeMessage(CMTMessageTemplate *tmpl, void *dest, CMTItem *msg);
/*************************************************************
* CMT_EncodeMessage
*
* Encode src into msg as specified by tmpl.
*
************************************************************/
CMTStatus
CMT_EncodeMessage(CMTMessageTemplate *tmpl, CMTItem *msg, void *src);
#endif /* __NEWPROTO_H__ */

View File

@@ -1,187 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/* SAMPLE CODE
** Illustrates use of SSMObscure object methods.
**
** Author: Nelson Bolyard June 1999
*/
#include <stdio.h>
#include "obscure.h"
/* On error, returns -1.
** On success, returns non-negative number of unobscured bytes in buf
int
RecvInitObscureData(int fd, SSMObscureObject * obj, void * buf, int bufSize )
{
SSMObscureBool done = 0;
do {
int cc;
int rv;
cc = read(fd, buf, bufSize);
if (cc <= 0)
return -1;
rv = SSMObscure_RecvInit(obj, buf, cc, &done);
} while (!done);
return rv;
}
/* returns -1 on error, 0 on success. */
int
SendInitObscureData(int fd, SSMObscureObject * obj)
{
unsigned char * initBuf = NULL;
int rv = -1;
do {
int bufLen;
int len;
int cc;
bufLen = SSMObscure_SendInit(obj, NULL);
if (bufLen <= 0)
break;
initBuf = malloc(bufLen);
if (!initBuf)
break;
len = SSMObscure_SendInit(obj, initBuf);
if (len != bufLen)
break;
cc = write(fd, initBuf, len);
/* Note, this code assumes a blocking socket,
** and hence doesn't deal with short writes.
*/
if (cc < len)
break;
rv = 0;
} while (0);
if (initBuf) {
free(initBuf);
initBuf = NULL;
}
return rv;
}
/* This is like write, but it obscures the data first. */
/* This code assumes a blocking socket, and so it doesn't handle short
** writes.
*/
int
obscuredWrite(SSMObscureObject * obj, int fd, void * buf, int len)
{
int rv;
int cc;
cc = SSMObscure_Send(obj, buf, len);
if (cc <= 0)
return cc;
rv = write(fd, buf, cc);
ASSERT(rv == cc || rv < 0);
return rv;
}
/* This is like read, but it unobscures the data after reading it. */
int
obscuredRead(SSMObscureObject * obj, int fd, void * buf, int len)
{
int rv;
int cc;
do {
cc = read(fd, buf, len);
if (cc <= 0)
return cc;
rv = SSMObscure_Recv(obj, buf, len);
} while (rv == 0);
return rv;
}
SSMObscureObject * sobj;
unsigned char buf[8192];
/* Call this with fd for socket that has just been accepted.
** returns -1 on error,
** On success, returns non-negative number of bytes received in buf.
*/
int
InitClientObscureObject(int fd)
{
int rv;
sobj = SSMObscure_Create(0);
if (!sobj)
return -1;
rv = SendInitObscureData(fd, sobj);
if (rv < 0)
return rv;
rv = RecvInitObscureData(fd, sobj, buf, sizeof buf);
return rv;
}
/* Call this with fd for socket that has just been connected.
** returns -1 on error,
** On success, returns non-negative number of bytes received in buf.
*/
int
InitServerObscureObject(int fd)
{
int cc;
sobj = SSMObscure_Create(1);
if (!sobj)
return -1;
cc = RecvInitObscureData(fd, sobj, buf, sizeof buf);
if (cc < 0)
return cc;
rv = SendInitObscureData(fd, sobj);
if (rv < 0)
return rv;
return cc;
}

View File

@@ -1,136 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include <stdlib.h>
#include "obspriv.h"
#include "newproto.h"
/*
** Create a new Obscuring object
*/
SSMObscureObject *
SSMObscure_Create(SSMObscureBool IsServer)
{
SSMObscureObject * obj;
void * priv;
obj = (SSMObscureObject *) cmt_alloc(sizeof *obj);
if (!obj)
return obj;
/* This needs to be a little more elegant */
priv = SSMObscure_InitPrivate(obj, IsServer);
if (!priv) {
cmt_free(obj);
return NULL;
}
obj->privData = priv;
return obj;
}
/* Prepare initial buffer with initial message to send to other side to
** establish cryptographic * synchronization.
**
** If buf is NULL, function returns the size of the buffer that
** the caller needs to allocate for sending the initial message.
**
** If buf is non-null, function returns the number of bytes of data filled
** into buf, the amount that the caller should then send to the other side.
**
*/
int
SSMObscure_SendInit( SSMObscureObject * obj, void * buf)
{
int rv;
rv = obj->sendInit(obj->privData, buf);
return rv;
}
/*
** Obscure "len" bytes in "buf" before sending it.
*/
int
SSMObscure_Send( SSMObscureObject * obj,
void * buf,
unsigned int len)
{
int rv;
rv = obj->send(obj->privData, buf, len);
return rv;
}
/*
** UnObscure "len" bytes in "buf" after receiving it.
** This function may absorb some or all of the received bytes, leaving
** fewer bytes (possibly none) in the buffer for the application to use
** than were in the buffer when the function was called.
** Function returns the number of bytes of unobscured data remaining in
** buf. Zero means all data was used internally and no data remains
** for application use. Negative number means error occurred.
*/
int
SSMObscure_Recv( SSMObscureObject * obj,
void * buf,
unsigned int len)
{
int rv;
rv = obj->recv(obj->privData, buf, len);
return rv;
}
/* like _Recv, but returns a flag telling when all initialization info has
** been received.
*/
int
SSMObscure_RecvInit( SSMObscureObject * obj,
void * buf,
unsigned int len,
SSMObscureBool * done)
{
int rv;
rv = obj->recvInit(obj->privData, buf, len, done);
return rv;
}
/*
** Destroy the Obscure Object
*/
int
SSMObscure_Destroy(SSMObscureObject * obj)
{
int rv;
rv = obj->destroy(obj->privData);
cmt_free(obj);
return rv;
}

View File

@@ -1,98 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef __obscure_h__
#define __obscure_h__ 1
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned char SSMObscureBool;
typedef struct SSMObscureObjectStr SSMObscureObject;
/*
** Create a new Obscuring object
*/
extern SSMObscureObject * SSMObscure_Create(SSMObscureBool IsServer);
/* Prepare initial buffer with initial message to send to other side to
** establish cryptographic * synchronization.
**
** If buf is NULL, function returns the size of the buffer that
** the caller needs to allocate for sending the initial message.
**
** If buf is non-null, function returns the number of bytes of data filled
** into buf, the amount that the caller should then send to the other side.
**
*/
extern int SSMObscure_SendInit( SSMObscureObject * obj,
void * buf);
/*
** Obscure "len" bytes in "buf" before sending it.
*/
extern int SSMObscure_Send( SSMObscureObject * obj,
void * buf,
unsigned int len);
/*
** UnObscure "len" bytes in "buf" after receiving it.
** This function may absorb some or all of the received bytes, leaving
** fewer bytes (possibly none) in the buffer for the application to use
** than were in the buffer when the function was called.
** Function returns the number of bytes of unobscured data remaining in
** buf. Zero means all data was used internally and no data remains
** for application use. Negative number means error occurred.
*/
extern int SSMObscure_Recv( SSMObscureObject * obj,
void * buf,
unsigned int len);
/* like _Recv, but returns a flag telling when all initialization info has
** been received.
*/
extern int SSMObscure_RecvInit( SSMObscureObject * obj,
void * buf,
unsigned int len,
SSMObscureBool * done);
/*
** Destroy the Obscure Object
*/
extern int SSMObscure_Destroy(SSMObscureObject * obj);
#ifdef __cplusplus
}
#endif
#endif /* __obscure_h__ */

View File

@@ -1,115 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "obspriv.h"
#include "newproto.h"
#include <string.h>
#include <assert.h>
#include <time.h>
/*
Originally this code was used to obscure the control messages
traveling between processes. With the relaxation of export rules,
this whole step is no longer necessary, and is included for
informational purposes only. (We need to finish removing the
obscuring code.)
*/
struct obscureNOPStr {
SSMObscureObject * obj;
};
typedef struct obscureNOPStr obscureV1;
static int
ssmObscure_Destroy(void * privData)
{
obscureV1 * priv = (obscureV1 *)privData;
memset(priv, 0, sizeof *priv);
cmt_free(priv);
return 0;
}
static int
ssmObscure_Send(void * privData, void * buf, unsigned int len)
{
/* obscureV1 * priv = (obscureV1 *)privData;*/
/* NOP */
return len;
}
static int
ssmObscure_Recv(void * privData, void * buf, unsigned int len)
{
/*obscureV1 * priv = (obscureV1 *)privData;*/
/* NOP */
return len;
}
static int
ssmObscure_SendInit(void * privData, void * buf)
{
/*obscureV1 * priv = (obscureV1 *)privData;*/
return 0;
}
static int
ssmObscure_RecvInit(void * privData, void * buf, unsigned int len,
SSMObscureBool * pDone)
{
return 0;
}
static void *
ssmObscure_InitPrivate(SSMObscureObject * obj, SSMObscureBool IsServer)
{
obscureV1 * priv = (obscureV1 *) cmt_alloc(sizeof (obscureV1));
if (!priv)
return NULL;
priv->obj = obj;
obj->privData = (void *)priv;
obj->destroy = ssmObscure_Destroy;
obj->send = ssmObscure_Send;
obj->recv = ssmObscure_Recv;
obj->sendInit = ssmObscure_SendInit;
obj->recvInit = ssmObscure_RecvInit;
return priv;
}
obsInitFn SSMObscure_InitPrivate = ssmObscure_InitPrivate;

View File

@@ -1,63 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "obscure.h"
typedef void * (* obsInitFn) (SSMObscureObject * instance,
SSMObscureBool IsServer);
typedef int (* obsDestroyFn) (void * priv);
typedef int (* obsSendFn) (void * priv, void * buf, unsigned int len);
typedef int (* obsRecvFn) (void * priv, void * buf, unsigned int len);
typedef int (* obsSendInitFn)(void * priv, void * buf);
typedef int (* obsRecvInitFn)(void * priv, void * buf, unsigned int len,
SSMObscureBool * done);
struct SSMObscureObjectStr {
void * privData;
obsDestroyFn destroy;
obsSendFn send;
obsRecvFn recv;
obsSendInitFn sendInit;
obsRecvInitFn recvInit;
};
/* This is common to the beginning of all versions of the obscuring protocol */
struct SSMInitMsgHdrStr {
short version;
short length;
};
typedef struct SSMInitMsgHdrStr SSMInitMsgHdr;
extern obsInitFn SSMObscure_InitPrivate;

View File

@@ -1,141 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/*
protocol.h - Definitions of various items to support the PSM protocol.
*/
#ifndef __PROTOCOL_H__
#define __PROTOCOL_H__
#include "rsrcids.h"
#define SSMPRStatus SSMStatus
#define SSMPR_SUCCESS SSM_SUCCESS
#define SSMPR_FAILURE SSM_FAILURE
#define SSMPR_INVALID_ARGUMENT_ERROR PR_INVALID_ARGUMENT_ERROR
#define SSMPR_OUT_OF_MEMORY_ERROR PR_OUT_OF_MEMORY_ERROR
#define SSMPRInt32 PRInt32
#define SSMPRUint32 PRUint32
#define SSMPR_ntohl PR_ntohl
#define SSMPR_htonl PR_htonl
#define SSMPORT_Free PORT_Free
#define SSMPORT_ZAlloc PORT_ZAlloc
#define SSMPR_SetError PR_SetError
#define SSMPR_GetError PR_GetError
#define SSMPORT_SetError PORT_SetError
#define SSMPORT_GetError PORT_GetError
/*
Current version of PSM protocol.
Increment this value when the protocol changes.
*/
#define SSMSTRING_PADDED_LENGTH(x) ((((x)+3)/4)*4)
#define SSMPORT_ZNEW(type) (type*)SSMPORT_ZAlloc(sizeof(type))
#define SSMPORT_ZNewArray(type,size) (type*)SSMPORT_ZAlloc(sizeof(type)*(size))
/* Various message structs */
struct _SSMHelloRequest {
CMUint32 m_version; /* Protocol version supported by client */
struct _SSMString m_profileName; /* Name of user profile (where to find
certs etc) */
};
struct _SSMHelloReply {
CMInt32 m_result; /* Error, if any, which occurred
(0 == success) */
CMUint32 m_version; /* Protocol version supported by PSM */
struct _SSMString m_nonce; /* Session nonce -- must be written to data channels */
};
struct _SSMRequestSSLDataConnection
{
CMUint32 m_flags; /* Flags to indicate to SSM what to do with
the connection */
CMUint32 m_port; /* Port number to connect to */
struct _SSMString m_hostIP; /* IP address of final target machine (not proxy) */
/* struct _SSMString m_hostName; Host name of target machine (for server auth) -- not accessed directly */
};
struct _SSMReplySSLDataConnection {
CMInt32 m_result; /* Error, if any, which occurred (0 == success) */
CMUint32 m_connectionID; /* Connection ID of newly opened channel */
CMUint32 m_port; /* Port number to which to connect on PSM */
};
struct _SSMRequestSecurityStatus {
CMUint32 m_connectionID; /* ID of connection of which to stat */
};
struct _SSMReplySecurityStatus {
CMInt32 m_result; /* Error, if any, which occurred (0 == success) */
CMUint32 m_keySize; /* Key size */
CMUint32 m_secretKeySize; /* Secret key size */
struct _SSMString m_cipherName; /* Name of cipher in use */
/* SSMString m_certificate; -- DER encoded cert
We do not access this as a field, we have to skip over m_cipherName */
};
/*
Use this macro to jump over strings.
For example, if you wanted to access m_certificate above,
use a line like the following:
char *ptr = &(reply->m_cipherName) + SSM_SIZEOF_STRING(reply->m_cipherName);
*/
#define SSM_SIZEOF_STRING(str) (SSMSTRING_PADDED_LENGTH(PR_ntohl((str).m_length)) + sizeof(CMUint32))
typedef struct _SSMHelloRequest SSMHelloRequest;
typedef struct _SSMHelloReply SSMHelloReply;
typedef struct _SSMRequestSSLDataConnection SSMRequestSSLDataConnection;
typedef struct _SSMReplySSLDataConnection SSMReplySSLDataConnection;
typedef struct _SSMRequestSecurityStatus SSMRequestSecurityStatus;
typedef struct _SSMReplySecurityStatus SSMReplySecurityStatus;
/*
Functions to convert between an SSMString and a C string.
Return values are allocated using PR_Malloc (which means that
SSMPR_Free must be used to free up the memory after use).
*/
CMTStatus SSM_StringToSSMString(SSMString ** ssmString, int len, char * string);
CMTStatus SSM_SSMStringToString(char ** string,int *len, SSMString * ssmString);
#endif /* __PROTOCOL_H__ */

File diff suppressed because it is too large Load Diff

View File

@@ -1,359 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#ifndef __PROTOCOLF_H__
#define __PROTOCOLF_H__
/*************************************************************************
* For each type of message, parse and pack function is provided.
*
* Parse functions accept a ptr to the "blob" of data received from the
* network and fill in fields of the message, numbers in host-order, strings
* as C-style NULL-terminated strings. Return SSMPRStatus.
*
* Pack functions take all the info to construct a message and fill in a
* ptr to the "blob" of data to be sent. Return length of the data blob, or
* a zero in case of an error
*
* All functions set NSPR errors when necessary.
************************************************************************/
#include "protocol.h"
#include "cert.h"
SSMPRStatus SSM_ParseHelloRequest(void * helloRequest,
SSMPRUint32 * version,
PRBool * doesUI,
PRInt32 * policyType,
SSMPRUint32 * profileLen,
char ** profile);
SSMPRInt32 SSM_PackHelloReply(void ** helloReply, SSMPRInt32 result,
SSMPRUint32 sessionID, SSMPRUint32 version,
SSMPRUint32 httpPort, SSMPRUint32 nonceLen,
char * nonce, SSMPolicyType policy);
/* Parse data connections requests */
SSMPRStatus SSM_ParseSSLDataConnectionRequest(void *sslRequest,
SSMPRUint32 * flags,
SSMPRUint32 * port,
SSMPRUint32 * hostIPLen,
char ** hostIP,
SSMPRUint32 * hostNameLen,
char ** hostName);
SSMPRStatus SSM_ParseHashStreamRequest(void * hashStreamRequest,
SSMPRUint32 * type);
SSMPRStatus SSM_ParseP7EncodeConnectionRequest(void *request,
SSMPRUint32 *ciRID);
/* Messages to initiate PKCS7 data connection */
/* PKCS7DecodeRequest message has no data */
/* Single data connection reply */
SSMPRInt32 SSM_PackDataConnectionReply(void ** sslReply,
SSMPRInt32 result,
SSMPRUint32 connID,
SSMPRUint32 port);
SSMPRStatus SSM_ParseSSLSocketStatusRequest(void * statusRequest,
SSMPRUint32 * connID);
SSMPRInt32 SSM_PackSSLSocketStatusReply(void ** statusReply,
SSMPRInt32 result,
SSMPRUint32 resourceID);
/*
* UI event is an asynchroneous message sent from PSM server to the client
* NOTE: (context) is the actual context pointer, it is NOT a ptr-to-ptr.
* The value of (context) is copied into the packet.
*/
SSMPRInt32 SSM_PackUIEvent(void ** eventRequest, SSMPRUint32 resourceID,
SSMPRUint32 width, SSMPRUint32 height,
SSMPRUint32 urlLen, char * url);
SSMPRInt32 SSM_PackTaskCompletedEvent(void **event, SSMPRUint32 resourceID,
SSMPRUint32 numTasks, SSMPRUint32 result);
/* Verify raw signature */
SSMPRStatus SSM_ParseVerifyRawSigRequest(void * verifyRawSigRequest,
SSMPRUint32 * algorithmID,
SSMPRUint32 * paramsLen,
unsigned char ** params,
SSMPRUint32 * pubKeyLen,
unsigned char ** pubKey,
SSMPRUint32 * hashLen,
unsigned char ** hash,
SSMPRUint32 * signatureLen,
unsigned char ** signature);
SSMPRInt32 SSM_PackVerifyRawSigReply(void ** verifyRawSigReply,
SSMPRInt32 result);
/* Verify detached signature */
SSMPRStatus SSM_ParseVerifyDetachedSigRequest(void * request,
SSMPRInt32 * pkcs7ContentID,
SSMPRInt32 * certUsage,
SSMPRInt32 * hashAlgID,
SSMPRUint32 * keepCert,
SSMPRUint32 * digestLen,
unsigned char ** hash);
SSMPRInt32 SSM_PackVerifyDetachedSigReply(void ** verifyDetachedSigReply,
SSMPRInt32 result);
/* PKCS#7 functions */
SSMPRStatus SSM_ParseCreateSignedRequest(void *request,
SSMPRInt32 *scertRID,
SSMPRInt32 *ecertRID,
SSMPRUint32 *dig_alg,
SECItem **digest);
SSMPRInt32 SSM_PackCreateSignedReply(void **reply, SSMPRInt32 ciRID,
SSMPRUint32 result);
SSMPRStatus SSM_ParseCreateEncryptedRequest(void *request,
SSMPRInt32 *scertRID,
SSMPRInt32 *nrcerts,
SSMPRInt32 **rcertRIDs);
SSMPRInt32 SSM_PackCreateEncryptedReply(void **reply, SSMPRInt32 ciRID,
SSMPRUint32 result);
/* Resource functions */
SSMPRStatus SSM_ParseCreateResourceRequest(void *request,
SSMPRUint32 *type,
unsigned char **params,
SSMPRUint32 *paramLen);
SSMPRStatus SSM_PackCreateResourceReply(void **reply, SSMPRStatus rv,
SSMPRUint32 resID);
SSMPRStatus SSM_ParseGetAttribRequest(void * getAttribRequest,
SSMPRUint32 * resourceID,
SSMPRUint32 * fieldID);
void SSM_DestroyAttrValue(SSMAttributeValue *value, PRBool freeit);
SSMPRInt32 SSM_PackGetAttribReply(void **getAttribReply,
SSMPRInt32 result,
SSMAttributeValue *value);
SSMPRStatus SSM_ParseSetAttribRequest(SECItem *msg,
SSMPRInt32 *resourceID,
SSMPRInt32 *fieldID,
SSMAttributeValue *value);
/* Currently, there is no need for a pack version. There is nothing to send
* back except for the notice that the operation was successful.
*/
/* Pickle and unpickle resources. */
SSMPRStatus SSM_ParsePickleResourceRequest(void * pickleResourceRequest,
SSMPRUint32 * resourceID);
SSMPRInt32 SSM_PackPickleResourceReply(void ** pickleResourceReply,
SSMPRInt32 result,
SSMPRUint32 resourceLen,
void * resource);
SSMPRStatus SSM_ParseUnpickleResourceRequest(void * unpickleResourceRequest,
SSMPRUint32 blobSize,
SSMPRUint32 * resourceType,
SSMPRUint32 * resourceLen,
void ** resource);
SSMPRInt32 SSM_PackUnpickleResourceReply(void ** unpickleResourceReply,
SSMPRInt32 result,
SSMPRUint32 resourceID);
/* Destroy resource */
SSMPRStatus SSM_ParseDestroyResourceRequest(void * destroyResourceRequest,
SSMPRUint32 * resourceID,
SSMPRUint32 * resourceType);
SSMPRInt32 SSM_PackDestroyResourceReply(void ** destroyResourceReply,
SSMPRInt32 result);
/* Duplicate resource */
SSMPRStatus SSM_ParseDuplicateResourceRequest(void * request,
SSMPRUint32 * resourceID);
SSMPRInt32 SSM_PackDuplicateResourceReply(void ** reply, SSMPRInt32 result,
SSMPRUint32 resID);
/* Cert actions */
typedef struct MatchUserCertRequestData {
PRUint32 certType;
PRInt32 numCANames;
char ** caNames;
} MatchUserCertRequestData;
typedef struct SSMCertList {
PRCList certs;
PRInt32 count;
} SSMCertList;
typedef struct SSMCertListElement {
PRCList links;
PRUint32 certResID;
} SSMCertListElement;
#define SSM_CERT_LIST_ELEMENT_PTR(_q) (SSMCertListElement*)(_q);
SSMPRStatus SSM_ParseVerifyCertRequest(void * verifyCertRequest,
SSMPRUint32 * resourceID,
SSMPRInt32 * certUsage);
SSMPRInt32 SSM_PackVerifyCertReply(void ** verifyCertReply,
SSMPRInt32 result);
SSMPRStatus SSM_ParseImportCertRequest(void * importCertRequest,
SSMPRUint32 * blobLen,
void ** certBlob);
SSMPRInt32 SSM_PackImportCertReply(void ** importCertReply, SSMPRInt32 result,
SSMPRUint32 resourceID);
PRStatus SSM_ParseFindCertByNicknameRequest(void *request, char ** nickname);
PRInt32 SSM_PackFindCertByNicknameReply(void ** reply, PRUint32 resourceID);
PRStatus SSM_ParseFindCertByKeyRequest(void *request, SECItem ** key);
PRInt32 SSM_PackFindCertByKeyReply(void ** reply, PRUint32 resourceID);
PRStatus SSM_ParseFindCertByEmailAddrRequest(void *request, char ** emailAddr);
PRInt32 SSM_PackFindCertByEmailAddrReply(void ** reply, PRUint32 resourceID);
PRStatus SSM_ParseAddTempCertToDBRequest(void *request, PRUint32 *resourceID, char ** nickname, PRInt32 *ssl, PRInt32 *email, PRInt32 *objectSigning);
PRInt32 SSM_PackAddTempCertToDBReply(void ** reply);
PRStatus SSM_ParseMatchUserCertRequest(void *request, MatchUserCertRequestData** data);
PRInt32 SSM_PackMatchUserCertReply(void **reply, SSMCertList * certList);
SSMPRInt32 SSM_PackErrorMessage(void ** errorReply, SSMPRInt32 result);
/* PKCS11 actions */
SSMPRStatus SSM_ParseKeyPairGenRequest(void *keyPairGenRequest,
SSMPRInt32 requestLen,
SSMPRUint32 *keyPairCtxtID,
SSMPRUint32 *genMechanism,
SSMPRUint32 *keySize,
unsigned char **params,
SSMPRUint32 *paramLen);
SSMPRInt32 SSM_PackKeyPairGenResponse(void ** keyPairGenResponse,
SSMPRUint32 keyPairId);
PRStatus
SSM_ParseFinishKeyGenRequest(void *finishKeyGenRequest,
PRInt32 requestLen,
PRInt32 *keyGenContext);
/* CMMF/CRMF Actions */
SSMPRStatus SSM_ParseCreateCRMFReqRequest(void *crmfReqRequest,
SSMPRInt32 requestLen,
SSMPRUint32 *keyPairId);
SSMPRInt32 SSM_PackCreateCRMFReqReply(void **crmfReqReply,
SSMPRUint32 crmfReqId);
SSMPRStatus SSM_ParseEncodeCRMFReqRequest(void *encodeReq,
SSMPRInt32 requestLen,
SSMPRUint32 **crmfReqId,
SSMPRInt32 *numRequests);
SSMPRInt32 SSM_PackEncodeCRMFReqReply(void **encodeReply,
char *crmfDER,
SSMPRUint32 derLen);
SSMPRStatus SSM_ParseCMMFCertResponse(void *encodedRes,
SSMPRInt32 encodeLen,
char **nickname,
char **base64Der,
PRBool *doBackup);
PRStatus SSM_ParsePOPChallengeRequest(void *challenge,
PRInt32 len,
char **responseString);
PRInt32 SSM_PackPOPChallengeResponse(void **response,
char *responseString,
PRInt32 responseStringLen);
PRInt32 SSM_PackPasswdRequest(void ** passwdRequest, PRInt32 tokenID,
char * prompt, PRInt32 promptLen);
PRStatus SSM_ParsePasswordReply(void * passwdReply, PRInt32 * result,
PRInt32 * tokenID,
char ** passwd, PRInt32 * passwdLen);
/* Sign Text Actions */
typedef struct {
char *stringToSign;
char *hostName;
char *caOption;
PRInt32 numCAs;
char **caNames;
} signTextRequestData;
PRStatus SSM_ParseSignTextRequest(void* signTextRequest, PRInt32 len, PRUint32* resID, signTextRequestData ** data);
PRStatus SSM_ParseGetLocalizedTextRequest(void *data,
SSMLocalizedString *whichString);
PRInt32 SSM_PackGetLocalizedTextResponse(void **data,
SSMLocalizedString whichString,
char *retString);
PRStatus SSM_ParseAddNewSecurityModuleRequest(void *data,
char **moduleName,
char **libraryPath,
unsigned long *pubMechFlags,
unsigned long *pubCipherFlags);
PRInt32 SSM_PackAddNewModuleResponse(void **data, PRInt32 rv);
PRStatus SSM_ParseDeleteSecurityModuleRequest(void *data, char **moduleName);
PRInt32 SSM_PackDeleteModuleResponse(void **data, PRInt32 moduleType);
PRInt32 SSM_PackFilePathRequest(void **data, PRInt32 resID, char *prompt,
PRBool shouldFileExist, char *fileSuffix);
PRStatus SSM_ParseFilePathReply(void *message, char **filePath,
PRInt32 *rid);
PRInt32 SSM_PackPromptRequestEvent(void **data, PRInt32 resID, char *prompt);
PRStatus SSM_ParsePasswordPromptReply(void *data, PRInt32 *resID,
char **reply);
/* messages for importing certs *the traditional way* */
PRInt32 SSM_PackDecodeCertReply(void ** data, PRInt32 certID);
PRStatus SSM_ParseDecodeCertRequest(void * data, PRInt32 * len,
char ** buffer);
PRStatus SSM_ParseGetKeyChoiceListRequest(void * data, PRUint32 dataLen,
char ** type, PRUint32 *typeLen,
char ** pqgString, PRUint32 *pqgLen);
PRInt32 SSM_PackGetKeyChoiceListReply(void **data, char ** list);
PRStatus SSM_ParseGenKeyOldStyleRequest(void * data, PRUint32 datalen,
char ** choiceString,
char ** challenge,
char ** typeString,
char ** pqgString);
PRInt32 SSM_PackGenKeyOldStyleReply(void ** data, char * keydata);
PRStatus SSM_ParseDecodeAndCreateTempCertRequest(void * data,
char ** certbuf, PRUint32 * certlen, int * certClass);
#endif /*PROTOCOLF_H_*/

View File

@@ -1,74 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/*****************************************************************************
*
*
*
*****************************************************************************
*/
#ifndef NULL
#define NULL 0x00000000
#endif
#define SSMPR_BYTES_PER_INT 4
#define SSMPR_BYTES_PER_LONG 4
/******************************************************************
* No NSPR - define all the SSMPR values and functions here
******************************************************************
*/
#define SSMPRStatus PRStatus
#define SSMPR_SUCCESS PR_SUCCESS
#define SSMPR_FAILURE PR_FAILURE
#define SSMPR_INVALID_ARGUMENT_ERROR PR_INVALID_ARGUMENT_ERROR
#define SSMPR_OUT_OF_MEMORY_ERROR PR_OUT_OF_MEMORY_ERROR
#define SSMPRInt32 PRInt32
#define SSMPRUint32 PRUint32
#define SSMPR_ntohl PR_ntohl
#define SSMPR_htonl PR_htonl
#define SSMPORT_Free PORT_Free
#define SSMPORT_ZAlloc PORT_ZAlloc
#define SSMPR_SetError PR_SetError
#define SSMPR_GetError PR_GetError
#define SSMPORT_SetError PORT_SetError
#define SSMPORT_GetError PORT_GetError

View File

@@ -1,49 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/*************************************************************************
*
* PSM portable run-time. (Used when NSPR20 is not available.)
*
*************************************************************************
*/
SSMPRInt32 ssmprErrno;
void SSMPORT_SetError(SSMPRInt32 errorcode)
{ ssmprErrno = errorcode; }
SSMPRInt32 SSMPORT_GetError(void)
{ return ssmprErrno; }

View File

@@ -1,93 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/*****************************************************************************
*
*
*
*****************************************************************************
*/
#ifndef NULL
#define NULL 0x00000000
#endif
#define SSMPR_BYTES_PER_INT 4
#define SSMPR_BYTES_PER_LONG 4
/******************************************************************
* No NSPR - define all the SSMPR values and functions here
******************************************************************
*/
typedef enum { SSMPR_SUCCESS = 0, SSMPR_FAILURE = -1 } SSMPRStatus;
enum {
SSMPR_INVALID_ARGUMENT_ERROR = -6000,
SSMPR_OUT_OF_MEMORY_ERROR = -5987
};
#if SSMPR_BYTES_PER_INT == 4
typedef unsigned int SSMPRUint32;
typedef int SSMPRInt32;
#elif SSMPR_BYTES_PER_LONG == 4
typedef unsigned long SSMPRUint32;
typedef long SSMPRInt32;
#else
#error No suitable type for SSMPRInt32/SSMPRUint32
#endif
/*******************************************************************
* Use libc functions instead
*******************************************************************
*/
#include <sys/types.h>
#ifdef WIN32
#include <winsock.h>
#else
#include <netinet/in.h>
#endif
#define SSMPR_ntohl ntohl
#define SSMPR_htonl htonl
#include <stdlib.h>
#define SSMPORT_Free free
#define SSMPR_sprint printf
#define SSMPORT_ZAlloc malloc
extern SSMPRInt32 ssmprErrno;
#define SSMPR_SetError(x, y) SSMPORT_SetError(x)
#define SSMPR_GetError SSMPORT_GetError
void SSMPORT_SetError(SSMPRInt32 errorcode);

View File

@@ -1,169 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "string.h"
#include "protocol.h"
#include "protocolshr.h"
#include "messages.h"
/* Forward ref */
static void encrypt(CMTItem *data);
static void decrypt(CMTItem *data);
const char *kPrefix = "Encrypted";
/* encryption request */
CMTStatus
CMT_DoEncryptionRequest(CMTItem *message)
{
CMTStatus rv = CMTSuccess;
EncryptRequestMessage request;
EncryptReplyMessage reply;
CMUint32 pLen = strlen(kPrefix);
/* Initialize */
request.keyid.data = 0;
request.data.data = 0;
reply.item.data = 0;
/* Decode incoming message */
rv = CMT_DecodeMessage(EncryptRequestTemplate, &request, message);
if (rv != CMTSuccess) goto loser; /* Protocol error */
/* Free incoming message */
free(message->data);
message->data = NULL;
/* "Encrypt" by prefixing the data */
reply.item.len = request.data.len + pLen;
reply.item.data = calloc(reply.item.len, 1);
if (!reply.item.data) {
rv = CMTFailure;
goto loser;
}
if (pLen) memcpy(reply.item.data, kPrefix, pLen);
encrypt(&request.data);
memcpy(&reply.item.data[pLen], request.data.data, request.data.len);
/* Generate response */
message->type = SSM_SDR_ENCRYPT_REPLY;
rv = CMT_EncodeMessage(EncryptReplyTemplate, message, &reply);
if (rv != CMTSuccess) goto loser; /* Unknown error */
loser:
if (request.keyid.data) free(request.keyid.data);
if (request.data.data) free(request.data.data);
if (request.ctx.data) free(request.ctx.data);
if (reply.item.data) free(reply.item.data);
return rv;
}
/* decryption request */
CMTStatus
CMT_DoDecryptionRequest(CMTItem *message)
{
CMTStatus rv = CMTSuccess;
DecryptRequestMessage request;
DecryptReplyMessage reply;
CMUint32 pLen = strlen(kPrefix);
/* Initialize */
request.data.data = 0;
request.ctx.data = 0;
reply.item.data = 0;
/* Decode the message */
rv = CMT_DecodeMessage(DecryptRequestTemplate, &request, message);
if (rv != CMTSuccess) goto loser;
/* Free incoming message */
free(message->data);
message->data = NULL;
/* "Decrypt" the message by removing the key */
if (pLen && memcmp(request.data.data, kPrefix, pLen) != 0) {
rv = CMTFailure; /* Invalid format */
goto loser;
}
reply.item.len = request.data.len - pLen;
reply.item.data = calloc(reply.item.len, 1);
if (!reply.item.data) { rv = CMTFailure; goto loser; }
memcpy(reply.item.data, &request.data.data[pLen], reply.item.len);
decrypt(&reply.item);
/* Create reply message */
message->type = SSM_SDR_DECRYPT_REPLY;
rv = CMT_EncodeMessage(DecryptReplyTemplate, message, &reply);
if (rv != CMTSuccess) goto loser;
loser:
if (request.data.data) free(request.data.data);
if (request.ctx.data) free(request.ctx.data);
if (reply.item.data) free(reply.item.data);
return rv;
}
/* "encrypt" */
static unsigned char mask[64] = {
0x73, 0x46, 0x1a, 0x05, 0x24, 0x65, 0x43, 0xb4, 0x24, 0xee, 0x79, 0xc1, 0xcc,
0x49, 0xc7, 0x27, 0x11, 0x91, 0x2e, 0x8f, 0xaa, 0xf7, 0x62, 0x75, 0x41, 0x7e,
0xb2, 0x42, 0xde, 0x1b, 0x42, 0x7b, 0x1f, 0x33, 0x49, 0xca, 0xd1, 0x6a, 0x85,
0x05, 0x6c, 0xf9, 0x0e, 0x3e, 0x72, 0x02, 0xf2, 0xd8, 0x9d, 0xa1, 0xb8, 0x6e,
0x03, 0x18, 0x3e, 0x82, 0x86, 0x34, 0x1a, 0x61, 0xd9, 0x65, 0xb6, 0x7f
};
static void
encrypt(CMTItem *data)
{
unsigned int i, j;
j = 0;
for(i = 0;i < data->len;i++)
{
data->data[i] ^= mask[j];
if (++j >= 64) j = 0;
}
}
static void
decrypt(CMTItem *data)
{
encrypt(data);
}

View File

@@ -1,48 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/*
protocolshr.h - Definitions of shared routines for both client and server
These are mostly for testing.
*/
#ifndef __PROTOCOLSHR_H__
#define __PROTOCOLSHR_H__
CMTStatus
CMT_DoEncryptionRequest(CMTItem *message);
CMTStatus
CMT_DoDecryptionRequest(CMTItem *meessage);
#endif /* __PROTOCOLSHR_H__ */

View File

@@ -1,207 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape security libraries.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
#include "protocolf.h"
#include <stdio.h>
int main()
{
void * blob, * recvd;
int blobSize;
SSMPRUint32 version, flags, port, connID, keySize, secretKeySize;
SSMPRUint32 sessionID, httpPort;
SSMPRInt32 result;
char *profile, * nonce, * hostIP, * hostName, * cipher, * CA;
SSMPRStatus rv;
/*
* Test functions to pack and parse HelloRequest message
*/
version = 3;
profile = (char *)SSMPORT_ZAlloc(strlen("profile"));
sprintf(profile, "profile");
printf("HelloRequest, packing version #%d, profile %s\n",
version, profile);
blobSize = SSM_PackHelloRequest(&blob, version, profile);
if (!blobSize)
printf("Error in PackHelloRequest: %d\n", SSMPR_GetError());
SSMPORT_Free(profile);
version = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseHelloRequest(recvd, &version, &profile);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseHelloRequest: %d\n", SSMPR_GetError());
printf("HelloRequest, parsing version #%d, profile %s\n",
version, profile);
/*
* Test functions to parse and pack HelloReply message
*/
version = 5;
result = 2;
sessionID = 34567;
httpPort = 87654;
nonce = (char *)SSMPORT_ZAlloc(strlen("some secret nonce"));
sprintf(nonce, "some secret nonce");
printf("HelloReply, packing result %d, sessionID %d, version #%d, httpPort %d,\n nonce %s\n",
result, sessionID, version, httpPort, nonce);
blobSize = SSM_PackHelloReply(&blob, result, sessionID, version, httpPort,
nonce);
if (!blobSize)
printf("Error in PackHelloReply: %d\n", SSMPR_GetError());
memset(nonce, 0, strlen(nonce));
SSMPORT_Free(nonce);
version = result = sessionID = httpPort = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseHelloReply(recvd, &result, &sessionID, &version, &httpPort,
&nonce);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseHelloReply: %d\n", SSMPR_GetError());
printf("HelloReply, parsing result %d, sessionID %d, version #%d, httpPort %d, \n nonce %s\n",
result, sessionID, version, httpPort, nonce);
/*
* Test functions to parse and pack SSLDataConnectionRequest message
*/
flags = 0x00044000;
port = 34567;
hostIP = (char *)SSMPORT_ZAlloc(strlen("somehostIP"));
sprintf(hostIP, "somehostIP");
hostName = (char *)SSMPORT_ZAlloc(strlen("somehostName"));
sprintf(hostName, "somehostName");
printf("SSLDataConnRequest, packing flags %x, port %d, hostIP %s, hostName %s\n",
flags, port, hostIP, hostName);
blobSize = SSM_PackSSLDataConnectionRequest(&blob, flags, port, hostIP,
hostName);
if (!blobSize)
printf("Error in PackSSLDataConnectionRequest: %d\n", SSMPR_GetError());
SSMPORT_Free(hostIP);
SSMPORT_Free(hostName);
flags = port = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseSSLDataConnectionRequest(recvd, &flags, &port, &hostIP,
&hostName);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseSSLDataConnectionRequest: %d\n", SSMPR_GetError());
printf(
"SSLDataConnRequest, parsing flags %x, port %d, hostIP %s, hostName %s\n",
flags, port, hostIP, hostName);
SSMPORT_Free(hostIP);
SSMPORT_Free(hostName);
/*
* Test functions to parse and pack SSLDataConnectionReply message
*/
result = 2;
connID = 713259;
port = 57402;
printf("SSLDataConnReply, packing result %d, connectionID %d, port %d\n",
result, connID, port);
blobSize = SSM_PackSSLDataConnectionReply(&blob, result, connID, port);
if (!blobSize)
printf("Error in PackSSLDataConnReply: %d\n", SSMPR_GetError());
result = connID = port = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseSSLDataConnectionReply(recvd, &result, &connID, &port);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseSSLDataConnectionReply: %d\n", SSMPR_GetError());
printf("SSLDataConnReply, parsing result %d, connectionID %d, port %d\n",
result, connID, port);
/*
* Test functions to parse and pack SecurityStatusRequest message
*/
connID = 45375;
printf("SecurityStatusRequest, packing connection ID %d\n", connID);
blobSize = SSM_PackSecurityStatusRequest(&blob, connID);
if (!blobSize)
printf("Error in PackSecurityStatusRequest: %d\n", SSMPR_GetError());
connID = 0;
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseSecurityStatusRequest(recvd, &connID);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseSecurityStatusRequest: %d\n", SSMPR_GetError());
printf("SecurityStatusRequest, parsing connection ID %d\n", connID);
/*
* Test functions to parse and pack SecurityStatusReply message
*/
result = 2;
keySize = 256;
secretKeySize = 511;
cipher = (char *)SSMPORT_ZAlloc(strlen("My Cipher"));
sprintf(cipher, "My Cipher");
CA = (char *)SSMPORT_ZAlloc(strlen("My CA issuer"));
sprintf(CA, "My CA issuer");
printf("SecurityStatusReply, packing result %d, keysize %d, secretKeySize %d, cipher %s, CA %s\n", result, keySize, secretKeySize, cipher, CA);
blobSize = SSM_PackSecurityStatusReply(&blob, result, keySize, secretKeySize, cipher, CA);
if (!blobSize)
printf("Error in PackSecurityStatusReply: %d\n", SSMPR_GetError());
result = keySize = secretKeySize = 0;
SSMPORT_Free(cipher);
SSMPORT_Free(CA);
recvd = (void *)SSMPORT_ZAlloc(blobSize);
if (!recvd) printf("Can't allocate %d bytes of memory!\n", blobSize);
memcpy(recvd, blob, blobSize);
SSMPORT_Free(blob);
rv = SSM_ParseSecurityStatusReply(recvd, &result, &keySize, &secretKeySize,
&cipher, &CA);
if (rv != SSMPR_SUCCESS)
printf("Error in ParseSecurityStatusReply: %d\n", SSMPR_GetError());
printf("SecurityStatusReply, parsing result %d, keysize %d, secretKeySize %d, cipher %s, CA %s\n", result, keySize, secretKeySize, cipher, CA);
}

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