Ejemplo n.º 1
0
nsresult nsCollationWin::AllocateRawSortKey(int32_t strength, 
                                            const nsAString& stringIn, uint8_t** key, uint32_t* outLen)
{
  int byteLen;
  void *buffer;
  nsresult res = NS_OK;
  DWORD dwMapFlags = LCMAP_SORTKEY;

  if (strength == kCollationCaseInSensitive)
    dwMapFlags |= NORM_IGNORECASE;

  byteLen = LCMapStringW(mLCID, dwMapFlags, 
                         (LPCWSTR) PromiseFlatString(stringIn).get(),
                         -1, NULL, 0);
  buffer = PR_Malloc(byteLen);
  if (!buffer) {
    res = NS_ERROR_OUT_OF_MEMORY;
  } else {
    *key = (uint8_t *)buffer;
    *outLen = LCMapStringW(mLCID, dwMapFlags, 
                           (LPCWSTR) PromiseFlatString(stringIn).get(),
                           -1, (LPWSTR) buffer, byteLen);
  }
  return res;
}
Ejemplo n.º 2
0
static void OutputDebugStringA(const char* msg) {
    int len = MultiByteToWideChar(CP_ACP, 0, msg, -1, 0, 0);
    WCHAR *wMsg = (WCHAR *)PR_Malloc(len * sizeof(WCHAR));
    MultiByteToWideChar(CP_ACP, 0, msg, -1, wMsg, len);
    OutputDebugStringW(wMsg);
    PR_Free(wMsg);
}
Ejemplo n.º 3
0
/*
//////////////////////////////////////////////////////////////////////////
*/
static char*
PR_Strdup(const char* str)
{
	char *tmp = (char*) PR_Malloc(strlen(str)+1);
	strcpy(tmp, str);
	return tmp;
}
/***********************************************************************
**
** J S S _ t h r o w M s g P r E r r A r g
**
** Throw an exception in native code.  You should return right after
** calling this function.
**
** throwableClassName is the name of the throwable you are throwing in
** JNI class name format (xxx/xx/xxx/xxx). It must not be NULL.
**
** message is the message parameter of the throwable. It must not be NULL.
** If you don't have a message, call JSS_throw.
**
** errCode is a PRErrorCode returned from PR_GetError().
**
** Example:
**      JSS_throwMsg(env, ILLEGAL_ARGUMENT_EXCEPTION, PR_GetError());
**      return -1;
*/
void
JSS_throwMsgPrErrArg(JNIEnv *env, char *throwableClassName, char *message,
    PRErrorCode errCode)
{
    const char *errStr = JSS_strerror(errCode);
    char *msg = NULL;
    int msgLen;

    if( errStr == NULL ) {
        errStr = "Unknown error";
    }

    msgLen = strlen(message) + strlen(errStr) + 40;
    msg = PR_Malloc(msgLen);
    if( msg == NULL ) {
        JSS_throw(env, OUT_OF_MEMORY_ERROR);
        goto finish;
    }
    PR_snprintf(msg, msgLen, "%s: (%ld) %s", message, errCode, errStr);

    JSS_throwMsg(env, throwableClassName, msg);

finish:
    if(msg != NULL) {
        PR_Free(msg);
    }
}
/***********************************************************************
 * J S S _ B y t e A r r a y T o S E C I t e m
 *
 * Copies the contents of a Java byte array into a new SECItem.
 *
 * byteArray
 *      A Java byte array. Must not be NULL.
 * RETURNS
 *      A newly allocated SECItem, or NULL iff an exception was thrown.
 */
