int readStdin(SECItem * result) { unsigned int bufsize = 0; int cc; unsigned int wanted = 8192U; result->len = 0; result->data = NULL; do { if (bufsize < wanted) { unsigned char * tmpData = (unsigned char *)PR_Realloc(result->data, wanted); if (!tmpData) { if (verbose) PR_fprintf(pr_stderr, "Allocation of buffer failed\n"); return -1; } result->data = tmpData; bufsize = wanted; } cc = PR_Read(PR_STDIN, result->data + result->len, bufsize - result->len); if (cc > 0) { result->len += (unsigned)cc; if (result->len >= wanted) wanted *= 2; } } while (cc > 0); return cc; }
void nsAttrAndChildArray::Compact() { if (!mImpl) { return; } // First compress away empty attrslots PRUint32 slotCount = AttrSlotCount(); PRUint32 attrCount = NonMappedAttrCount(); PRUint32 childCount = ChildCount(); if (attrCount < slotCount) { memmove(mImpl->mBuffer + attrCount * ATTRSIZE, mImpl->mBuffer + slotCount * ATTRSIZE, childCount * sizeof(nsIContent*)); SetAttrSlotCount(attrCount); } // Then resize or free buffer PRUint32 newSize = attrCount * ATTRSIZE + childCount; if (!newSize && !mImpl->mMappedAttrs) { PR_Free(mImpl); mImpl = nsnull; } else if (newSize < mImpl->mBufferSize) { mImpl = static_cast<Impl*>(PR_Realloc(mImpl, (newSize + NS_IMPL_EXTRA_SIZE) * sizeof(nsIContent*))); NS_ASSERTION(mImpl, "failed to reallocate to smaller buffer"); mImpl->mBufferSize = newSize; } }
// do the fallback, reallocate the buffer if necessary // need to pass destination buffer info (size, current position and estimation of rest of the conversion) NS_IMETHODIMP nsSaveAsCharset::HandleFallBack(uint32_t character, char **outString, int32_t *bufferLength, int32_t *currentPos, int32_t estimatedLength) { NS_ENSURE_ARG_POINTER(outString); NS_ENSURE_ARG_POINTER(bufferLength); NS_ENSURE_ARG_POINTER(currentPos); char fallbackStr[256]; nsresult rv = DoConversionFallBack(character, fallbackStr, 256); if (NS_SUCCEEDED(rv)) { int32_t tempLen = (int32_t) strlen(fallbackStr); // reallocate if the buffer is not large enough if ((tempLen + estimatedLength) >= (*bufferLength - *currentPos)) { int32_t addLength = tempLen + RESERVE_FALLBACK_BYTES; // + 1 is for the terminating NUL, don't add that to bufferLength char *temp = (char *) PR_Realloc(*outString, *bufferLength + addLength + 1); if (temp) { // adjust length/pointer after realloc *bufferLength += addLength; *outString = temp; } else { *outString = nullptr; *bufferLength = 0; return NS_ERROR_OUT_OF_MEMORY; } } memcpy((*outString + *currentPos), fallbackStr, tempLen); *currentPos += tempLen; } return rv; }
// do the fallback, reallocate the buffer if necessary // need to pass destination buffer info (size, current position and estimation of rest of the conversion) NS_IMETHODIMP nsSaveAsCharset::HandleFallBack(PRUint32 character, char **outString, PRInt32 *bufferLength, PRInt32 *currentPos, PRInt32 estimatedLength) { if((nullptr == outString ) || (nullptr == bufferLength) ||(nullptr ==currentPos)) return NS_ERROR_NULL_POINTER; char fallbackStr[256]; nsresult rv = DoConversionFallBack(character, fallbackStr, 256); if (NS_SUCCEEDED(rv)) { PRInt32 tempLen = (PRInt32) PL_strlen(fallbackStr); // reallocate if the buffer is not large enough if ((tempLen + estimatedLength) >= (*bufferLength - *currentPos)) { char *temp = (char *) PR_Realloc(*outString, *bufferLength + tempLen); if (NULL != temp) { // adjust length/pointer after realloc *bufferLength += tempLen; *outString = temp; } else { *outString = NULL; *bufferLength =0; return NS_ERROR_OUT_OF_MEMORY; } } memcpy((*outString + *currentPos), fallbackStr, tempLen); *currentPos += tempLen; } return rv; }
bool nsAttrAndChildArray::GrowBy(PRUint32 aGrowSize) { PRUint32 size = mImpl ? mImpl->mBufferSize + NS_IMPL_EXTRA_SIZE : 0; PRUint32 minSize = size + aGrowSize; if (minSize <= ATTRCHILD_ARRAY_LINEAR_THRESHOLD) { do { size += ATTRCHILD_ARRAY_GROWSIZE; } while (size < minSize); } else { size = PR_BIT(PR_CeilingLog2(minSize)); } bool needToInitialize = !mImpl; Impl* newImpl = static_cast<Impl*>(PR_Realloc(mImpl, size * sizeof(void*))); NS_ENSURE_TRUE(newImpl, false); mImpl = newImpl; // Set initial counts if we didn't have a buffer before if (needToInitialize) { mImpl->mMappedAttrs = nsnull; SetAttrSlotAndChildCount(0, 0); } mImpl->mBufferSize = size - NS_IMPL_EXTRA_SIZE; return true; }
SKERR SKIntegerList::SetListFromAsciiString(const char* pcString) { PRUint32 *piTmp = NULL; PRUint32 iSize = 0; PRUint32 iCount = 0; while(*pcString) { if(*pcString == ' ') { pcString++; continue; } /* a number to parse */ if(iSize == iCount) { iSize = iSize * 2 + 10; piTmp = (PRUint32*) PR_Realloc(piTmp, iSize * sizeof(PRUint32)); if(!piTmp) return err_memory; } char * pcEnd; piTmp[iCount++] = strtoul(pcString, &pcEnd, 16); pcString = pcEnd; } SetListFromArray(piTmp, iCount, PR_TRUE); PR_Free(piTmp); return noErr; }
SKERR SKRecordPool::GetRecord(SKRecord **ppRecord, void *pBuffer, PRBool bVolatileBuffer) { SKERR err; for(PRUint32 i = 0; i < m_iPoolsCount; ++i) { err = m_ppPools[i]->GetRecord(ppRecord, pBuffer, bVolatileBuffer); // If succeeded then return if(err == noErr) return noErr; } // All the pools are full, create a new one SKFixedRecordPool * pPool = sk_CreateInstance(SKFixedRecordPool)(m_iPoolSize, m_iRecordSize); if(!pPool) return err_memory; err = pPool->Init(); if(err != noErr) return err; m_ppPools = (SKFixedRecordPool **) PR_Realloc(m_ppPools, (m_iPoolsCount + 1) * sizeof(SKFixedRecordPool *)); SK_ASSERT(NULL != m_ppPools); m_ppPools[m_iPoolsCount++] = pPool; return m_ppPools[m_iPoolsCount - 1]->GetRecord(ppRecord, pBuffer, bVolatileBuffer); }
void * PORT_Realloc(void *oldptr, size_t bytes) { void *rv; rv = (void *)PR_Realloc(oldptr, bytes); return rv; }
SKERR SKCursorRecordSet::AppendSpeeder(SKRefCount *pSpeeder) { m_ppSpeeders = (SKRefCount **) PR_Realloc(m_ppSpeeders, (m_iSpeederCount + 1) * sizeof(SKRefCount *)); SK_ASSERT(NULL != m_ppSpeeders); m_ppSpeeders[m_iSpeederCount++] = pSpeeder; pSpeeder->AddRef(); return noErr; }
static int MimeExternalBody_parse_line (const char *line, PRInt32 length, MimeObject *obj) { MimeExternalBody *bod = (MimeExternalBody *) obj; int status = 0; NS_ASSERTION(line && *line, "1.1 <*****@*****.**> 19 Mar 1999 12:00"); if (!line || !*line) return -1; if (!obj->output_p) return 0; /* If we're supposed to write this object, but aren't supposed to convert it to HTML, simply pass it through unaltered. */ if (obj->options && !obj->options->write_html_p && obj->options->output_fn) return MimeObject_write(obj, line, length, PR_TRUE); /* If we already have a `body' then we're done parsing headers, and all subsequent lines get tacked onto the body. */ if (bod->body) { int L = strlen(bod->body); char *new_str = (char *)PR_Realloc(bod->body, L + length + 1); if (!new_str) return MIME_OUT_OF_MEMORY; bod->body = new_str; memcpy(bod->body + L, line, length); bod->body[L + length] = 0; return 0; } /* Otherwise we don't yet have a body, which means we're not done parsing our headers. */ if (!bod->hdrs) { bod->hdrs = MimeHeaders_new(); if (!bod->hdrs) return MIME_OUT_OF_MEMORY; } status = MimeHeaders_parse_line(line, length, bod->hdrs); if (status < 0) return status; /* If this line is blank, we're now done parsing headers, and should create a dummy body to show that. Gag. */ if (*line == '\r' || *line == '\n') { bod->body = strdup(""); if (!bod->body) return MIME_OUT_OF_MEMORY; } return 0; }
NS_IMETHODIMP nsRegionPh :: GetRects( nsRegionRectSet **aRects ) { /* 99.99% there is only one tile - so simplify things, while allow the general case to work as well */ if( mRegion && !mRegion->next ) { if( *aRects == nsnull ) *aRects = ( nsRegionRectSet * ) PR_Malloc( sizeof( nsRegionRectSet ) ); nsRegionRect *rect = (*aRects)->mRects; (*aRects)->mRectsLen = (*aRects)->mNumRects = 1; rect->x = mRegion->rect.ul.x; rect->y = mRegion->rect.ul.y; rect->width = mRegion->rect.lr.x - mRegion->rect.ul.x + 1; rect->height = mRegion->rect.lr.y - mRegion->rect.ul.y + 1; (*aRects)->mArea = rect->width * rect->height; return NS_OK; } /* the general case - old code */ nsRegionRectSet *rects; int nbox = 0; nsRegionRect *rect; PhTile_t *t = mRegion; while( t ) { nbox++; t = t->next; } /* Count the Tiles */ rects = *aRects; if ((nsnull == rects) || (rects->mRectsLen < (PRUint32) nbox)) { void *buf = PR_Realloc(rects, sizeof(nsRegionRectSet) + (sizeof(nsRegionRect) * (nbox - 1)));//was -1 if (nsnull == buf) { if (nsnull != rects) rects->mNumRects = 0; return NS_OK; } rects = (nsRegionRectSet *) buf; rects->mRectsLen = nbox; } rects->mNumRects = nbox; rects->mArea = 0; rect = &rects->mRects[0]; t = mRegion; /* Reset tile indexer */ while( nbox-- ) { rect->x = tulx; rect->width = (tlrx - tulx+1); rect->y = tuly; rect->height = (tlry - tuly+1); rects->mArea += rect->width * rect->height; rect++; t = t->next; } *aRects = rects; return NS_OK; }
static void lexAppendc(int c) { lexBuf.strs[lexBuf.strsLen] = c; /* append up to zero termination */ if (c == 0) return; lexBuf.strsLen++; if (lexBuf.strsLen >= lexBuf.maxToken) { /* double the token string size */ lexBuf.maxToken <<= 1; lexBuf.strs = (char *)PR_Realloc(lexBuf.strs, lexBuf.maxToken); } }
void * PORT_Realloc(void *oldptr, size_t bytes) { void *rv; rv = (void *)PR_Realloc(oldptr, bytes); if (!rv) { ++port_allocFailures; PORT_SetError(SEC_ERROR_NO_MEMORY); } return rv; }
void * PORT_Realloc(void *oldptr, size_t bytes) { void *rv = NULL; if (bytes <= MAX_SIZE) { rv = PR_Realloc(oldptr, bytes); } if (!rv) { PORT_SetError(SEC_ERROR_NO_MEMORY); } return rv; }
nsresult nsMsgSendLater::BuildNewBuffer(const char* aBuf, uint32_t aCount, uint32_t *totalBufSize) { // Only build a buffer when there are leftovers... if (!mLeftoverBuffer) return NS_ERROR_FAILURE; int32_t leftoverSize = PL_strlen(mLeftoverBuffer); mLeftoverBuffer = (char *)PR_Realloc(mLeftoverBuffer, aCount + leftoverSize); if (!mLeftoverBuffer) return NS_ERROR_FAILURE; memcpy(mLeftoverBuffer + leftoverSize, aBuf, aCount); *totalBufSize = aCount + leftoverSize; return NS_OK; }
/* * FUNCTION: PKIX_PL_Realloc (see comments in pkix_pl_system.h) */ PKIX_Error * PKIX_PL_Realloc( void *ptr, PKIX_UInt32 size, void **pMemory, void *plContext) { PKIX_PL_NssContext *nssContext = NULL; void *result = NULL; PKIX_ENTER(MEM, "PKIX_PL_Realloc"); PKIX_NULLCHECK_ONE(pMemory); nssContext = (PKIX_PL_NssContext *)plContext; if (nssContext != NULL && nssContext->arena != NULL) { PKIX_MEM_DEBUG("\tCalling PORT_ArenaAlloc.\n"); result = PORT_ArenaAlloc(nssContext->arena, size); if (result){ PKIX_MEM_DEBUG("\tCalling PORT_Memcpy.\n"); PORT_Memcpy(result, ptr, size); } *pMemory = result; } else { PKIX_MEM_DEBUG("\tCalling PR_Realloc.\n"); result = (void *) PR_Realloc(ptr, size); if (result == NULL) { if (size == 0){ *pMemory = NULL; } else { PKIX_MEM_DEBUG ("Fatal Error Occurred: " "PR_Realloc failed.\n"); PKIX_ERROR_ALLOC_ERROR(); } } else { *pMemory = result; } } cleanup: PKIX_RETURN(MEM); }
static int push_tag(MimeMultipartRelated* relobj, const char* buf, int32_t size) { if (size + relobj->curtag_length > relobj->curtag_max) { relobj->curtag_max += 2 * size; if (relobj->curtag_max < 1024) relobj->curtag_max = 1024; if (!relobj->curtag) { relobj->curtag = (char*) PR_MALLOC(relobj->curtag_max); } else { relobj->curtag = (char*) PR_Realloc(relobj->curtag, relobj->curtag_max); } if (!relobj->curtag) return MIME_OUT_OF_MEMORY; } memcpy(relobj->curtag + relobj->curtag_length, buf, size); relobj->curtag_length += size; return 0; }
/* msg_make_full_address * * Given an e-mail address and a person's name, cons them together into a * single string of the form "name <address>", doing all the necessary quoting. * A new string is returned, which you must free when you're done with it. */ static char * msg_make_full_address(const char* name, const char* addr) { int nl = name ? strlen (name) : 0; int al = addr ? strlen (addr) : 0; char *buf, *s; PRUint32 buflen, slen; int L; if (al == 0) return 0; buflen = (nl * 2) + (al * 2) + 25; buf = (char *)PR_Malloc(buflen); if (!buf) return 0; if (nl > 0) { PL_strncpyz(buf, name, buflen); L = msg_quote_phrase_or_addr(buf, nl, PR_FALSE); s = buf + L; slen = buflen - L; if ( slen > 2 ) { *s++ = ' '; *s++ = '<'; slen -= 2; // for ' ' and '<' } } else { s = buf; slen = buflen; } PL_strncpyz(s, addr, slen); L = msg_quote_phrase_or_addr(s, al, PR_TRUE); s += L; if (nl > 0) *s++ = '>'; *s = 0; L = (s - buf) + 1; buf = (char *)PR_Realloc (buf, L); return buf; }
static void appendcOFile_(OFile *fp, char c) { if (fp->fail) return; stuff: if (fp->len+1 < fp->limit) { fp->s[fp->len] = c; fp->len++; return; } else if (fp->alloc) { fp->limit = fp->limit + OFILE_REALLOC_SIZE; fp->s = (char *)PR_Realloc(fp->s,fp->limit); if (fp->s) goto stuff; } if (fp->alloc) PR_FREEIF(fp->s); fp->s = 0; fp->fail = 1; }
//---------------------------------------------------------------------------------------- void nsSimpleCharString::ReallocData(PRUint32 inLength) // Reallocate mData to a new length. Since this presumably precedes a change to the string, // we want to detach ourselves if the data is shared by another string, even if the length // requested would not otherwise require a reallocation. //---------------------------------------------------------------------------------------- { PRUint32 newAllocLength = CalculateAllocLength(inLength); PRUint32 oldAllocLength = CalculateAllocLength(Length()); if (mData) { NS_ASSERTION(mData->mRefCount > 0, "String deleted too many times!"); if (mData->mRefCount == 1) { // We are the sole owner, so just change its length, if necessary. if (newAllocLength > oldAllocLength) mData = (Data*)PR_Realloc(mData, newAllocLength + sizeof(Data)); mData->mLength = inLength; mData->mString[inLength] = '\0'; // we may be truncating return; } } PRUint32 copyLength = Length(); if (inLength < copyLength) copyLength = inLength; Data* newData = (Data*)PR_Malloc(newAllocLength + sizeof(Data)); // If data was already allocated when we get to here, then we are cloning the data // from a shared pointer. if (mData) { memcpy(newData, mData, sizeof(Data) + copyLength); mData->mRefCount--; // Say goodbye } else newData->mString[0] = '\0'; mData = newData; mData->mRefCount = 1; mData->mLength = inLength; } // nsSimpleCharString::ReleaseData
nsresult DoGrowBuffer(int32_t desired_size, int32_t element_size, int32_t quantum, char **buffer, int32_t *size) { if (*size <= desired_size) { char *new_buf; int32_t increment = desired_size - *size; if (increment < quantum) // always grow by a minimum of N bytes increment = quantum; new_buf = (*buffer ? (char *) PR_Realloc (*buffer, (*size + increment) * (element_size / sizeof(char))) : (char *) PR_Malloc ((*size + increment) * (element_size / sizeof(char)))); if (! new_buf) return NS_ERROR_OUT_OF_MEMORY; *buffer = new_buf; *size += increment; } return NS_OK; }
extern "C" int mime_GrowBuffer (PRUint32 desired_size, PRUint32 element_size, PRUint32 quantum, char **buffer, PRInt32 *size) { if ((PRUint32) *size <= desired_size) { char *new_buf; PRUint32 increment = desired_size - *size; if (increment < quantum) /* always grow by a minimum of N bytes */ increment = quantum; new_buf = (*buffer ? (char *) PR_Realloc (*buffer, (*size + increment) * (element_size / sizeof(char))) : (char *) PR_MALLOC ((*size + increment) * (element_size / sizeof(char)))); if (! new_buf) return MIME_OUT_OF_MEMORY; *buffer = new_buf; *size += increment; } return 0; }
static PRPollDesc *_pr_setfd( PR_fd_set *set, PRInt16 flags, PRPollDesc *polldesc) { PRUintn fsidx, pdidx; PRPollDesc *poll = polldesc; if (NULL == set) return poll; /* First set the pr file handle osfds */ for (fsidx = 0; fsidx < set->hsize; fsidx++) { for (pdidx = 0; 1; pdidx++) { if ((PRFileDesc*)-1 == poll[pdidx].fd) { /* our vector is full - extend and condition it */ poll = (PRPollDesc*)PR_Realloc( poll, (pdidx + 1 + PD_INCR) * sizeof(PRPollDesc)); if (NULL == poll) goto out_of_memory; memset( poll + pdidx * sizeof(PRPollDesc), 0, PD_INCR * sizeof(PRPollDesc)); poll[pdidx + PD_INCR].fd = (PRFileDesc*)-1; } if ((NULL == poll[pdidx].fd) || (poll[pdidx].fd == set->harray[fsidx])) { /* PR_ASSERT(0 == (poll[pdidx].in_flags & flags)); */ /* either empty or prevously defined */ poll[pdidx].fd = set->harray[fsidx]; /* possibly redundant */ poll[pdidx].in_flags |= flags; /* possibly redundant */ break; } } } #if 0 /* Second set the native osfds */ for (fsidx = 0; fsidx < set->nsize; fsidx++) { for (pdidx = 0; ((PRFileDesc*)-1 != poll[pdidx].fd); pdidx++) { if ((PRFileDesc*)-1 == poll[pdidx].fd) { /* our vector is full - extend and condition it */ poll = PR_Realloc( poll, (pdidx + PD_INCR) * sizeof(PRPollDesc)); if (NULL == poll) goto out_of_memory; memset( poll + pdidx * sizeof(PRPollDesc), 0, PD_INCR * sizeof(PRPollDesc)); poll[(pdidx + PD_INCR)].fd = (PRFileDesc*)-1; } if ((NULL == poll[pdidx].fd) || (poll[pdidx].fd == set->narray[fsidx])) { /* either empty or prevously defined */ poll[pdidx].fd = set->narray[fsidx]; PR_ASSERT(0 == (poll[pdidx].in_flags & flags)); poll[pdidx].in_flags |= flags; break; } } } #endif /* 0 */ return poll; out_of_memory: if (NULL != polldesc) PR_DELETE(polldesc); return NULL; } /* _pr_setfd */
char * MimeHeaders_get (MimeHeaders *hdrs, const char *header_name, bool strip_p, bool all_p) { int i; int name_length; char *result = 0; if (!hdrs) return 0; NS_ASSERTION(header_name, "1.1 <*****@*****.**> 19 Mar 1999 12:00"); if (!header_name) return 0; /* Specifying strip_p and all_p at the same time doesn't make sense... */ NS_ASSERTION(!(strip_p && all_p), "1.1 <*****@*****.**> 19 Mar 1999 12:00"); /* One shouldn't be trying to read headers when one hasn't finished parsing them yet... but this can happen if the message ended prematurely, and has no body at all (as opposed to a null body, which is more normal.) So, if we try to read from the headers, let's assume that the headers are now finished. If they aren't in fact finished, then a later attempt to write to them will assert. */ if (!hdrs->done_p) { int status; hdrs->done_p = true; status = MimeHeaders_build_heads_list(hdrs); if (status < 0) return 0; } if (!hdrs->heads) /* Must not have been any headers. */ { NS_ASSERTION(hdrs->all_headers_fp == 0, "1.1 <*****@*****.**> 19 Mar 1999 12:00"); return 0; } name_length = strlen(header_name); for (i = 0; i < hdrs->heads_size; i++) { char *head = hdrs->heads[i]; char *end = (i == hdrs->heads_size-1 ? hdrs->all_headers + hdrs->all_headers_fp : hdrs->heads[i+1]); char *colon, *ocolon; NS_ASSERTION(head, "1.1 <*****@*****.**> 19 Mar 1999 12:00"); if (!head) continue; /* Quick hack to skip over BSD Mailbox delimiter. */ if (i == 0 && head[0] == 'F' && !strncmp(head, "From ", 5)) continue; /* Find the colon. */ for (colon = head; colon < end; colon++) if (*colon == ':') break; if (colon >= end) continue; /* Back up over whitespace before the colon. */ ocolon = colon; for (; colon > head && IS_SPACE(colon[-1]); colon--) ; /* If the strings aren't the same length, it doesn't match. */ if (name_length != colon - head ) continue; /* If the strings differ, it doesn't match. */ if (PL_strncasecmp(header_name, head, name_length)) continue; /* Otherwise, we've got a match. */ { char *contents = ocolon + 1; char *s; /* Skip over whitespace after colon. */ while (contents < end && IS_SPACE(contents[0])) { /* Mac or Unix style line break, followed by space or tab. */ if (contents < (end - 1) && (contents[0] == '\r' || contents[0] == '\n') && (contents[1] == ' ' || contents[1] == '\t')) contents += 2; /* Windows style line break, followed by space or tab. */ else if (contents < (end - 2) && contents[0] == '\r' && contents[1] == '\n' && (contents[2] == ' ' || contents[2] == '\t')) contents += 3; /* Any space or tab. */ else if (contents[0] == ' ' || contents[0] == '\t') contents++; /* If we get here, it's because this character is a line break followed by non-whitespace, or a line break followed by another line break */ else { end = contents; break; } } /* If we're supposed to strip at the first token, pull `end' back to the first whitespace or ';' after the first token. */ if (strip_p) { for (s = contents; s < end && *s != ';' && *s != ',' && !IS_SPACE(*s); s++) ; end = s; } /* Now allocate some storage. If `result' already has a value, enlarge it. Otherwise, just allocate a block. `s' gets set to the place where the new data goes. */ if (!result) { result = (char *) PR_MALLOC(end - contents + 1); if (!result) return 0; s = result; } else { int32_t L = strlen(result); s = (char *) PR_Realloc(result, (L + (end - contents + 10))); if (!s) { PR_Free(result); return 0; } result = s; s = result + L; /* Since we are tacking more data onto the end of the header field, we must make it be a well-formed continuation line, by separating the old and new data with CR-LF-TAB. */ *s++ = ','; /* #### only do this for addr headers? */ *s++ = MSG_LINEBREAK[0]; # if (MSG_LINEBREAK_LEN == 2) *s++ = MSG_LINEBREAK[1]; # endif *s++ = '\t'; } /* Take off trailing whitespace... */ while (end > contents && IS_SPACE(end[-1])) end--; if (end > contents) { /* Now copy the header's contents in... */ memcpy(s, contents, end - contents); s[end - contents] = 0; } else { s[0] = 0; } /* If we only wanted the first occurence of this header, we're done. */ if (!all_p) break; } } if (result && !*result) /* empty string */ { PR_Free(result); return 0; } return result; }
nsresult nsMsgSendLater::BuildHeaders() { char *buf = m_headers; char *buf_end = buf + m_headersFP; PR_FREEIF(m_to); PR_FREEIF(m_bcc); PR_FREEIF(m_newsgroups); PR_FREEIF(m_newshost); PR_FREEIF(m_fcc); PR_FREEIF(mIdentityKey); PR_FREEIF(mAccountKey); m_flags = 0; while (buf < buf_end) { bool prune_p = false; bool do_flags_p = false; char *colon = PL_strchr(buf, ':'); char *end; char *value = 0; char **header = 0; char *header_start = buf; if (! colon) break; end = colon; while (end > buf && (*end == ' ' || *end == '\t')) end--; switch (buf [0]) { case 'B': case 'b': if (!PL_strncasecmp ("BCC", buf, end - buf)) { header = &m_bcc; prune_p = true; } break; case 'C': case 'c': if (!PL_strncasecmp ("CC", buf, end - buf)) header = &m_to; else if (!PL_strncasecmp (HEADER_CONTENT_LENGTH, buf, end - buf)) prune_p = true; break; case 'F': case 'f': if (!PL_strncasecmp ("FCC", buf, end - buf)) { header = &m_fcc; prune_p = true; } break; case 'L': case 'l': if (!PL_strncasecmp ("Lines", buf, end - buf)) prune_p = true; break; case 'N': case 'n': if (!PL_strncasecmp ("Newsgroups", buf, end - buf)) header = &m_newsgroups; break; case 'S': case 's': if (!PL_strncasecmp ("Sender", buf, end - buf)) prune_p = true; break; case 'T': case 't': if (!PL_strncasecmp ("To", buf, end - buf)) header = &m_to; break; case 'X': case 'x': { int32_t headLen = PL_strlen(HEADER_X_MOZILLA_STATUS2); if (headLen == end - buf && !PL_strncasecmp(HEADER_X_MOZILLA_STATUS2, buf, end - buf)) prune_p = true; else if (PL_strlen(HEADER_X_MOZILLA_STATUS) == end - buf && !PL_strncasecmp(HEADER_X_MOZILLA_STATUS, buf, end - buf)) prune_p = do_flags_p = true; else if (!PL_strncasecmp(HEADER_X_MOZILLA_DRAFT_INFO, buf, end - buf)) prune_p = true; else if (!PL_strncasecmp(HEADER_X_MOZILLA_KEYWORDS, buf, end - buf)) prune_p = true; else if (!PL_strncasecmp(HEADER_X_MOZILLA_NEWSHOST, buf, end - buf)) { prune_p = true; header = &m_newshost; } else if (!PL_strncasecmp(HEADER_X_MOZILLA_IDENTITY_KEY, buf, end - buf)) { prune_p = true; header = &mIdentityKey; } else if (!PL_strncasecmp(HEADER_X_MOZILLA_ACCOUNT_KEY, buf, end - buf)) { prune_p = true; header = &mAccountKey; } break; } } buf = colon + 1; while (*buf == ' ' || *buf == '\t') buf++; value = buf; SEARCH_NEWLINE: while (*buf != 0 && *buf != '\r' && *buf != '\n') buf++; if (buf+1 >= buf_end) ; // If "\r\n " or "\r\n\t" is next, that doesn't terminate the header. else if (buf+2 < buf_end && (buf[0] == '\r' && buf[1] == '\n') && (buf[2] == ' ' || buf[2] == '\t')) { buf += 3; goto SEARCH_NEWLINE; } // If "\r " or "\r\t" or "\n " or "\n\t" is next, that doesn't terminate // the header either. else if ((buf[0] == '\r' || buf[0] == '\n') && (buf[1] == ' ' || buf[1] == '\t')) { buf += 2; goto SEARCH_NEWLINE; } if (header) { int L = buf - value; if (*header) { char *newh = (char*) PR_Realloc ((*header), PL_strlen(*header) + L + 10); if (!newh) return NS_ERROR_OUT_OF_MEMORY; *header = newh; newh = (*header) + PL_strlen (*header); *newh++ = ','; *newh++ = ' '; memcpy(newh, value, L); newh [L] = 0; } else { *header = (char *) PR_Malloc(L+1); if (!*header) return NS_ERROR_OUT_OF_MEMORY; memcpy((*header), value, L); (*header)[L] = 0; } } else if (do_flags_p) { int i; char *s = value; PR_ASSERT(*s != ' ' && *s != '\t'); m_flags = 0; for (i=0 ; i<4 ; i++) { m_flags = (m_flags << 4) | UNHEX(*s); s++; } } if (*buf == '\r' || *buf == '\n') { if (*buf == '\r' && buf[1] == '\n') buf++; buf++; } if (prune_p) { char *to = header_start; char *from = buf; while (from < buf_end) *to++ = *from++; buf = header_start; buf_end = to; m_headersFP = buf_end - m_headers; } } m_headers[m_headersFP++] = '\r'; m_headers[m_headersFP++] = '\n'; // Now we have parsed out all of the headers we need and we // can proceed. return NS_OK; }
NS_IMETHODIMP nsUnicodeToJamoTTF::Convert(const PRUnichar * aSrc, PRInt32 * aSrcLength, char * aDest, PRInt32 * aDestLength) { nsresult rv = NS_OK; mByteOff = 0; // This should never happen, but it happens under MS Windows, somehow... if (mJamoCount > mJamosMaxLength) { NS_WARNING("mJamoCount > mJamoMaxLength on entering Convert()"); Reset(); } for (PRInt32 charOff = 0; charOff < *aSrcLength; charOff++) { PRUnichar ch = aSrc[charOff]; // Syllable boundary check. Ref. : Unicode 3.2 section 3.11 if (mJamoCount != 0 && gIsBoundary[CHAR_CLASS(mJamos[mJamoCount - 1])][CHAR_CLASS(ch)]) { composeHangul(aDest); mJamoCount = 0; } // Ignore tone marks other than the first in a sequence of tone marks. else if (mJamoCount != 0 && IS_TONE(mJamos[mJamoCount - 1]) && IS_TONE(ch)) { --mJamoCount; composeHangul(aDest); mJamoCount = 0; // skip over tone marks from the second on in a series. while (IS_TONE(ch) && ++charOff < *aSrcLength) ch = aSrc[charOff]; if (!IS_TONE(ch)) { mJamos[mJamoCount++] = ch; continue; } else break; } if (mJamoCount == mJamosMaxLength) { mJamosMaxLength++; if (mJamos == mJamosStatic) { mJamos = (PRUnichar *) PR_Malloc(sizeof(PRUnichar) * mJamosMaxLength); if (!mJamos) return NS_ERROR_OUT_OF_MEMORY; memcpy(mJamos, mJamosStatic, sizeof(PRUnichar) * mJamoCount); } else { mJamos = (PRUnichar *) PR_Realloc(mJamos, sizeof(PRUnichar) * mJamosMaxLength); if (!mJamos) return NS_ERROR_OUT_OF_MEMORY; } } mJamos[mJamoCount++] = ch; } if (mJamoCount != 0) composeHangul(aDest); mJamoCount = 0; *aDestLength = mByteOff; return rv; }
/* This parses and converts the base64 format for binary encoding into * a decoded buffer (allocated with new). See RFC 1521. */ static char *lexGetDataFromBase64() { unsigned long bytesLen = 0, bytesMax = 0; int quadIx = 0, pad = 0; unsigned long trip = 0; unsigned char b; int c; unsigned char *bytes = nullptr; unsigned char *oldBytes = nullptr; DBG_(("db: lexGetDataFromBase64\n")); while (1) { c = lexGetc(); if (c == '\n') { ++mime_lineNum; if (lexLookahead() == '\n') { /* a '\n' character by itself means end of data */ break; } else continue; /* ignore '\n' */ } else { if ((c >= 'A') && (c <= 'Z')) b = (unsigned char)(c - 'A'); else if ((c >= 'a') && (c <= 'z')) b = (unsigned char)(c - 'a') + 26; else if ((c >= '0') && (c <= '9')) b = (unsigned char)(c - '0') + 52; else if (c == '+') b = 62; else if (c == '/') b = 63; else if (c == '=' && (quadIx == 2 || quadIx == 3)) { b = 0; pad++; } else if ((c == ' ') || (c == '\t')) { continue; } else { /* error condition */ if (bytes) PR_Free(bytes); else if (oldBytes) PR_Free(oldBytes); /* error recovery: skip until 2 adjacent newlines. */ DBG_(("db: invalid character 0x%x '%c'\n", c, c)); if (c != EOF) { c = lexGetc(); while (c != EOF) { if (c == '\n' && lexLookahead() == '\n') { ++mime_lineNum; break; } c = lexGetc(); } } return NULL; } trip = (trip << 6) | b; if (++quadIx == 4) { unsigned char outBytes[3]; int numOut; int i; for (i = 0; i < 3; i++) { outBytes[2 - i] = (unsigned char)(trip & 0xFF); trip >>= 8; } numOut = 3 - pad; if (bytesLen + numOut > bytesMax) { if (!bytes) { bytesMax = 1024; } else { bytesMax <<= 2; oldBytes = bytes; } bytes = (unsigned char *)PR_Realloc(oldBytes, bytesMax); if (!bytes) { mime_error("out of memory while processing BASE64 data\n"); break; } } if (bytes) { memcpy(bytes + bytesLen, outBytes, numOut); bytesLen += numOut; } trip = 0; quadIx = 0; pad = 0; } } } /* while */
NS_IMETHODIMP nsRegionGTK::GetRects(nsRegionRectSet **aRects) { *aRects = nsnull; if (!mRegion) return NS_OK; nsRegionRectSet *rects = nsnull; GdkRegionPrivate *priv = nsnull; Region pRegion; int nbox = 0; BOX *pbox = nsnull; nsRegionRect *rect = nsnull; priv = (GdkRegionPrivate *)mRegion; pRegion = priv->xregion; pbox = pRegion->rects; nbox = pRegion->numRects; NS_ASSERTION(!(nsnull == aRects), "bad ptr"); //code lifted from old xfe. MMP rects = *aRects; if ((nsnull == rects) || (rects->mRectsLen < (PRUint32)nbox)) { void *buf = PR_Realloc(rects, sizeof(nsRegionRectSet) + (sizeof(nsRegionRect) * (nbox - 1))); if (nsnull == buf) { if (nsnull != rects) rects->mNumRects = 0; return NS_OK; } rects = (nsRegionRectSet *)buf; rects->mRectsLen = nbox; } rects->mNumRects = nbox; rects->mArea = 0; rect = &rects->mRects[0]; while (nbox--) { rect->x = pbox->x1; rect->width = (pbox->x2 - pbox->x1); rect->y = pbox->y1; rect->height = (pbox->y2 - pbox->y1); rects->mArea += rect->width * rect->height; pbox++; rect++; } *aRects = rects; return NS_OK; }
// This method is called when there's more data available off the // network, but it's also called from our data pump when we're feeding // the plugin data that we already got off the network, but the plugin // was unable to consume it at the point it arrived. In the case when // the plugin pump calls this method, the input argument will be null, // and the length will be the number of bytes available in our // internal buffer. nsresult nsNPAPIPluginStreamListener::OnDataAvailable(nsPluginStreamListenerPeer* streamPeer, nsIInputStream* input, uint32_t length) { if (!length || !mInst || !mInst->CanFireNotifications()) return NS_ERROR_FAILURE; PluginDestructionGuard guard(mInst); // Just in case the caller switches plugin info on us. mStreamListenerPeer = streamPeer; nsNPAPIPlugin* plugin = mInst->GetPlugin(); if (!plugin || !plugin->GetLibrary()) return NS_ERROR_FAILURE; NPPluginFuncs* pluginFunctions = plugin->PluginFuncs(); // check out if plugin implements NPP_Write call if (!pluginFunctions->write) return NS_ERROR_FAILURE; // it'll cancel necko transaction if (!mStreamBuffer) { // To optimize the mem usage & performance we have to allocate // mStreamBuffer here in first ODA when length of data available // in input stream is known. mStreamBuffer will be freed in DTOR. // we also have to remember the size of that buff to make safe // consecutive Read() calls form input stream into our buff. uint32_t contentLength; streamPeer->GetLength(&contentLength); mStreamBufferSize = NS_MAX(length, contentLength); // Limit the size of the initial buffer to MAX_PLUGIN_NECKO_BUFFER // (16k). This buffer will grow if needed, as in the case where // we're getting data faster than the plugin can process it. mStreamBufferSize = NS_MIN(mStreamBufferSize, uint32_t(MAX_PLUGIN_NECKO_BUFFER)); mStreamBuffer = (char*) PR_Malloc(mStreamBufferSize); if (!mStreamBuffer) return NS_ERROR_OUT_OF_MEMORY; } // prepare NPP_ calls params NPP npp; mInst->GetNPP(&npp); int32_t streamPosition; streamPeer->GetStreamOffset(&streamPosition); int32_t streamOffset = streamPosition; if (input) { streamOffset += length; // Set new stream offset for the next ODA call regardless of how // following NPP_Write call will behave we pretend to consume all // data from the input stream. It's possible that current steam // position will be overwritten from NPP_RangeRequest call made // from NPP_Write, so we cannot call SetStreamOffset after // NPP_Write. // // Note: there is a special case when data flow should be // temporarily stopped if NPP_WriteReady returns 0 (bug #89270) streamPeer->SetStreamOffset(streamOffset); // set new end in case the content is compressed // initial end is less than end of decompressed stream // and some plugins (e.g. acrobat) can fail. if ((int32_t)mNPStreamWrapper->mNPStream.end < streamOffset) mNPStreamWrapper->mNPStream.end = streamOffset; } nsresult rv = NS_OK; while (NS_SUCCEEDED(rv) && length > 0) { if (input && length) { if (mStreamBufferSize < mStreamBufferByteCount + length && mIsSuspended) { // We're in the ::OnDataAvailable() call that we might get // after suspending a request, or we suspended the request // from within this ::OnDataAvailable() call while there's // still data in the input, and we don't have enough space to // store what we got off the network. Reallocate our internal // buffer. mStreamBufferSize = mStreamBufferByteCount + length; char *buf = (char*)PR_Realloc(mStreamBuffer, mStreamBufferSize); if (!buf) return NS_ERROR_OUT_OF_MEMORY; mStreamBuffer = buf; } uint32_t bytesToRead = NS_MIN(length, mStreamBufferSize - mStreamBufferByteCount); uint32_t amountRead = 0; rv = input->Read(mStreamBuffer + mStreamBufferByteCount, bytesToRead, &amountRead); NS_ENSURE_SUCCESS(rv, rv); if (amountRead == 0) { NS_NOTREACHED("input->Read() returns no data, it's almost impossible " "to get here"); break; } mStreamBufferByteCount += amountRead; length -= amountRead; } else { // No input, nothing to read. Set length to 0 so that we don't // keep iterating through this outer loop any more. length = 0; } // Temporary pointer to the beginning of the data we're writing as // we loop and feed the plugin data. char *ptrStreamBuffer = mStreamBuffer; // it is possible plugin's NPP_Write() returns 0 byte consumed. We // use zeroBytesWriteCount to count situation like this and break // the loop int32_t zeroBytesWriteCount = 0; // mStreamBufferByteCount tells us how many bytes there are in the // buffer. WriteReady returns to us how many bytes the plugin is // ready to handle. while (mStreamBufferByteCount > 0) { int32_t numtowrite; if (pluginFunctions->writeready) { NPPAutoPusher nppPusher(npp); NS_TRY_SAFE_CALL_RETURN(numtowrite, (*pluginFunctions->writeready)(npp, &mNPStreamWrapper->mNPStream), mInst, NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO); NPP_PLUGIN_LOG(PLUGIN_LOG_NOISY, ("NPP WriteReady called: this=%p, npp=%p, " "return(towrite)=%d, url=%s\n", this, npp, numtowrite, mNPStreamWrapper->mNPStream.url)); if (!mStreamStarted) { // The plugin called NPN_DestroyStream() from within // NPP_WriteReady(), kill the stream. return NS_BINDING_ABORTED; } // if WriteReady returned 0, the plugin is not ready to handle // the data, suspend the stream (if it isn't already // suspended). // // Also suspend the stream if the stream we're loading is not // a javascript: URL load that was initiated during plugin // initialization and there currently is such a stream // loading. This is done to work around a Windows Media Player // plugin bug where it can't deal with being fed data for // other streams while it's waiting for data from the // javascript: URL loads it requests during // initialization. See bug 386493 for more details. if (numtowrite <= 0 || (!mIsPluginInitJSStream && PluginInitJSLoadInProgress())) { if (!mIsSuspended) { SuspendRequest(); } // Break out of the inner loop, but keep going through the // outer loop in case there's more data to read from the // input stream. break; } numtowrite = NS_MIN(numtowrite, mStreamBufferByteCount); } else { // if WriteReady is not supported by the plugin, just write // the whole buffer numtowrite = mStreamBufferByteCount; } NPPAutoPusher nppPusher(npp); int32_t writeCount = 0; // bytes consumed by plugin instance NS_TRY_SAFE_CALL_RETURN(writeCount, (*pluginFunctions->write)(npp, &mNPStreamWrapper->mNPStream, streamPosition, numtowrite, ptrStreamBuffer), mInst, NS_PLUGIN_CALL_UNSAFE_TO_REENTER_GECKO); NPP_PLUGIN_LOG(PLUGIN_LOG_NOISY, ("NPP Write called: this=%p, npp=%p, pos=%d, len=%d, " "buf=%s, return(written)=%d, url=%s\n", this, npp, streamPosition, numtowrite, ptrStreamBuffer, writeCount, mNPStreamWrapper->mNPStream.url)); if (!mStreamStarted) { // The plugin called NPN_DestroyStream() from within // NPP_Write(), kill the stream. return NS_BINDING_ABORTED; } if (writeCount > 0) { NS_ASSERTION(writeCount <= mStreamBufferByteCount, "Plugin read past the end of the available data!"); writeCount = NS_MIN(writeCount, mStreamBufferByteCount); mStreamBufferByteCount -= writeCount; streamPosition += writeCount; zeroBytesWriteCount = 0; if (mStreamBufferByteCount > 0) { // This alignment code is most likely bogus, but we'll leave // it in for now in case it matters for some plugins on some // architectures. Who knows... if (writeCount % sizeof(intptr_t)) { // memmove will take care about alignment memmove(mStreamBuffer, ptrStreamBuffer + writeCount, mStreamBufferByteCount); ptrStreamBuffer = mStreamBuffer; } else { // if aligned we can use ptrStreamBuffer += to eliminate // memmove() ptrStreamBuffer += writeCount; } } } else if (writeCount == 0) { // if NPP_Write() returns writeCount == 0 lets say 3 times in // a row, suspend the request and continue feeding the plugin // the data we got so far. Once that data is consumed, we'll // resume the request. if (mIsSuspended || ++zeroBytesWriteCount == 3) { if (!mIsSuspended) { SuspendRequest(); } // Break out of the for loop, but keep going through the // while loop in case there's more data to read from the // input stream. break; } } else { // Something's really wrong, kill the stream. rv = NS_ERROR_FAILURE; break; } } // end of inner while loop if (mStreamBufferByteCount && mStreamBuffer != ptrStreamBuffer) { memmove(mStreamBuffer, ptrStreamBuffer, mStreamBufferByteCount); } } if (streamPosition != streamOffset) { // The plugin didn't consume all available data, or consumed some // of our cached data while we're pumping cached data. Adjust the // plugin info's stream offset to match reality, except if the // plugin info's stream offset was set by a re-entering // NPN_RequestRead() call. int32_t postWriteStreamPosition; streamPeer->GetStreamOffset(&postWriteStreamPosition); if (postWriteStreamPosition == streamOffset) { streamPeer->SetStreamOffset(streamPosition); } } return rv; }
int MimeHeaders_build_heads_list(MimeHeaders *hdrs) { char *s; char *end; int i; NS_ASSERTION(hdrs, "1.1 <*****@*****.**> 19 Mar 1999 12:00"); if (!hdrs) return -1; NS_ASSERTION(hdrs->done_p && !hdrs->heads, "1.1 <*****@*****.**> 19 Mar 1999 12:00"); if (!hdrs->done_p || hdrs->heads) return -1; if (hdrs->all_headers_fp == 0) { /* Must not have been any headers (we got the blank line right away.) */ PR_FREEIF (hdrs->all_headers); hdrs->all_headers_size = 0; return 0; } /* At this point, we might as well realloc all_headers back down to the minimum size it must be (it could be up to 1k bigger.) But don't bother if we're only off by a tiny bit. */ NS_ASSERTION(hdrs->all_headers_fp <= hdrs->all_headers_size, "1.1 <*****@*****.**> 19 Mar 1999 12:00"); if (hdrs->all_headers_fp + 60 <= hdrs->all_headers_size) { char *ls = (char *)PR_Realloc(hdrs->all_headers, hdrs->all_headers_fp); if (ls) /* can this ever fail? we're making it smaller... */ { hdrs->all_headers = ls; /* in case it got relocated */ hdrs->all_headers_size = hdrs->all_headers_fp; } } /* First go through and count up the number of headers in the block. */ end = hdrs->all_headers + hdrs->all_headers_fp; for (s = hdrs->all_headers; s < end; s++) { if (s < (end-1) && s[0] == '\r' && s[1] == '\n') /* CRLF -> LF */ s++; if ((s[0] == '\r' || s[0] == '\n') && /* we're at a newline, and */ (s >= (end-1) || /* we're at EOF, or */ !(s[1] == ' ' || s[1] == '\t'))) /* next char is nonwhite */ hdrs->heads_size++; } /* Now allocate storage for the pointers to each of those headers. */ hdrs->heads = (char **) PR_MALLOC((hdrs->heads_size + 1) * sizeof(char *)); if (!hdrs->heads) return MIME_OUT_OF_MEMORY; memset(hdrs->heads, 0, (hdrs->heads_size + 1) * sizeof(char *)); /* Now make another pass through the headers, and this time, record the starting position of each header. */ i = 0; hdrs->heads[i++] = hdrs->all_headers; s = hdrs->all_headers; while (s < end) { SEARCH_NEWLINE: while (s < end && *s != '\r' && *s != '\n') s++; if (s >= end) break; /* If "\r\n " or "\r\n\t" is next, that doesn't terminate the header. */ else if (s+2 < end && (s[0] == '\r' && s[1] == '\n') && (s[2] == ' ' || s[2] == '\t')) { s += 3; goto SEARCH_NEWLINE; } /* If "\r " or "\r\t" or "\n " or "\n\t" is next, that doesn't terminate the header either. */ else if (s+1 < end && (s[0] == '\r' || s[0] == '\n') && (s[1] == ' ' || s[1] == '\t')) { s += 2; goto SEARCH_NEWLINE; } /* At this point, `s' points before a header-terminating newline. Move past that newline, and store that new position in `heads'. */ if (*s == '\r') s++; if (s >= end) break; if (*s == '\n') s++; if (s < end) { NS_ASSERTION(! (i > hdrs->heads_size), "1.1 <*****@*****.**> 19 Mar 1999 12:00"); if (i > hdrs->heads_size) return -1; hdrs->heads[i++] = s; } } return 0; }