PRBool
gfxImageSurface::CopyFrom(gfxImageSurface *other)
{
    if (other->mSize != mSize)
    {
        return PR_FALSE;
    }

    if (other->mFormat != mFormat &&
        !(other->mFormat == ImageFormatARGB32 && mFormat == ImageFormatRGB24) &&
        !(other->mFormat == ImageFormatRGB24 && mFormat == ImageFormatARGB32))
    {
        return PR_FALSE;
    }

    if (other->mStride == mStride) {
        memcpy (mData, other->mData, mStride * mSize.height);
    } else {
        int lineSize = PR_MIN(other->mStride, mStride);
        for (int i = 0; i < mSize.height; i++) {
            unsigned char *src = other->mData + other->mStride * i;
            unsigned char *dst = mData + mStride * i;

            memcpy (dst, src, lineSize);
        }
    }

    return PR_TRUE;
}
nsSMILTimeValue
nsSMILTimedElement::GetRepeatDuration()
{
  nsSMILTimeValue result;

  if (mRepeatCount.IsDefinite() && mRepeatDur.IsResolved()) {
    if (mSimpleDur.IsResolved()) {
      nsSMILTime activeDur = mRepeatCount * double(mSimpleDur.GetMillis());
      result.SetMillis(PR_MIN(activeDur, mRepeatDur.GetMillis()));
    } else {
      result = mRepeatDur;
    }
  } else if (mRepeatCount.IsDefinite() && mSimpleDur.IsResolved()) {
    nsSMILTime activeDur = mRepeatCount * double(mSimpleDur.GetMillis());
    result.SetMillis(activeDur);
  } else if (mRepeatDur.IsResolved()) {
    result = mRepeatDur;
  } else if (mRepeatCount.IsIndefinite()) {
    result.SetIndefinite();
  } else {
    result = mSimpleDur;
  }

  return result;
}
Beispiel #3
0
SECStatus
SSL_GetPreliminaryChannelInfo(PRFileDesc *fd,
                              SSLPreliminaryChannelInfo *info,
                              PRUintn len)
{
    sslSocket *ss;
    SSLPreliminaryChannelInfo inf;

    /* Check if we can properly return the length of data written and that
     * we're not asked to return more information than we know how to provide.
     */
    if (!info || len < sizeof inf.length || len > sizeof inf) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }

    ss = ssl_FindSocket(fd);
    if (!ss) {
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetPreliminaryChannelInfo",
                 SSL_GETPID(), fd));
        return SECFailure;
    }

    memset(&inf, 0, sizeof(inf));
    inf.length = PR_MIN(sizeof(inf), len);

    inf.valuesSet = ss->ssl3.hs.preliminaryInfo;
    inf.protocolVersion = ss->version;
    inf.cipherSuite = ss->ssl3.hs.cipher_suite;

    memcpy(info, &inf, inf.length);
    return SECSuccess;
}
Beispiel #4
0
/* Buffer entropy data, and feed it to the RNG, entropy_buf_len bytes at a time.
 * Returns error if RNG_RandomUpdate fails. Also increments *total_fed
 * by the number of bytes successfully buffered.
 */