SECItem*
JSS_ByteArrayToSECItem(JNIEnv *env, jbyteArray byteArray)
{
    SECItem *item = NULL;

    PR_ASSERT(env!=NULL && byteArray!=NULL);

    /* Create a new SECItem */
    item = PR_NEW(SECItem);
    if( item == NULL ) {
        JSS_throw(env, OUT_OF_MEMORY_ERROR);
        goto finish;
    }

    /* Setup the length, allocate the buffer */
    item->len = (*env)->GetArrayLength(env, byteArray);
    item->data = PR_Malloc(item->len);

    /* copy the bytes from the byte array into the SECItem */
    (*env)->GetByteArrayRegion(env, byteArray, 0, item->len,
                (jbyte*)item->data);
    if( (*env)->ExceptionOccurred(env) ) {
        SECITEM_FreeItem(item, PR_TRUE /*freeit*/);
        item = NULL;
    }

finish:
    return item;
}
Ejemplo n.º 6
0
void nsMsgBodyHandler::StripHtml (nsCString &pBufInOut)
{
  char *pBuf = (char*) PR_Malloc (pBufInOut.Length() + 1);
  if (pBuf)
  {
    char *pWalk = pBuf;
    
    char *pWalkInOut = (char *) pBufInOut.get();
    bool inTag = false;
    while (*pWalkInOut) // throw away everything inside < >
    {
      if (!inTag)
        if (*pWalkInOut == '<')
          inTag = PR_TRUE;
        else
          *pWalk++ = *pWalkInOut;
        else
          if (*pWalkInOut == '>')
            inTag = PR_FALSE;
          pWalkInOut++;
    }
    *pWalk = 0; // null terminator
    
    pBufInOut.Adopt(pBuf);
  }
}
Ejemplo n.º 7
0
//
// remember the name and series of a token in a particular slot.
// This is important because the name is no longer available when
// the token is removed. If listeners depended on this information,
// They would be out of luck. It also is a handy way of making sure
// we don't generate spurious insertion and removal events as the slot
// cycles through various states.
//
void
SmartCardMonitoringThread::SetTokenName(CK_SLOT_ID slotid, 
                                       const char *tokenName, PRUint32 series)
{
  if (mHash) {
    if (tokenName) {
      int len = strlen(tokenName) + 1;
      /* this must match the allocator used in
       * PLHashAllocOps.freeEntry DefaultFreeEntry */
      char *entry = (char *)PR_Malloc(len+sizeof(PRUint32));
     
      if (entry) {  
        memcpy(entry,&series,sizeof(PRUint32));
        memcpy(&entry[sizeof(PRUint32)],tokenName,len);

        PL_HashTableAdd(mHash,(void *)slotid, entry); /* adopt */
        return;
      }
    } 
    else {
      // if tokenName was not provided, remove the old one (implicit delete)
      PL_HashTableRemove(mHash,(void *)slotid);
    }
  }
}
Ejemplo n.º 8
0
nsresult
nsMsgAttachmentHandler::LoadDataFromFile(nsILocalFile *file, nsString &sigData, PRBool charsetConversion)
{
    PRInt32       readSize;
    char          *readBuf;

    nsCOMPtr <nsIInputStream> inputFile;
    nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(inputFile), file);
    if (NS_FAILED(rv))
        return NS_MSG_ERROR_WRITING_FILE;

    PRInt64 fileSize;
    file->GetFileSize(&fileSize);
    readSize = (PRUint32) fileSize;

    readBuf = (char *)PR_Malloc(readSize + 1);
    if (!readBuf)
        return NS_ERROR_OUT_OF_MEMORY;
    memset(readBuf, 0, readSize + 1);

    PRUint32 bytesRead;
    inputFile->Read(readBuf, readSize, &bytesRead);
    inputFile->Close();

    if (charsetConversion)
    {
        if (NS_FAILED(ConvertToUnicode(m_charset, nsDependentCString(readBuf), sigData)))
            CopyASCIItoUTF16(readBuf, sigData);
    }
    else
        CopyASCIItoUTF16(readBuf, sigData);

    PR_FREEIF(readBuf);
    return NS_OK;
}
Ejemplo n.º 9
0
PRStatus
_PR_MD_CREATE_THREAD(PRThread *thread,
                     void (*start)(void *),
                     PRThreadPriority priority,
                     PRThreadScope scope,
                     PRThreadState state,
                     PRUint32 stackSize)
{
    PARAMSTORE* params = PR_Malloc(sizeof(PARAMSTORE));
    params->start = start;
    params->thread = thread;
    thread->md.handle = thread->id = (TID) _beginthread(ExcpStartFunc,
                                     NULL,
                                     thread->stack->stackSize,
                                     params);
    if(thread->md.handle == -1) {
        return PR_FAILURE;
    }

    /*
     * On OS/2, a thread is created with a thread priority of
     * THREAD_PRIORITY_NORMAL
     */

    if (priority != PR_PRIORITY_NORMAL) {
        _PR_MD_SET_PRIORITY(&(thread->md), priority);
    }

    return PR_SUCCESS;
}
Ejemplo n.º 10
0
/**
 * Called from PL_HashTableEnumerateEntries
 * A pointer to a PRCList (circular linked list) is passed in. 
 * Once enumeration is complete, the PRCList will contain a lexically
 * ordered list of a copy of the keys in the hash.  
 * The caller needs to free the copies
 */ 