static SECStatus BufferEntropy(char* inbuf, PRUint32 inlen,
                               char* entropy_buf, PRUint32* entropy_buffered,
                               PRUint32* total_fed)
{
    PRUint32 tocopy = 0;
    PRUint32 avail = 0;
    SECStatus rv = SECSuccess;

    while (inlen) {
        avail = entropy_buf_len - *entropy_buffered;
        if (!avail) {
            /* Buffer is full, time to feed it to the RNG. */
            rv = RNG_RandomUpdate(entropy_buf, entropy_buf_len);
            if (SECSuccess != rv) {
                break;
            }
            *entropy_buffered = 0;
            avail = entropy_buf_len;
        }
        tocopy = PR_MIN(avail, inlen);
        memcpy(entropy_buf + *entropy_buffered, inbuf, tocopy);
        *entropy_buffered += tocopy;
        inlen -= tocopy;
        inbuf += tocopy;
        *total_fed += tocopy;
    }
    return rv;
}
nsresult
nsMsgSearchValidityTable::GetAvailableOperators(nsMsgSearchAttribValue aAttribute,
                                                PRUint32 *aLength,
                                                nsMsgSearchOpValue **aResult)
{
    nsMsgSearchAttribValue attr;
    if (aAttribute == nsMsgSearchAttrib::Default)
      attr = m_defaultAttrib;
    else
       attr = PR_MIN(aAttribute, nsMsgSearchAttrib::OtherHeader);

    PRUint32 totalOperators=0;
    PRInt32 i;
    for (i=0; i<nsMsgSearchOp::kNumMsgSearchOperators; i++) {
        if (m_table[attr][i].bitAvailable)
            totalOperators++;
    }

    nsMsgSearchOpValue *array = (nsMsgSearchOpValue*)
        nsMemory::Alloc(sizeof(nsMsgSearchOpValue) * totalOperators);
    NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY);

    PRUint32 numStored = 0;
    for (i=0; i<nsMsgSearchOp::kNumMsgSearchOperators;i++) {
        if (m_table[attr][i].bitAvailable)
            array[numStored++] = i;
    }

    NS_ASSERTION(totalOperators == numStored, "Search Operators not lining up");
    *aLength = totalOperators;
    *aResult = array;
    return NS_OK;
}
Beispiel #6
0
PRInt32
nsRenderingContext::GetMaxChunkLength()
{
    if (!mFontMetrics)
        return 1;
    return PR_MIN(mFontMetrics->GetMaxStringLength(), MAX_GFX_TEXT_BUF_SIZE);
}
void nsBufferDecoderSupport::FillBuffer(const char ** aSrc, PRInt32 aSrcLength)
{
  PRInt32 bcr = PR_MIN(mBufferCapacity - mBufferLength, aSrcLength);
  memcpy(mBuffer + mBufferLength, *aSrc, bcr);
  mBufferLength += bcr;
  (*aSrc) += bcr;
}
static PRInt32 FindSafeLength(nsThebesRenderingContext* aContext,
                              const char *aString, PRUint32 aLength,
                              PRUint32 aMaxChunkLength)
{
    // Since it's ASCII, we don't need to worry about clusters or RTL
    return PR_MIN(aLength, aMaxChunkLength);
}
/* Use this function to update the ClientRandom of a client's handshake state
 * after replacing its ClientHello message. We for example need to do this
 * when replacing an SSLv3 ClientHello with its SSLv2 equivalent. */