static PRIntn OrderLoop(PLHashEntry *he, PRIntn index, void *arg)
{
    PRCList *qp = (PRCList *)arg;
    OrderedEntry_t *entry;

    if (he != NULL) {
        entry = (OrderedEntry_t *) PR_Malloc(sizeof(OrderedEntry_t));
        entry->key = PL_strdup((char *) he->key);
        if (index ==0) {
            PR_APPEND_LINK((PRCList *)entry, qp);
            return HT_ENUMERATE_NEXT;
        }
        PRCList *head = PR_LIST_HEAD(qp);
        PRCList *next;
        while (head != qp) {
            OrderedEntry_t *current = (OrderedEntry_t *) head;
            if (strcmp((char *) he->key, (char *) current->key) <=0) 
                break;
            next = PR_NEXT_LINK(head);
            head = next;
        }
        PR_INSERT_BEFORE((PRCList*) entry, head);
        return HT_ENUMERATE_NEXT;
    } else {
        return HT_ENUMERATE_STOP;
    }
}
Ejemplo n.º 11
0
nsInstallUninstall::nsInstallUninstall( nsInstall* inInstall,
                                        const nsString& regName,
                                        PRInt32 *error)

: nsInstallObject(inInstall)
{
    MOZ_COUNT_CTOR(nsInstallUninstall);

    if (regName.IsEmpty()) 
    {
        *error = nsInstall::INVALID_ARGUMENTS;
        return;
    }
    
    mRegName.Assign(regName);

    char* userName = (char*)PR_Malloc(MAXREGPATHLEN);
    PRInt32 err = VR_GetUninstallUserName( NS_CONST_CAST(char*, NS_ConvertUCS2toUTF8(regName).get()),
                                           userName, 
                                           MAXREGPATHLEN );
    
    mUIName.AssignWithConversion(userName);
    
    if (err != REGERR_OK)
    {
        *error = nsInstall::NO_SUCH_COMPONENT;
    }
    
    PR_FREEIF(userName);
    
}
nsresult
nsSubscribableServer::CreateNode(SubscribeTreeNode *parent, const char *name, SubscribeTreeNode **result)
{
    NS_ASSERTION(result && name, "result or name is null");
    if (!result || !name) return NS_ERROR_NULL_POINTER;

    *result = (SubscribeTreeNode *) PR_Malloc(sizeof(SubscribeTreeNode));
    if (!*result) return NS_ERROR_OUT_OF_MEMORY;

    (*result)->name = strdup(name);
    if (!(*result)->name) return NS_ERROR_OUT_OF_MEMORY;

    (*result)->parent = parent;
    (*result)->prevSibling = nullptr;
    (*result)->nextSibling = nullptr;
    (*result)->firstChild = nullptr;
    (*result)->lastChild = nullptr;
    (*result)->isSubscribed = false;
    (*result)->isSubscribable = false;
#ifdef HAVE_SUBSCRIBE_DESCRIPTION
    (*result)->description = nullptr;
#endif
#ifdef HAVE_SUBSCRIBE_MESSAGES
    (*result)->messages = 0;
#endif
    (*result)->cachedChild = nullptr;

    if (parent) {
        parent->cachedChild = *result;
    }

    return NS_OK;
}
Ejemplo n.º 13
0
Archivo: Util.cpp Proyecto: encukou/pki
TPS_PUBLIC char *Util::URLEncode (Buffer &data)
{
	int i;
	BYTE *buf = (BYTE*)data;
        int len = (int)data.size();
	int sum = 0;

	for (i = 0; i < len; i ++) {
                if (buf[i] == ' ') { 
			sum+=1;
		} else if (isAlphaNumeric(buf[i])) { 
			sum+=1;
		} else { 
			sum+=3;
		}
	}
	char *ret = (char *)PR_Malloc(sum + 1); // allocate more than we may need
	char *cur = ret;

	for (i = 0; i < len; i ++) {
                if (buf[i] == ' ') { 
			*cur++ = '+'; 
		} else if (isAlphaNumeric(buf[i])) { 
			*cur++ = buf[i]; 
		} else { 
			*cur++ = '%'; 
			*cur++ = bin2hex(buf[i] >> 4); 
			*cur++ = bin2hex(buf[i]); 
		}
	}
	*cur = '\0'; // null-terminated
	return ret;
}
Ejemplo n.º 14
0
/* Returned string needs to be PR_Free'd by caller */
static char *LoadRCDATAString( HMODULE hMod, ULONG resid)
{
   APIRET rc;
   ULONG  ulSize = 0;
   char  *string = 0;

   rc = DosQueryResourceSize( hMod, RT_RCDATA, resid, &ulSize);

   if( rc == NO_ERROR)
   {
      char *readOnlyString = 0;
      rc = DosGetResource( hMod, RT_RCDATA, resid, (void**) &readOnlyString);

      /* allow for 0-termination if user hasn't got it right */
      if( readOnlyString[ ulSize - 1] != '\0')
         ulSize++;

      if( rc == NO_ERROR)
      {
         /* copy string & zero-terminate */
         string = (char*) PR_Malloc( ulSize);
         memcpy( string, readOnlyString, ulSize - 1);
         string[ ulSize - 1] = '\0';

         DosFreeResource( readOnlyString);
      }
   }

   return string;
}
Ejemplo n.º 15
0
char *nsMsgSearchAdapter::TransformSpacesToStars (const char *spaceString, msg_TransformType transformType)
{
  char *starString;

  if (transformType == kOverwrite)
  {
    if ((starString = strdup(spaceString)) != nsnull)
    {
      char *star = starString;
      while ((star = PL_strchr(star, ' ')) != nsnull)
        *star = '*';
    }
  }
  else
  {
    int i, count;

    for (i = 0, count = 0; spaceString[i]; )
    {
      if (spaceString[i++] == ' ')
      {
        count++;
        while (spaceString[i] && spaceString[i] == ' ') i++;
      }
    }

    if (transformType == kSurround)
      count *= 2;

    if (count > 0)
    {
      if ((starString = (char *)PR_Malloc(i + count + 1)) != nsnull)
      {
        int j;

        for (i = 0, j = 0; spaceString[i]; )
        {
          if (spaceString[i] == ' ')
          {
            starString[j++] = '*';
            starString[j++] = ' ';
            if (transformType == kSurround)
              starString[j++] = '*';

            i++;
            while (spaceString[i] && spaceString[i] == ' ')
              i++;
          }
          else
            starString[j++] = spaceString[i++];
        }
        starString[j] = 0;
      }
    }
    else
      starString = strdup(spaceString);
  }

  return starString;
}
Ejemplo n.º 16
0
nsresult nsAutoConfig::evaluateLocalFile(nsIFile *file)
{
    nsresult rv;
    nsCOMPtr<nsIInputStream> inStr;
    
    rv = NS_NewLocalFileInputStream(getter_AddRefs(inStr), file);
    if (NS_FAILED(rv)) 
        return rv;
        
    PRInt64 fileSize;
    PRUint32 fs, amt=0;
    file->GetFileSize(&fileSize);
    LL_L2UI(fs, fileSize); // Converting 64 bit structure to unsigned int
    char *buf = (char *)PR_Malloc(fs * sizeof(char));
    if (!buf) 
        return NS_ERROR_OUT_OF_MEMORY;
    
    rv = inStr->Read(buf, fs, &amt);
    if (NS_SUCCEEDED(rv)) {
      EvaluateAdminConfigScript(buf, fs, nsnull, PR_FALSE, 
                                PR_TRUE, PR_FALSE);
    }
    inStr->Close();
    PR_Free(buf);
    return rv;
}
Ejemplo n.º 17
0
/**
 * Called from PL_HashTableEnumerateEntries
 * A pointer to a PatternEntry is passed in.  A PatternEntry consists of 
 * a pointer a regex_t and a pointer to a new config store. 
 * Once enumeration is complete, the new config store will contain 
 * all the parameters (key and values) whose keys match the regex.
 */ 
static PRIntn PatternLoop(PLHashEntry *he, PRIntn index, void *arg)
{
    PatternEntry_t *entry = (PatternEntry_t *) arg;

    if (entry == NULL) {
        return HT_ENUMERATE_STOP;
    }

    regex_t *r = entry->regex;
    ConfigStore *store = entry->store;

    if ((r == NULL) || (store == NULL)) {
        return HT_ENUMERATE_STOP;
    }

    size_t no_sub = r->re_nsub+1; 
    regmatch_t *result = NULL;

    result = (regmatch_t *) PR_Malloc(sizeof(regmatch_t) * no_sub);
 
    if ((he != NULL) && (he->key != NULL) && (he->value != NULL)) {
        if (regexec(r, (char *) he->key, no_sub, result, 0)==0) {
            // Found a match 
            store->Add((const char*) he->key, (const char *) he->value);
        }
    }  else {
        return HT_ENUMERATE_STOP;
    }
    
    if (result != NULL) PR_Free(result);
    return HT_ENUMERATE_NEXT;
}
Ejemplo n.º 18
0
char *nsMsgSearchAdapter::UnEscapeSearchUrl (const char *commandSpecificData)
{
  char *result = (char*) PR_Malloc (strlen(commandSpecificData) + 1);
  if (result)
  {
    char *resultPtr = result;
    while (1)
    {
      char ch = *commandSpecificData++;
      if (!ch)
        break;
      if (ch == '\\')
      {
        char scratchBuf[3];
        scratchBuf[0] = (char) *commandSpecificData++;
        scratchBuf[1] = (char) *commandSpecificData++;
        scratchBuf[2] = '\0';
        unsigned int accum = 0;
        sscanf (scratchBuf, "%X", &accum);
        *resultPtr++ = (char) accum;
      }
      else
        *resultPtr++ = ch;
    }
    *resultPtr = '\0';
  }
  return result;
}
Ejemplo n.º 19
0
nsresult aptCoreTrace::Init(const char* sLock)
{
    if (mCanLog) return NS_OK;
    
    mLC = new LogClient();
    if (!mLC)
      return NS_ERROR_OUT_OF_MEMORY;

    const char* logfifo = getenv("JAXERLOG_PIPENAME");
    mLC->Init(logfifo, -1, sLock);
    mLC->OpenPipeForWrite();
#ifdef _WIN32
    mPid = GetCurrentProcessId();
#else
    mPid = getpid();
#endif
    
    mLoggerLock = PR_NewMonitor();

    mBuf = (char *)PR_Malloc(0x8000);
    mBufSize = 0x8000;

    mCanLog = PR_TRUE;

    nsCOMPtr<nsIPrefBranch> prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID));

    if (prefBranch)
        UpdatePrefSettings(prefBranch, nsnull);

    return NS_OK;
}
Ejemplo n.º 20
0
Archivo: Util.cpp Proyecto: encukou/pki
TPS_PUBLIC Buffer *Util::URLDecode(const char *data)
{
	int i;
	Buffer buf;
        Buffer *ret = NULL;
	int len = strlen(data);
	BYTE *tmp = NULL;
	int sum = 0;

        if (len == 0)
            return NULL;
        tmp = (BYTE *)PR_Malloc(len);
	for (i = 0; i < len; i++) {
		if (data[i] == '+') {
			tmp[sum++] = ' ';
		} else if (data[i] == '%') {
			tmp[sum++] = (hex2bin(data[i+1]) << 4) + hex2bin(data[i+2]);
			i+=2;
		} else {
			tmp[sum++] = (BYTE)data[i];
		}
	}	

        ret = new Buffer(tmp, sum);
        if( tmp != NULL ) {
            PR_Free( tmp );
            tmp = NULL;
        }
	return ret;
}
Ejemplo n.º 21
0
static void AllocateSolidColorFrame(layers::PlanarYCbCrData& aData,
                                    int aWidth, int aHeight,
                                    int aY, int aCb, int aCr)
{
  MOZ_ASSERT(!(aWidth&1));
  MOZ_ASSERT(!(aHeight&1));
  // Allocate a single frame with a solid color
  int yLen = aWidth*aHeight;
  int cbLen = yLen>>2;
  int crLen = cbLen;
  uint8_t* frame = (uint8_t*) PR_Malloc(yLen+cbLen+crLen);
  memset(frame, aY, yLen);
  memset(frame+yLen, aCb, cbLen);
  memset(frame+yLen+cbLen, aCr, crLen);

  aData.mYChannel = frame;
  aData.mYSize = IntSize(aWidth, aHeight);
  aData.mYStride = aWidth;
  aData.mCbCrStride = aWidth>>1;
  aData.mCbChannel = frame + yLen;
  aData.mCrChannel = aData.mCbChannel + cbLen;
  aData.mCbCrSize = IntSize(aWidth>>1, aHeight>>1);
  aData.mPicX = 0;
  aData.mPicY = 0;
  aData.mPicSize = IntSize(aWidth, aHeight);
  aData.mStereoMode = StereoMode::MONO;
}
Ejemplo n.º 22
0
PRUint32 *nsUInt32Array::CloneData() 
{ 
  PRUint32 *copyOfData = (PRUint32 *)PR_Malloc(m_nSize * sizeof(PRUint32)); 
  if (copyOfData) 
    memcpy(copyOfData, m_pData, m_nSize * sizeof(PRUint32)); 
  
  return copyOfData; 
} 
Ejemplo n.º 23
0
/****************************************************************
 *
 * J z i p O p e n
 *
 * Opens a new ZIP file and creates a new ZIPfile structure to
 * control the process of installing files into a zip.
 */