SECStatus SSLInt_UpdateSSLv2ClientRandom(PRFileDesc *fd, uint8_t *rnd,
                                         size_t rnd_len, uint8_t *msg,
                                         size_t msg_len) {
  sslSocket *ss = ssl_FindSocket(fd);
  if (!ss) {
    return SECFailure;
  }

  SECStatus rv = ssl3_InitState(ss);
  if (rv != SECSuccess) {
    return rv;
  }

  rv = ssl3_RestartHandshakeHashes(ss);
  if (rv != SECSuccess) {
    return rv;
  }

  // Ensure we don't overrun hs.client_random.
  rnd_len = PR_MIN(SSL3_RANDOM_LENGTH, rnd_len);

  // Zero the client_random struct.
  PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);

  // Copy over the challenge bytes.
  size_t offset = SSL3_RANDOM_LENGTH - rnd_len;
  PORT_Memcpy(&ss->ssl3.hs.client_random.rand[offset], rnd, rnd_len);

  // Rehash the SSLv2 client hello message.
  return ssl3_UpdateHandshakeHashes(ss, msg, msg_len);
}
Beispiel #10
0
NS_IMETHODIMP
nsJSONListener::OnDataAvailable(nsIRequest *aRequest, nsISupports *aContext,
                                nsIInputStream *aStream,
                                PRUint32 aOffset, PRUint32 aLength)
{
  PRUint32 contentLength;
  aStream->Available(&contentLength);
  nsresult rv = NS_OK;

  if (mNeedsConverter && mSniffBuffer.Length() < 4) {
    PRUint32 readCount = (aLength < 4) ? aLength : 4;
    rv = NS_ConsumeStream(aStream, readCount, mSniffBuffer);
    NS_ENSURE_SUCCESS(rv, rv);

    if (mSniffBuffer.Length() < 4)
      return NS_OK;
  }
  
  char buffer[JSON_STREAM_BUFSIZE];
  unsigned long bytesRemaining = aLength - mSniffBuffer.Length();
  while (bytesRemaining) {
    unsigned int bytesRead;
    rv = aStream->Read(buffer,
                       PR_MIN(sizeof(buffer), bytesRemaining),
                       &bytesRead);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = ProcessBytes(buffer, bytesRead);
    NS_ENSURE_SUCCESS(rv, rv);
    bytesRemaining -= bytesRead;
  }

  return rv;
}
Beispiel #11
0
SECStatus
SSL_GetCipherSuiteInfo(PRUint16 cipherSuite,
                       SSLCipherSuiteInfo *info, PRUintn len)
{
    unsigned int i;

    /* Check if we can properly return the length of data written and that
     * we're not asked to return more information than we know how to provide.
     */
    if (!info || len < sizeof suiteInfo[0].length ||
        len > sizeof suiteInfo[0]) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }
    len = PR_MIN(len, sizeof suiteInfo[0]);
    for (i = 0; i < NUM_SUITEINFOS; i++) {
        if (suiteInfo[i].cipherSuite == cipherSuite) {
            memcpy(info, &suiteInfo[i], len);
            info->length = len;
            return SECSuccess;
        }
    }
    PORT_SetError(SEC_ERROR_INVALID_ARGS);
    return SECFailure;
}
Beispiel #12
0
nsresult PREF_GetCharPref(const char *pref_name, char * return_buffer, int * length, PRBool get_default)
{
    if (!gHashTable.ops)
        return NS_ERROR_NOT_INITIALIZED;

    nsresult rv = NS_ERROR_UNEXPECTED;
    char* stringVal;

    PrefHashEntry* pref = pref_HashTableLookup(pref_name);

    if (pref)
    {
        if (get_default || PREF_IS_LOCKED(pref) || !PREF_HAS_USER_VALUE(pref))
            stringVal = pref->defaultPref.stringVal;
        else
            stringVal = pref->userPref.stringVal;

        if (stringVal)
        {
            if (*length <= 0)
                *length = PL_strlen(stringVal) + 1;
            else
            {
                PL_strncpy(return_buffer, stringVal, PR_MIN((size_t)*length - 1, PL_strlen(stringVal) + 1));
                return_buffer[*length - 1] = '\0';
            }
            rv = NS_OK;
        }
    }

    return rv;
}
Beispiel #13
0
void 
MD2_Update(MD2Context *cx, const unsigned char *input, unsigned int inputLen)
{
	PRUint32 bytesToConsume;
	
	/* Fill the remaining input buffer. */
	if (cx->unusedBuffer != MD2_BUFSIZE) {
		bytesToConsume = PR_MIN(inputLen, cx->unusedBuffer);
		memcpy(&cx->X[MD2_INPUT + (MD2_BUFSIZE - cx->unusedBuffer)],
		            input, bytesToConsume);
		if (cx->unusedBuffer + bytesToConsume >= MD2_BUFSIZE)
			md2_compress(cx);
		inputLen -= bytesToConsume;
		input += bytesToConsume;
	}

	/* Iterate over 16-byte chunks of the input. */
	while (inputLen >= MD2_BUFSIZE) {
		memcpy(&cx->X[MD2_INPUT], input, MD2_BUFSIZE);
		md2_compress(cx);
		inputLen -= MD2_BUFSIZE;
		input += MD2_BUFSIZE;
	}

	/* Copy any input that remains into the buffer. */
	if (inputLen)
		memcpy(&cx->X[MD2_INPUT], input, inputLen);
	cx->unusedBuffer = MD2_BUFSIZE - inputLen;
}
Beispiel #14
0
SECStatus
SSL_GetPreliminaryChannelInfo(PRFileDesc *fd,
                              SSLPreliminaryChannelInfo *info,
                              PRUintn len)
{
    sslSocket *ss;
    SSLPreliminaryChannelInfo inf;

    if (!info || len < sizeof inf.length) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }

    ss = ssl_FindSocket(fd);
    if (!ss) {
        SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetPreliminaryChannelInfo",
                 SSL_GETPID(), fd));
        return SECFailure;
    }

    if (ss->version < SSL_LIBRARY_VERSION_3_0) {
        PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
        return SECFailure;
    }

    memset(&inf, 0, sizeof(inf));
    inf.length = PR_MIN(sizeof(inf), len);

    inf.valuesSet = ss->ssl3.hs.preliminaryInfo;
    inf.protocolVersion = ss->version;
    inf.cipherSuite = ss->ssl3.hs.cipher_suite;

    memcpy(info, &inf, inf.length);
    return SECSuccess;
}
NS_IMETHODIMP
nsIncrementalDownload::OnDataAvailable(nsIRequest *request,
                                       nsISupports *context,
                                       nsIInputStream *input,
                                       PRUint32 offset,
                                       PRUint32 count)
{
  while (count) {
    PRUint32 space = mChunkSize - mChunkLen;
    PRUint32 n, len = PR_MIN(space, count);

    nsresult rv = input->Read(mChunk + mChunkLen, len, &n);
    if (NS_FAILED(rv))
      return rv;
    if (n != len)
      return NS_ERROR_UNEXPECTED;

    count -= n;
    mChunkLen += n;

    if (mChunkLen == mChunkSize)
      FlushChunk();
  }

  if (PR_Now() > mLastProgressUpdate + UPDATE_PROGRESS_INTERVAL)
    UpdateProgress();

  return NS_OK;
}
PRBool
nsAttrValue::ParseSpecialIntValue(const nsAString& aString,
                                  PRBool aCanBePercent)
{
  ResetIfSet();

  PRInt32 ec;
  nsAutoString tmp(aString);
  PRInt32 val = tmp.ToInteger(&ec);

  if (NS_FAILED(ec)) {
    return PR_FALSE;
  }

  val = PR_MAX(val, 0);
  val = PR_MIN(val, NS_ATTRVALUE_INTEGERTYPE_MAXVALUE);

  // % (percent)
  // XXX RFindChar means that 5%x will be parsed!
  if (aCanBePercent && tmp.RFindChar('%') >= 0) {
    if (val > 100) {
      val = 100;
    }
    SetIntValueAndType(val, ePercent);
    return PR_TRUE;
  }

  // Straight number is interpreted as integer
  SetIntValueAndType(val, eInteger);
  return PR_TRUE;
}
static void
PaintCheckMark(nsIRenderingContext& aRenderingContext,
               const nsRect& aRect)
{
  // Points come from the coordinates on a 7X7 unit box centered at 0,0
  const PRInt32 checkPolygonX[] = { -3, -1,  3,  3, -1, -3 };
  const PRInt32 checkPolygonY[] = { -1,  1, -3, -1,  3,  1 };
  const PRInt32 checkNumPoints = sizeof(checkPolygonX) / sizeof(PRInt32);
  const PRInt32 checkSize      = 9; // This is value is determined by adding 2
                                    // units to pad the 7x7 unit checkmark

  // Scale the checkmark based on the smallest dimension
  nscoord paintScale = PR_MIN(aRect.width, aRect.height) / checkSize;
  nsPoint paintCenter(aRect.x + aRect.width  / 2,
                      aRect.y + aRect.height / 2);

  nsPoint paintPolygon[checkNumPoints];
  // Convert checkmark for screen rendering
  for (PRInt32 polyIndex = 0; polyIndex < checkNumPoints; polyIndex++) {
    paintPolygon[polyIndex] = paintCenter +
                              nsPoint(checkPolygonX[polyIndex] * paintScale,
                                      checkPolygonY[polyIndex] * paintScale);
  }

  aRenderingContext.FillPolygon(paintPolygon, checkNumPoints);
}
Beispiel #18
0
void nsIntervalSet::IncludeInterval(coord_type aBegin, coord_type aEnd)
{
    Interval *newInterval = static_cast<Interval*>
                                       ((*mAlloc)(sizeof(Interval), mAllocatorClosure));
    if (!newInterval) {
        NS_NOTREACHED("allocation failure");
        return;
    }
    new(newInterval) Interval(aBegin, aEnd);

    Interval **current = &mList;
    while (*current && (*current)->mEnd < aBegin)
        current = &(*current)->mNext;

    newInterval->mNext = *current;
    *current = newInterval;

    Interval *subsumed = newInterval->mNext;
    while (subsumed && subsumed->mBegin <= aEnd) {
        newInterval->mBegin = PR_MIN(newInterval->mBegin, subsumed->mBegin);
        newInterval->mEnd = PR_MAX(newInterval->mEnd, subsumed->mEnd);
        newInterval->mNext = subsumed->mNext;
        FreeInterval(subsumed);
        subsumed = newInterval->mNext;
    }
}
Beispiel #19
0
NS_IMETHODIMP
HttpBaseChannel::SetRedirectionLimit(PRUint32 value)
{
  ENSURE_CALLED_BEFORE_ASYNC_OPEN();

  mRedirectionLimit = PR_MIN(value, 0xff);
  return NS_OK;
}
PRInt32
nsHTMLEditor::GetNewResizingY(PRInt32 aX, PRInt32 aY)
{
  PRInt32 resized = mResizedObjectY +
                    GetNewResizingIncrement(aX, aY, kY) * mYIncrementFactor;
  PRInt32 max =   mResizedObjectY + mResizedObjectHeight;
  return PR_MIN(resized, max);
}
PRInt32
nsHTMLEditor::GetNewResizingX(PRInt32 aX, PRInt32 aY)
{
  PRInt32 resized = mResizedObjectX +
                    GetNewResizingIncrement(aX, aY, kX) * mXIncrementFactor;
  PRInt32 max =   mResizedObjectX + mResizedObjectWidth;
  return PR_MIN(resized, max);
}
Beispiel #22
0
/*-----------------------------------------------------------------

	GetNamedFragmentOffsets

	Get the offsets into the data fork of the named fragment,
	by reading the 'cfrg' resoruce.

-----------------------------------------------------------------*/
OSErr GetNamedFragmentOffsets(const FSSpec *fileSpec, const char* fragmentName,
							UInt32 *outOffset, UInt32 *outLength)
{
	CFragResourceHandle		cFragHandle;
	short									fileRefNum;
	OSErr									err = noErr;
	
	fileRefNum = FSpOpenResFile(fileSpec, fsRdPerm);
	err = ResError();
	if (err != noErr) return err;

	cFragHandle = (CFragResourceHandle)Get1Resource(kCFragResourceType, kCFragResourceID);	
	if (!cFragHandle)
	{
		err = resNotFound;
		goto done;
	}
	
	/* nothing here moves memory, so no need to lock the handle */
	
	err = cfragNoLibraryErr;			/* in case of failure */
	*outOffset = 0;
	*outLength = 0;
	
	/* Now look for the named fragment */
	if ((**cFragHandle).memberCount > 0)
	{
		CFragResourceMemberPtr	memberPtr;
		UInt16									i;
		
		for (	i = 0, memberPtr = &(**cFragHandle).firstMember;
					i < (**cFragHandle).memberCount;
					i ++, memberPtr = (CFragResourceMemberPtr)((char *)memberPtr + memberPtr->memberSize))
		{
			char		memberName[256];
			UInt16	nameLen = PR_MIN(memberPtr->name[0], 255);
		
			// avoid malloc here for speed
			strncpy(memberName, (char *)&memberPtr->name[1], nameLen);
			memberName[nameLen] = '\0';
		
			// fragment names are case insensitive, so act like the system
			if (PL_strcasecmp(memberName, fragmentName) == 0)
			{
				*outOffset = memberPtr->offset;
				*outLength = memberPtr->length;
				err = noErr;
				break;
			}
		}
	}
	
	/* Resource handle will go away when the res fork is closed */
	
done:
	CloseResFile(fileRefNum);
	return err;
}
PRUint32 KeyboardLayout::GetUniChars (PRUnichar* aUniChars, PRUint8* aShiftStates, PRUint32 aMaxChars) const
{
  PRUint32 chars = PR_MIN (mNumOfChars, aMaxChars);

  memcpy (aUniChars, mChars, chars * sizeof (PRUnichar));
  memcpy (aShiftStates, mShiftStates, chars);

  return chars;
}
Beispiel #24
0
gfxRect
gfxRect::Intersect(const gfxRect& aRect) const
{
    gfxRect result(0,0,0,0);

    gfxFloat x = PR_MAX(aRect.X(), X());
    gfxFloat xmost = PR_MIN(aRect.XMost(), XMost());
    if (x >= xmost)
        return result;

    gfxFloat y = PR_MAX(aRect.Y(), Y());
    gfxFloat ymost = PR_MIN(aRect.YMost(), YMost());
    if (y >= ymost)
        return result;

    result = gfxRect(x, y, xmost - x, ymost - y);
    return result;
}
Beispiel #25
0
SECStatus
CTR_Update(CTRContext *ctr, unsigned char *outbuf,
	   unsigned int *outlen, unsigned int maxout,
	   const unsigned char *inbuf, unsigned int inlen,
	   unsigned int blocksize)
{
    unsigned int tmp;
    SECStatus rv;

    if (maxout < inlen) {
	*outlen = inlen;
	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
	return SECFailure;
    }
    *outlen = 0;
    if (ctr->bufPtr != blocksize) {
	unsigned int needed = PR_MIN(blocksize-ctr->bufPtr, inlen);
	ctr_xor(outbuf, inbuf, ctr->buffer + ctr->bufPtr, needed);
	ctr->bufPtr += needed;
	outbuf += needed;
	inbuf += needed;
	*outlen += needed;
	inlen -= needed;
	if (inlen == 0) {
	    return SECSuccess;
	}
	PORT_Assert(ctr->bufPtr == blocksize);
    }

    while (inlen >= blocksize) {
	rv = (*ctr->cipher)(ctr->context, ctr->buffer, &tmp, blocksize,
			ctr->counter, blocksize, blocksize);
	ctr_GetNextCtr(ctr->counter, ctr->counterBits, blocksize);
	if (rv != SECSuccess) {
	    return SECFailure;
	}
	ctr_xor(outbuf, inbuf, ctr->buffer, blocksize);
	outbuf += blocksize;
	inbuf += blocksize;
	*outlen += blocksize;
	inlen -= blocksize;
    }
    if (inlen == 0) {
	return SECSuccess;
    }
    rv = (*ctr->cipher)(ctr->context, ctr->buffer, &tmp, blocksize,
			ctr->counter, blocksize, blocksize);
    ctr_GetNextCtr(ctr->counter, ctr->counterBits, blocksize);
    if (rv != SECSuccess) {
	return SECFailure;
    }
    ctr_xor(outbuf, inbuf, ctr->buffer, inlen);
    ctr->bufPtr = inlen;
    *outlen += inlen;
    return SECSuccess;
}
void
nsFileCopyEvent::DoCopy()
{
  // We'll copy in chunks this large by default.  This size affects how
  // frequently we'll check for interrupts.
  const PRInt32 chunk = NET_DEFAULT_SEGMENT_SIZE * NET_DEFAULT_SEGMENT_COUNT;

  nsresult rv = NS_OK;

  PRInt64 len = mLen, progress = 0;
  while (len) {
    // If we've been interrupted, then stop copying.
    rv = mInterruptStatus;
    if (NS_FAILED(rv))
      break;

    PRInt32 num = PR_MIN((PRInt32) len, chunk);

    PRUint32 result;
    rv = mSource->ReadSegments(NS_CopySegmentToStream, mDest, num, &result);
    if (NS_FAILED(rv))
      break;
    if (result != (PRUint32) num) {
      rv = NS_ERROR_FILE_DISK_FULL;  // stopped prematurely (out of disk space)
      break;
    }

    // Dispatch progress notification
    if (mSink) {
      progress += num;
      mSink->OnTransportStatus(nsnull, nsITransport::STATUS_WRITING, progress,
                               mLen);
    }
                               
    len -= num;
  }

  if (NS_FAILED(rv))
    mStatus = rv;

  // Close the output stream before notifying our callback so that others may
  // freely "play" with the file.
  mDest->Close();

  // Notify completion
  if (mCallback) {
    mCallbackTarget->Dispatch(mCallback, NS_DISPATCH_NORMAL);

    // Release the callback on the target thread to avoid destroying stuff on
    // the wrong thread.
    nsIRunnable *doomed = nsnull;
    mCallback.swap(doomed);
    NS_ProxyRelease(mCallbackTarget, doomed);
  }
}
Beispiel #27
0
OSStatus
otMacAudioInputStream::InputReadyCb(void *userdata, AudioUnitRenderActionFlags *actionFlags,
                                    const AudioTimeStamp *timeStamp, UInt32 busNumber,
                                    UInt32 numberFrames, AudioBufferList *data)
{
  otMacAudioInputStream *_this = (otMacAudioInputStream*)userdata;
  OSStatus err;
  DEBUG_DUMP2("InputReadyCb numberFrames = %d, frameEnd = %d", numberFrames, _this->mFrameEnd);

  err = AudioUnitRender(_this->mAudioUnit, actionFlags, timeStamp, busNumber,
                        numberFrames, _this->mBuffer);
  if (err == noErr) {
    UInt32 bytes = _this->mBuffer->mBuffers[0].mDataByteSize;
    char *data = (char*) _this->mBuffer->mBuffers[0].mData;

    while (bytes > 0) {
      PRUint32 len = PR_MIN(_this->mInputFrameSize - _this->mFrameEnd, bytes);
      memcpy(_this->mFrame + _this->mFrameEnd, data, len);

  DEBUG_DUMP_N(("InputReadyCbInt bytes = %d frameEnd = %d, inputFrameSize = %d, frameSize = %d", bytes, _this->mFrameEnd, _this->mInputFrameSize, _this->mFrameSize));

      data += len;
      bytes -= len;
      _this->mFrameEnd += len;

      if (_this->mFrameEnd < _this->mInputFrameSize)
        break;

      UInt32 frameSize = _this->mFrameSize/2;

      err = AudioConverterFillComplexBuffer(_this->mConverter,
                                            &ConverterCb, _this, &frameSize,
                                            _this->mConvertBuffer, NULL);
      if (err != noErr) {
        printErrCode(err);
        return err;
      }

      DEBUG_DUMP("SendFrame");

      char *data2 = (char*)_this->mConvertBuffer->mBuffers[0].mData;

      _this->mFilter->InputData(data2, _this->mFrameSize);
      if (_this->mTarget)
        _this->mTarget->AcceptData(data2, _this->mFrameSize);

      //_this->mFrameEnd = 0;
    }
  } else {
    printErrCode(err);
  }

  return noErr;
}
Beispiel #28
0
SECStatus
CTR_Update_HW_AES(CTRContext *ctr, unsigned char *outbuf,
		  unsigned int *outlen, unsigned int maxout,
		  const unsigned char *inbuf, unsigned int inlen,
		  unsigned int blocksize)
{
    unsigned int fullblocks;
    unsigned int tmp;
    SECStatus rv;

    if (maxout < inlen) {
	*outlen = inlen;
	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
	return SECFailure;
    }
    *outlen = 0;
    if (ctr->bufPtr != blocksize) {
	unsigned int needed = PR_MIN(blocksize-ctr->bufPtr, inlen);
	ctr_xor(outbuf, inbuf, ctr->buffer + ctr->bufPtr, needed);
	ctr->bufPtr += needed;
	outbuf += needed;
	inbuf += needed;
	*outlen += needed;
	inlen -= needed;
	if (inlen == 0) {
	    return SECSuccess;
	}
	PORT_Assert(ctr->bufPtr == blocksize);
    }

    intel_aes_ctr_worker(((AESContext*)(ctr->context))->Nr)(
	ctr, outbuf, outlen, maxout, inbuf, inlen, blocksize);
    /* XXX intel_aes_ctr_worker should set *outlen. */
    PORT_Assert(*outlen == 0);
    fullblocks = (inlen/blocksize)*blocksize;
    *outlen += fullblocks;
    outbuf += fullblocks;
    inbuf += fullblocks;
    inlen -= fullblocks;

    if (inlen == 0) {
	return SECSuccess;
    }
    rv = (*ctr->cipher)(ctr->context, ctr->buffer, &tmp, blocksize,
			ctr->counter, blocksize, blocksize);
    ctr_GetNextCtr(ctr->counter, ctr->counterBits, blocksize);
    if (rv != SECSuccess) {
	return SECFailure;
    }
    ctr_xor(outbuf, inbuf, ctr->buffer, inlen);
    ctr->bufPtr = inlen;
    *outlen += inlen;
    return SECSuccess;
}
Beispiel #29
0
size_t RNG_FileUpdate(const char *fileName, size_t limit)
{
    FILE *        file;
    int           fd;
    int           bytes;
    size_t        fileBytes = 0;
    struct stat   stat_buf;
    unsigned char buffer[BUFSIZ];
    static size_t totalFileBytes = 0;
    
    /* suppress valgrind warnings due to holes in struct stat */
    memset(&stat_buf, 0, sizeof(stat_buf));

    if (stat((char *)fileName, &stat_buf) < 0)
	return fileBytes;
    RNG_RandomUpdate(&stat_buf, sizeof(stat_buf));
    
    file = fopen(fileName, "r");
    if (file != NULL) {
	/* Read from the underlying file descriptor directly to bypass stdio
	 * buffering and avoid reading more bytes than we need from
	 * /dev/urandom. NOTE: we can't use fread with unbuffered I/O because
	 * fread may return EOF in unbuffered I/O mode on Android.
	 *
	 * Moreover, we read into a buffer of size BUFSIZ, so buffered I/O
	 * has no performance advantage. */
	fd = fileno(file);
	/* 'file' was just opened, so this should not fail. */
	PORT_Assert(fd != -1);
	while (limit > fileBytes && fd != -1) {
	    bytes = PR_MIN(sizeof buffer, limit - fileBytes);
	    bytes = read(fd, buffer, bytes);
	    if (bytes <= 0)
		break;
	    RNG_RandomUpdate(buffer, bytes);
	    fileBytes      += bytes;
	    totalFileBytes += bytes;
	    /* after TOTAL_FILE_LIMIT has been reached, only read in first
	    ** buffer of data from each subsequent file.
	    */
	    if (totalFileBytes > TOTAL_FILE_LIMIT) 
		break;
	}
	fclose(file);
    }
    /*
     * Pass yet another snapshot of our highest resolution clock into
     * the hash function.
     */
    bytes = RNG_GetNoise(buffer, sizeof(buffer));
    RNG_RandomUpdate(buffer, bytes);
    return fileBytes;
}
Beispiel #30
0
void
WeightTableInitCorrection(PRUint8* aTable, PRUint8 aMinValue,
                                double aGain)
{
  // setup the wieghting table
  for (int i=0; i<256; i++) {
    int val = i + (int)rint((double)(i-aMinValue)*aGain);
    val = PR_MAX(0, val);
    val = PR_MIN(val, 255);
    aTable[i] = (PRUint8)val;
  }
}