ZIPfile *
JzipOpen(char *filename, char *comment)
{
    ZIPfile *zipfile;
    PRExplodedTime prtime;

    zipfile = PORT_ZAlloc(sizeof(ZIPfile));
    if (!zipfile)
        out_of_memory();

    /* Construct time and date */
    PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &prtime);
    zipfile->date = ((prtime.tm_year - 1980) << 9) |
                    ((prtime.tm_month + 1) << 5) |
                    prtime.tm_mday;
    zipfile->time = (prtime.tm_hour << 11) |
                    (prtime.tm_min << 5) |
                    (prtime.tm_sec & 0x3f);

    zipfile->fp = NULL;
    if (filename &&
        (zipfile->fp = PR_Open(filename,
                               PR_WRONLY |
                                   PR_CREATE_FILE |
                                   PR_TRUNCATE,
                               0777)) == NULL) {
        char *nsprErr;
        if (PR_GetErrorTextLength()) {
            nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
            PR_GetErrorText(nsprErr);
        } else {
            nsprErr = NULL;
        }
        PR_fprintf(errorFD, "%s: can't open output jar, %s.%s\n",
                   PROGRAM_NAME,
                   filename, nsprErr ? nsprErr : "");
        if (nsprErr)
            PR_Free(nsprErr);
        errorCount++;
        exit(ERRX);
    }

    zipfile->list = NULL;
    if (filename) {
        zipfile->filename = PORT_ZAlloc(strlen(filename) + 1);
        if (!zipfile->filename)
            out_of_memory();
        PORT_Strcpy(zipfile->filename, filename);
    }
    if (comment) {
        zipfile->comment = PORT_ZAlloc(strlen(comment) + 1);
        if (!zipfile->comment)
            out_of_memory();
        PORT_Strcpy(zipfile->comment, comment);
    }

    return zipfile;
}
Ejemplo n.º 24
0
void *
PORT_Alloc(size_t bytes)
{
    void *rv;

    /* Always allocate a non-zero amount of bytes */
    rv = (void *)PR_Malloc(bytes ? bytes : 1);
    return rv;
}
Ejemplo n.º 25
0
NSAPI_PUBLIC char *fcgi_util_env_str(char *name, char *value) {
    char *t;

    t = (char *) PR_Malloc(strlen(name)+strlen(value)+2); /* 2: '=' and '\0' */

    sprintf(t, "%s=%s", name, value);

    return t;
}
Ejemplo n.º 26
0
NSAPI_PUBLIC char *fcgi_util_arg_str(char *name) {
    char *t;

    t = (char *) PR_Malloc(strlen(name)+1); /* 1 = '\0' */

    PL_strcpy(t, name);

    return t;
}
Ejemplo n.º 27
0
NS_IMETHODIMP nsCollationMacUC::AllocateRawSortKey(int32_t strength, const nsAString& stringIn,
                                                   uint8_t** key, uint32_t* outLen)
{
  NS_ENSURE_TRUE(mInit, NS_ERROR_NOT_INITIALIZED);
  NS_ENSURE_ARG_POINTER(key);
  NS_ENSURE_ARG_POINTER(outLen);

  nsresult res = EnsureCollator(strength);
  NS_ENSURE_SUCCESS(res, res);

  uint32_t stringInLen = stringIn.Length();
  uint32_t maxKeyLen = (1 + stringInLen) * kCollationValueSizeFactor * sizeof(UCCollationValue);
  if (maxKeyLen > mBufferLen) {
    uint32_t newBufferLen = mBufferLen;
    do {
      newBufferLen *= 2;
    } while (newBufferLen < maxKeyLen);
    void *newBuffer = PR_Malloc(newBufferLen);
    if (!newBuffer)
      return NS_ERROR_OUT_OF_MEMORY;

    PR_FREEIF(mBuffer);
    mBuffer = newBuffer;
    mBufferLen = newBufferLen;
  }

  ItemCount actual;
  OSStatus err = ::UCGetCollationKey(mCollator, (const UniChar*) PromiseFlatString(stringIn).get(),
                                     (UniCharCount) stringInLen,
                                     (ItemCount) (mBufferLen / sizeof(UCCollationValue)),
                                     &actual, (UCCollationValue *)mBuffer);
  NS_ENSURE_TRUE((err == noErr), NS_ERROR_FAILURE);

  uint32_t keyLength = actual * sizeof(UCCollationValue);
  void *newKey = PR_Malloc(keyLength);
  if (!newKey)
    return NS_ERROR_OUT_OF_MEMORY;

  memcpy(newKey, mBuffer, keyLength);
  *key = (uint8_t *)newKey;
  *outLen = keyLength;

  return NS_OK;
}
void
nsCompressedCharMap::SetChar(PRUint32 aChar)
{
  if (mExtended) {
    PRUint32 plane_num = CCMAP_PLANE(aChar);
    NS_ASSERTION(plane_num <= EXTENDED_UNICODE_PLANES,"invalid plane");
    if (plane_num <= EXTENDED_UNICODE_PLANES) {
      if (mExtMap[plane_num] == 0) {
        mExtMap[plane_num] = (PRUint32*)PR_Malloc(sizeof(PRUint32)*UCS2_MAP_LEN);
        NS_ASSERTION(mExtMap[plane_num], "failed to alloc new mExtMap");
        if (!mExtMap[plane_num]) {
          return;
        }
        memset(mExtMap[plane_num], 0, sizeof(PRUint32)*UCS2_MAP_LEN);
      }
      SET_REPRESENTABLE(mExtMap[plane_num], aChar & 0xffff);
    }
  } else {
    NS_ASSERTION(aChar <= 0xffff, "extended char is passed");

    unsigned int i;
    unsigned int upper_index      = CCMAP_UPPER_INDEX(aChar);
    unsigned int mid_index        = CCMAP_MID_INDEX(aChar);

    PRUint16 mid_offset = u.mCCMap[upper_index];
    if (mid_offset == CCMAP_EMPTY_MID) {
      mid_offset = u.mCCMap[upper_index] = mUsedLen;
      mUsedLen += CCMAP_NUM_MID_POINTERS;
      NS_ASSERTION(mUsedLen<=CCMAP_MAX_LEN,"length too long");
      // init the mid
      PRUint16 *mid = &u.mCCMap[mid_offset];
      for (i=0; i<CCMAP_NUM_MID_POINTERS; i++) {
        NS_ASSERTION(mid[i]==0, "this mid pointer should be unused");
        mid[i] = CCMAP_EMPTY_PAGE;
      }
    }

    PRUint16 page_offset = u.mCCMap[mid_offset+mid_index];
    if (page_offset == CCMAP_EMPTY_PAGE) {
      page_offset = u.mCCMap[mid_offset+mid_index] = mUsedLen;
      mUsedLen += CCMAP_NUM_PRUINT16S_PER_PAGE;
      NS_ASSERTION(mUsedLen<=CCMAP_MAX_LEN,"length too long");
      // init the page
      PRUint16 *page = &u.mCCMap[page_offset];
      for (i=0; i<CCMAP_NUM_PRUINT16S_PER_PAGE; i++) {
        NS_ASSERTION(page[i]==0, "this page should be unused");
        page[i] = 0;
      }
    }
#undef CCMAP_SET_CHAR
#define CCMAP_SET_CHAR(m,c) (CCMAP_TO_ALU(m,c) |= (CCMAP_POW2(CCMAP_BIT_INDEX(c))))
    CCMAP_SET_CHAR(u.mCCMap,aChar);
#undef CCMAP_SET_CHAR
    NS_ASSERTION(CCMAP_HAS_CHAR(u.mCCMap,aChar), "failed to set bit");
  }
}
Ejemplo n.º 29
0
StringNode *
StringNode_new()
{
    StringNode *new_this;
    new_this = (StringNode *)PR_Malloc(sizeof(StringNode));
    PORT_Assert(new_this != NULL);
    new_this->str = NULL;
    new_this->next = NULL;
    return new_this;
}
Ejemplo n.º 30
0
/* dir_ValidateAndAddNewServer
 *
 * This function verifies that the position, serverName and description values
 * are set for the given prefName.  If they are then it adds the server to the
 * unified server list.
 */
static PRBool dir_ValidateAndAddNewServer(nsVoidArray *wholeList, const char *fullprefname)
{
  PRBool rc = PR_FALSE;

  const char *endname = PL_strchr(&fullprefname[PL_strlen(PREF_LDAP_SERVER_TREE_NAME) + 1], '.');
  if (endname)
  {
    char *prefname = (char *)PR_Malloc(endname - fullprefname + 1);
    if (prefname)
    {
      PRInt32 dirType;
      char *t1 = nsnull, *t2 = nsnull;

      PL_strncpyz(prefname, fullprefname, endname - fullprefname + 1);

      dirType = DIR_GetIntPref(prefname, "dirType", -1);
      if (dirType != -1 &&
          DIR_GetIntPref(prefname, "position", 0) != 0 &&
          (t1 = DIR_GetStringPref(prefname, "description", nsnull)) != nsnull)
      {
        if (dirType == PABDirectory || dirType == IMDirectory ||
           (t2 = DIR_GetStringPref(prefname, "serverName",  nsnull)) != nsnull)
        {
          DIR_Server *server = (DIR_Server *)PR_Malloc(sizeof(DIR_Server));
          if (server)
          {
            DIR_InitServer(server, (DirectoryType)dirType);
            server->prefName = prefname;
            DIR_GetPrefsForOneServer(server);
            DIR_SetServerPosition(wholeList, server, server->position);
            rc = PR_TRUE;
          }
          PR_FREEIF(t2);
        }
        PR_Free(t1);
      }
      else
        PR_Free(prefname);
    }
  }

  return rc;
}