Exemplo n.º 1
0
CARingBuffer::~CARingBuffer()
{
    deallocate();
}
Exemplo n.º 2
0
void operator delete[](void* p) {
	deallocate(p);
}
size_t
AudioReadStream::getInterleavedFrames(size_t count, float *frames)
{
    if (m_retrievalRate == 0 ||
        m_retrievalRate == m_sampleRate ||
        m_channelCount == 0) {
        return getFrames(count, frames);
    }

    int samples = count * m_channelCount;

    if (!m_resampler) {
        m_resampler = new Resampler(Resampler::Best, m_channelCount);
        m_resampleBuffer = new RingBuffer<float>(samples * 2);
    }

    float ratio = float(m_retrievalRate) / float(m_sampleRate);
    int fileFrames = int(ceil(count / ratio));
    bool finished = false;

    float *in  = allocate<float>(fileFrames * m_channelCount);
    float *out = allocate<float>((count + 1) * m_channelCount);

    while (m_resampleBuffer->getReadSpace() < samples) {

        int fileFramesRemaining =
            int(ceil((samples - m_resampleBuffer->getReadSpace())
                     / (m_channelCount * ratio)));

        int got = 0;

        if (!finished) {
            got = getFrames(fileFramesRemaining, in);
            m_totalFileFrames += got;
            if (got < fileFramesRemaining) {
                finished = true;
            }
        } else {
            v_zero(in, fileFramesRemaining * m_channelCount);
            got = fileFramesRemaining;
        }

        if (got > 0) {
            int resampled = m_resampler->resampleInterleaved
                (out, count + 1, in, got, ratio, finished);

            if (m_resampleBuffer->getWriteSpace() < resampled * m_channelCount) {
                m_resampleBuffer = m_resampleBuffer->resized
                    (m_resampleBuffer->getReadSpace() + resampled * m_channelCount);
            }
        
            m_resampleBuffer->write(out, resampled * m_channelCount);
        }
    }

    deallocate(in);
    deallocate(out);

    int toReturn = samples;

    int available = (int(m_totalFileFrames * ratio) - m_totalRetrievedFrames) *
        m_channelCount;
    
    if (toReturn > available) toReturn = available;

    m_totalRetrievedFrames += toReturn;

    return m_resampleBuffer->read(frames, toReturn) / m_channelCount;
}
Exemplo n.º 4
0
int truncateFile( fileHandleType fh, securityIdType securityID ) {

unsigned int dirEntry;
unsigned int *catalogBlock;
unsigned int *entryPtr;
int retval;

	if (fh > MAX_OPEN_FILES) {

		return ERROR_BAD_HANDLE;
	}

	if (fileCursors[fh].inUse == 0) {

		return ERROR_BAD_HANDLE;
	}

	// if its a memory file, just return
	if (fileCursors[fh].fileType > 2 ) {

		return NO_ERROR;

	}

	if ( (securityID != fileCursors[fh].securityID) && securityID != ROOT_ID && (fileCursors[fh].othersPermissions&0x01) == 0) {

		return ERROR_NO_PERMISSION;

	}

	// read the catalog of blocks for this file
	dirEntry = fileCursors[fh].dirEntryNum;
	
	// read the catalog for this file
	retval = readBlock(rootDir->entry[dirEntry].firstCatalogBlock, (void **)&catalogBlock);

	if (retval != 0) {

		return ERROR_READ_ERROR;

	}

	entryPtr = catalogBlock;

	while(*entryPtr != 0) {

		eraseBlock(*entryPtr);

		setBlockAsFree(*entryPtr);

		++entryPtr;
	}

	deallocate((void *)catalogBlock, masterBlocks->mblock0.blockSize);

	eraseBlock(rootDir->entry[dirEntry].firstCatalogBlock);

	rootDir->entry[dirEntry].fileSize = 0;

	fileCursors[fh].writePos = 0;
	fileCursors[fh].readPos = 0;
	fileCursors[fh].readBlockNum = 0;
	fileCursors[fh].writeBlockNum = 0;
	fileCursors[fh].fileSize = 0;

	return NO_ERROR;
}
Exemplo n.º 5
0
/**
 * Tests the integer array.
 */
void test_integer_array() {

    log_write_terminated_message((void*) stdout, L"Test integer array:\n");

    // The test value (for the "decode" function below).
    wchar_t* test = L"2,3,4";
    int testc = *NUMBER_5_INTEGER_MEMORY_MODEL;

    // The test knowledge model.
    int* m = (int*) *NULL_POINTER_MEMORY_MODEL;
    int* mc = (int*) *NULL_POINTER_MEMORY_MODEL;
    int* ms = (int*) *NULL_POINTER_MEMORY_MODEL;

    // Allocate test knowledge model.
    allocate((void*) &mc, (void*) PRIMITIVE_MEMORY_MODEL_COUNT, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
    *mc = *NUMBER_0_INTEGER_MEMORY_MODEL;
    allocate((void*) &ms, (void*) PRIMITIVE_MEMORY_MODEL_COUNT, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
    *ms = *NUMBER_0_INTEGER_MEMORY_MODEL;
    allocate((void*) &m, (void*) ms, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);

    fwprintf(stdout, L"pre mc: %i\n", *mc);
    fwprintf(stdout, L"pre ms: %i\n", *ms);
    fwprintf(stdout, L"pre m: %i\n", *m);

    //
    // Use either the "decode" function or the three "set" functions below.
    // Both possibilities should have the same functionality and results.
    //

/*??
    // Decode (parse) test value and assign to test knowledge model.
    decode((void*) &m, (void*) mc, (void*) ms, *NULL_POINTER_MEMORY_MODEL, *NULL_POINTER_MEMORY_MODEL, *NULL_POINTER_MEMORY_MODEL, (void*) test, (void*) &testc,
        *NULL_POINTER_MEMORY_MODEL, *NULL_POINTER_MEMORY_MODEL, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
*/

/*?? TODO!
    // Set test values.
    overwrite_array((void*) &m, (void*) mc, (void*) ms, (void*) NUMBER_2_INTEGER_MEMORY_MODEL, (void*) PRIMITIVE_MEMORY_MODEL_COUNT, (void*) mc, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
    overwrite_array((void*) &m, (void*) mc, (void*) ms, (void*) NUMBER_3_INTEGER_MEMORY_MODEL, (void*) PRIMITIVE_MEMORY_MODEL_COUNT, (void*) mc, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
    overwrite_array((void*) &m, (void*) mc, (void*) ms, (void*) NUMBER_4_INTEGER_MEMORY_MODEL, (void*) PRIMITIVE_MEMORY_MODEL_COUNT, (void*) mc, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
*/

    // The result values read out from the integer vector.
    int* result0 = (int*) *NULL_POINTER_MEMORY_MODEL;
    int* result1 = (int*) *NULL_POINTER_MEMORY_MODEL;
    int* result2 = (int*) *NULL_POINTER_MEMORY_MODEL;

    // Get result values.
    get((void*) &result0, m, (void*) NUMBER_0_INTEGER_MEMORY_MODEL, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
    get((void*) &result1, m, (void*) NUMBER_1_INTEGER_MEMORY_MODEL, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
    get((void*) &result2, m, (void*) NUMBER_2_INTEGER_MEMORY_MODEL, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);

    fwprintf(stdout, L"post mc: %i\n", *mc);
    fwprintf(stdout, L"post ms: %i\n", *ms);
    fwprintf(stdout, L"post m: %i\n", *m);
    fwprintf(stdout, L"post result0: %i\n", *result0);
    fwprintf(stdout, L"post result1: %i\n", *result1);
    fwprintf(stdout, L"post result2: %i\n", *result2);

    // Deallocate test knowledge model.
    deallocate((void*) &m, (void*) ms, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
    deallocate((void*) &mc, (void*) PRIMITIVE_MEMORY_MODEL_COUNT, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
    deallocate((void*) &ms, (void*) PRIMITIVE_MEMORY_MODEL_COUNT, (void*) INTEGER_MEMORY_ABSTRACTION, (void*) INTEGER_MEMORY_ABSTRACTION_COUNT);
}
Exemplo n.º 6
0
unsigned int addNewBlock(fileHandleType fh) {

unsigned int newBlockNum;
void *catalogBlock;
unsigned int dirEntry;
int i;
int retval;
	
	if (fh > MAX_OPEN_FILES) {

		return ERROR_BAD_HANDLE;

	}

	if (fileCursors[fh].inUse == 0) {

		return ERROR_BAD_HANDLE;

	}

	dirEntry = fileCursors[fh].dirEntryNum;

	// read the catalog for this file
	retval = readBlock(rootDir->entry[dirEntry].firstCatalogBlock, &catalogBlock);

	if (retval != 0) {

		return ERROR_READ_ERROR;

	}

	for (i=0; i < masterBlocks->mblock0.blockEntriesPerCatalog; ++i) {

		if (*((unsigned int *)(catalogBlock)+i) == 0)
			break;
	}

	if (i == masterBlocks->mblock0.blockEntriesPerCatalog) {

		return -1;

	}

	if (findFreeBlock(&newBlockNum) != NO_ERROR) {

		return ERROR_NO_BLOCKS;

	}

	setBlockInUse(newBlockNum);

	// add this new block to the catalog for this file
	*((unsigned int *)catalogBlock+i) = newBlockNum;

	// and write the block back 
	writeBlock(catalogBlock, rootDir->entry[dirEntry].firstCatalogBlock);

	// release the memory allocated by readBlock
	deallocate(catalogBlock, masterBlocks->mblock0.blockSize);

	return newBlockNum;

}
Exemplo n.º 7
0
// read up to size bytes from the file.  Stops reading if the end of file is reached.
// returns the actual number of bytes read, or -1 on error
int readFile(fileHandleType fh, char *buffer, unsigned int size, int relPosition, unsigned int *numRead, securityIdType securityID) {

int i;
int retval;
unsigned int leftToRead;
unsigned int bytesRead;
unsigned int readPos;
unsigned int blockIndexToRead;
unsigned int blockNumForRead;
void *blockToRead;
unsigned int *catalogBlock;
unsigned int dirEntry;
unsigned int readOffset;
unsigned int amountToRead;
unsigned int blockSize;
unsigned int remainingInFile;
unsigned int remainingInBlock;
int offset;
int retcode;

	*numRead = 0;

	if (fh > MAX_OPEN_FILES) {

		return ERROR_BAD_HANDLE;

	}

	if (fileCursors[fh].inUse == 0) {

		return ERROR_BAD_HANDLE;

	}

	if (buffer == 0) {

		return ERROR_BAD_VALUE;

	}

	if (size == 0) {

		return ERROR_BAD_VALUE;

	}

	if ( (securityID != fileCursors[fh].securityID) && securityID != ROOT_ID && (fileCursors[fh].othersPermissions&0x02) == 0) {

		return ERROR_NO_PERMISSION;
	}

	// treat a memory file specially 
	if (fileCursors[fh].fileType > 2 ) {

		retcode=readMemoryFile( fh, buffer, size, numRead );

		return retcode;

	}

	leftToRead = size;
	bytesRead = 0;

	if (relPosition != 0) {

		offset = relPosition;
	
		if (fileReadPosRelative(fh, offset) != 0 ) {

			return ERROR_BAD_VALUE;
	
		}		

	}

	// read the catalog of blocks for this file
	dirEntry = fileCursors[fh].dirEntryNum;
	
	readPos = fileCursors[fh].readPos;

	// get a local of the blocksize just to keep code more readable
	blockSize = masterBlocks->mblock0.blockSize;

	while(leftToRead) {

		// use the directory entry, not the fileCursor so that we get updated fileSize of writes occur.
		if (readPos == rootDir->entry[dirEntry].fileSize) {

			break;

		}

		// find what the relative (not the absolute) block number is
		// the later will be looked up in the block catalog for this file
		blockIndexToRead = readPos / blockSize;

		// read the catalog for this file
		// re-read it every time because it could also get written to, extending the EOF
		if (readBlock(rootDir->entry[dirEntry].firstCatalogBlock, (void **)&catalogBlock)!= 0) {

			return ERROR_READ_ERROR;

		}

		blockNumForRead = *(unsigned int *)(catalogBlock + blockIndexToRead);

		deallocate(catalogBlock, blockSize);

		if (readBlock(blockNumForRead, &blockToRead)!= 0) {

			return ERROR_READ_ERROR;

		}

		// now there are three cases on how much memory to copy--the smallest of:
		// 1) the remaining data in this block from the calculated offset
		// 2) the remaining data in this read request
		// 3) until the end of file is reached

		readOffset = readPos % blockSize;

		remainingInBlock = blockSize - readOffset;
		remainingInFile = rootDir->entry[dirEntry].fileSize - readPos;

		amountToRead = minimum( minimum(remainingInFile, remainingInBlock), leftToRead);

		memcpy(buffer+bytesRead, blockToRead+readOffset, amountToRead);

		// we are done with this block so release the memory
		deallocate((void *)blockToRead, blockSize);

		bytesRead += amountToRead;
		leftToRead -= amountToRead;
		readPos += amountToRead;


	} // while

	fileCursors[fh].readPos = readPos;
	*numRead = bytesRead;

	if (readPos == rootDir->entry[dirEntry].fileSize) {

		return ERROR_EOF;

	}
	else {

		return NO_ERROR;
	}
}
Exemplo n.º 8
0
/**
 * Extract the next element name without affecting the string
 *	This buffer must be freed by the caller
 * @param str Pointer to a string structure
 * @return Returns a new pointer to the name of the element or NULL on failure
 **/
char *pullNextElementName( pstring str )
{
        char * elementId = NULL;
        int reset = 0;
        int index = 0;
        unsigned int length = 0;

        if ( str == NULL ) {
                return NULL;
        }

        /// This will be used to reset the buffer at the end
        reset = str->index;

        /// This shouldn't be necessary but just in case
        skipWhiteSpace( str );

        /// The first character should be an open curly brace
        if (str->buffer[ str->index ] != '{' ) {
                printf("!!Invalid opening element: @s\n", str->buffer );
                goto end;
        }

        /// Increment beyond the initial '{'
	if ( incChar( str ) == -1 ) {
		goto end;
	}

        /// Skip past any whitespace
        skipWhiteSpace(str);

        /// Store the index to the start of the element name
        index = str->index;

        /// Loop until the end of the buffer, a null, or a non-alpha, white space, or  '}' character is encountered
        while ( index < str->maxlength ) {

                /// If we hit a NULL then it is improperly formatted.
                /// Just skip to the end
                if ( str->buffer[index] == '\x00' ) {
                        printf("!!Null character hit. Improperly formatted element\n");
                        goto end;
                }

                /// If it is a closing brace or a white space then the name is passed
                if ( str->buffer[ index ]  == '}' || isspace( str->buffer[index] ) ) {
                        length = index-str->index;

                        /// Copy the name for the return
                        if ( allocate( length + 1, 0, (void*)&elementId ) != 0 ) {
                                elementId = NULL;
                                goto end;
                        }

                        bzero( elementId, length + 1 );

                        strncpy( elementId, str->buffer + str->index, length );

                        /// Check for a properly formatted name. Start by updating
			///	the string index to the end of the string
			///	Then skip any proceeding whitespace
                        str->index = index;
                        skipWhiteSpace(str);

                        /// If the current character is not '}' then it invalid is
			///	invalid since only whitespace is allowed between the
			///	element id and the closing brace
                        if (str->buffer[ str->index ] != '}' ) {
                                printf("!!Improperly formatted element name\n");
                                deallocate( elementId, length + 1 );
                                elementId = NULL;
                        }

                        /// Work here is done. Skip to the end
                        goto end;
                }

                /// Non alpha characters are not allowed as element names
                if ( !isalpha( str->buffer[index] ) ) {
                        goto end;
                }

                index++;
        }

end:
	/// Revert the string to the beginning
        str->index = reset;

        return elementId;
}
Exemplo n.º 9
0
ArrayGraph::~ArrayGraph(void)
{
	if (m_nodeXPos)
		deallocate();
}
Exemplo n.º 10
0
extern int main(int argc, char *argv[])
{
  unsigned i;
  Addr base, limit;
  mps_arena_t mpsArena;
  Arena arena; /* the ANSI arena which we use to allocate the BT */
  CBSStruct cbsStruct;
  CBS cbs;
  void *p;
  Addr dummyBlock;
  BT allocTable;
  Size size;
  Bool high;
  CBSFindDelete findDelete = CBSFindDeleteNONE;

  randomize(argc, argv);

  NAllocateTried = NAllocateSucceeded = NDeallocateTried =
    NDeallocateSucceeded = NNewBlocks = NDeleteBlocks =
    NGrowBlocks = NShrinkBlocks = 0;

  clearExpectations();

  die(mps_arena_create(&mpsArena, mps_arena_class_vm(), testArenaSIZE),
      "mps_arena_create");
  arena = (Arena)mpsArena; /* avoid pun */

  die((mps_res_t)BTCreate(&allocTable, arena, ArraySize),
      "failed to create alloc table");

  die((mps_res_t)CBSInit(arena, &cbsStruct, NULL, &cbsNewCallback,
                         &cbsDeleteCallback, &cbsGrowCallback,
                         &cbsShrinkCallback, MinSize,
                         Alignment, TRUE, TRUE),
      "failed to initialise CBS");
  cbs = &cbsStruct;

  BTSetRange(allocTable, 0, ArraySize); /* Initially all allocated */

  /* We're not going to use this block, but I feel unhappy just */
  /* inventing addresses. */
  die((mps_res_t)ControlAlloc(&p, arena, ArraySize * Alignment,
                              /* withReservoirPermit */ FALSE),
      "failed to allocate block");
  dummyBlock = (Addr)p; /* avoid pun */

  printf("Allocated block [%p, %p)\n", (void*)dummyBlock,
         (char *)dummyBlock + ArraySize);

  checkCBS(cbs, allocTable, dummyBlock);
  for(i = 0; i < NOperations; i++) {
    switch(cbsRnd(3)) {
    case 0: {
      randomRange(&base, &limit, allocTable, dummyBlock);
      allocate(cbs, dummyBlock, allocTable, base, limit);
    } break;
    case 1: {
      randomRange(&base, &limit, allocTable, dummyBlock);
      deallocate(cbs, dummyBlock, allocTable, base, limit);
    } break;
    case 2: {
      size = cbsRnd(ArraySize / 10) + 1;
      high = cbsRnd(2) ? TRUE : FALSE;
      switch(cbsRnd(6)) {
      case 0:
      case 1:
      case 2: findDelete = CBSFindDeleteNONE; break;
      case 3: findDelete = CBSFindDeleteLOW; break;
      case 4: findDelete = CBSFindDeleteHIGH; break;
      case 5: findDelete = CBSFindDeleteENTIRE; break;
      }
      find(cbs, dummyBlock, allocTable, size, high, findDelete);
    } break;
    }
    if (i % 5000 == 0)
      checkCBS(cbs, allocTable, dummyBlock);
  }

  checkExpectations();

  /* CBSDescribe prints a very long line. */
  /* CBSDescribe(cbs, mps_lib_get_stdout()); */

  printf("\nNumber of allocations attempted: %ld\n", NAllocateTried);
  printf("Number of allocations succeeded: %ld\n", NAllocateSucceeded);
  printf("Number of deallocations attempted: %ld\n", NDeallocateTried);
  printf("Number of deallocations succeeded: %ld\n", NDeallocateSucceeded);
  printf("Number of new large blocks: %ld\n", NNewBlocks);
  printf("Number of deleted large blocks: %ld\n", NDeleteBlocks);
  printf("Number of grown large blocks: %ld\n", NGrowBlocks);
  printf("Number of shrunk large blocks: %ld\n", NShrinkBlocks);
  printf("\nNo problems detected.\n");
  return 0;
}
Exemplo n.º 11
0
char *strtok(char *str, const char *delim) {
	char *start;
	char *end;
	char *t;
	int i;

	// invalid input
	if (delim == NULL) {
		return(NULL);
	}
	
	// called on existing string
	if (str == NULL) {
		if (prev_str == NULL) {
			return(NULL);
		}
		// already parsed through end of original str
		if (prev_str_ptr >= prev_str+prev_str_len) {
			return(NULL);
		}
	} else {
		// called with new string, so free the old one
		if (prev_str) {
			deallocate(prev_str, prev_str_len);
			prev_str = NULL;
			prev_str_len = 0;
			prev_str_ptr = NULL;
		}
	}

	// not been called before, so make a copy of the string
	if (prev_str == NULL) {
		if (strlen(str) > 4096) {
			// too big
			return(NULL);
		} 
		prev_str_len = strlen(str);
		if (allocate(prev_str_len, 0, (void *)&prev_str)) {
			return(NULL);
		}
		strcpy(prev_str, str);
		prev_str_ptr = prev_str;
	}

	str = prev_str_ptr;

	// make sure the string isn't starting with a delimeter
	while (strchr(delim, str[0]) && str < prev_str+prev_str_len) {
		str++;
	}
	if (str >= prev_str+prev_str_len) {
		return(NULL);
	}

	// find the earliest next delimiter
	start = str;
	end = str+strlen(str);
	for (i = 0; i < strlen((char *)delim); i++) {
		if ((t = strchr(start, delim[i]))) {
			if (t != NULL && t < end) {
				end = t;
			}
		}
	}
	
	// populate the new token
	token = start;
	*end = '\0';

	prev_str_ptr = end+1;

	return(token);
}
Exemplo n.º 12
0
int main (int argc, char **argv)
{
    int i;
    int index, index1, index2;
    FILE *fpt1;
    FILE *fpt2;
    FILE *fpt3;
    FILE *fpt4;
    FILE *fpt5;
    individual *ea;
    individual *parent1, *parent2, *child1, *child2;
    ind_list *elite, *cur;
    if (argc<2)
    {
        printf("\n Usage ./main random_seed \n");
        exit(1);
    }
    seed = (double)atof(argv[1]);
    if (seed<=0.0 || seed>=1.0)
    {
        printf("\n Entered seed value is wrong, seed value must be in (0,1) \n");
        exit(1);
    }
    fpt1 = fopen("initial_pop.out","w");
    fpt2 = fopen("final_pop.out","w");
    fpt3 = fopen("final_archive.out","w");
    fpt4 = fopen("all_archive.out","w");
    fpt5 = fopen("params.out","w");
    fprintf(fpt1,"# This file contains the data of initial population\n");
    fprintf(fpt2,"# This file contains the data of final population\n");
    fprintf(fpt3,"# This file contains the best obtained solution(s)\n");
    fprintf(fpt4,"# This file contains the data of archive for all generations\n");
    fprintf(fpt5,"# This file contains information about inputs as read by the program\n");
    printf("\n Enter the problem relevant and algorithm relevant parameters ... ");
    printf("\n Enter the population size (>1) : ");
    scanf("%d",&popsize);
    if (popsize<2)
    {
        printf("\n population size read is : %d",popsize);
        printf("\n Wrong population size entered, hence exiting \n");
        exit (1);
    }
    printf("\n Enter the number of function evaluations : ");
    scanf("%d",&neval);
    if (neval<popsize)
    {
        printf("\n number of function evaluations read is : %d",neval);
        printf("\n Wrong nuber of evaluations entered, hence exiting \n");
        exit (1);
    }
    printf("\n Enter the number of objectives (>=2): ");
    scanf("%d",&nobj);
    if (nobj<2)
    {
        printf("\n number of objectives entered is : %d",nobj);
        printf("\n Wrong number of objectives entered, hence exiting \n");
        exit (1);
    }
    epsilon = (double *)malloc(nobj*sizeof(double));
    min_obj = (double *)malloc(nobj*sizeof(double));
    for (i=0; i<nobj; i++)
    {
        printf("\n Enter the value of epsilon[%d] : ",i+1);
        scanf("%lf",&epsilon[i]);
        if (epsilon[i]<=0.0)
        {
            printf("\n Entered value of epsilon[%d] is non-positive, hence exiting\n",i+1);
            exit(1);
        }
        printf("\n Enter the value of min_obj[%d] (if not known, enter 0.0) : ",i+1);
        scanf("%lf",&min_obj[i]);
    }
    printf("\n Enter the number of constraints : ");
    scanf("%d",&ncon);
    if (ncon<0)
    {
        printf("\n number of constraints entered is : %d",ncon);
        printf("\n Wrong number of constraints enetered, hence exiting \n");
        exit (1);
    }
    printf("\n Enter the number of real variables : ");
    scanf("%d",&nreal);
    if (nreal<0)
    {
        printf("\n number of real variables entered is : %d",nreal);
        printf("\n Wrong number of variables entered, hence exiting \n");
        exit (1);
    }
    if (nreal != 0)
    {
        min_realvar = (double *)malloc(nreal*sizeof(double));
        max_realvar = (double *)malloc(nreal*sizeof(double));
        for (i=0; i<nreal; i++)
        {
            printf ("\n Enter the lower limit of real variable %d : ",i+1);
            scanf ("%lf",&min_realvar[i]);
            printf ("\n Enter the upper limit of real variable %d : ",i+1);
            scanf ("%lf",&max_realvar[i]);
            if (max_realvar[i] <= min_realvar[i])
            {
                printf("\n Wrong limits entered for the min and max bounds of real variable %d, hence exiting \n",i+1);
                exit(1);
            }
        }
        printf ("\n Enter the probability of crossover of real variable (0.6-1.0) : ");
        scanf ("%lf",&pcross_real);
        if (pcross_real<0.0 || pcross_real>1.0)
        {
            printf("\n Probability of crossover entered is : %e",pcross_real);
            printf("\n Entered value of probability of crossover of real variables is out of bounds, hence exiting \n");
            exit (1);
        }
        printf ("\n Enter the probablity of mutation of real variables (1/nreal) : ");
        scanf ("%lf",&pmut_real);
        if (pmut_real<0.0 || pmut_real>1.0)
        {
            printf("\n Probability of mutation entered is : %e",pmut_real);
            printf("\n Entered value of probability of mutation of real variables is out of bounds, hence exiting \n");
            exit (1);
        }
        printf ("\n Enter the value of distribution index for crossover (5-20): ");
        scanf ("%lf",&eta_c);
        if (eta_c<=0)
        {
            printf("\n The value entered is : %e",eta_c);
            printf("\n Wrong value of distribution index for crossover entered, hence exiting \n");
            exit (1);
        }
        printf ("\n Enter the value of distribution index for mutation (5-50): ");
        scanf ("%lf",&eta_m);
        if (eta_m<=0)
        {
            printf("\n The value entered is : %e",eta_m);
            printf("\n Wrong value of distribution index for mutation entered, hence exiting \n");
            exit (1);
        }
    }
    printf("\n Enter the number of binary variables : ");
    scanf("%d",&nbin);
    if (nbin<0)
    {
        printf ("\n number of binary variables entered is : %d",nbin);
        printf ("\n Wrong number of binary variables entered, hence exiting \n");
        exit(1);
    }
    if (nbin != 0)
    {
        nbits = (int *)malloc(nbin*sizeof(int));
        min_binvar = (double *)malloc(nbin*sizeof(double));
        max_binvar = (double *)malloc(nbin*sizeof(double));
        for (i=0; i<nbin; i++)
        {
            printf ("\n Enter the number of bits for binary variable %d : ",i+1);
            scanf ("%d",&nbits[i]);
            if (nbits[i] < 1)
            {
                printf("\n Wrong number of bits for binary variable entered, hence exiting");
                exit(1);
            }
            printf ("\n Enter the lower limit of binary variable %d : ",i+1);
            scanf ("%lf",&min_binvar[i]);
            printf ("\n Enter the upper limit of binary variable %d : ",i+1);
            scanf ("%lf",&max_binvar[i]);
            if (max_binvar[i] <= min_binvar[i])
            {
                printf("\n Wrong limits entered for the min and max bounds of binary variable entered, hence exiting \n");
                exit(1);
            }
        }
        printf ("\n Enter the probability of crossover of binary variable (0.6-1.0): ");
        scanf ("%lf",&pcross_bin);
        if (pcross_bin<0.0 || pcross_bin>1.0)
        {
            printf("\n Probability of crossover entered is : %e",pcross_bin);
            printf("\n Entered value of probability of crossover of binary variables is out of bounds, hence exiting \n");
            exit (1);
        }
        printf ("\n Enter the probability of mutation of binary variables (1/nbits): ");
        scanf ("%lf",&pmut_bin);
        if (pmut_bin<0.0 || pmut_bin>1.0)
        {
            printf("\n Probability of mutation entered is : %e",pmut_bin);
            printf("\n Entered value of probability  of mutation of binary variables is out of bounds, hence exiting \n");
            exit (1);
        }
    }
    if (nreal==0 && nbin==0)
    {
        printf("\n Number of real as well as binary variables, both are zero, hence exiting \n");
        exit(1);
    }
    printf("\n Input data successfully entered, now performing initialization \n");
    fprintf(fpt5,"\n Population size = %d",popsize);
    fprintf(fpt5,"\n Number of function evaluations = %d",neval);
    fprintf(fpt5,"\n Number of objective functions = %d",nobj);
    for (i=0; i<nobj; i++)
    {
        fprintf(fpt5,"\n Epsilon for objective %d = %e",i+1,epsilon[i]);
        fprintf(fpt5,"\n Minimum value of objective %d = %e",i+1,min_obj[i]);
    }
    fprintf(fpt5,"\n Number of constraints = %d",ncon);
    fprintf(fpt5,"\n Number of real variables = %d",nreal);
    if (nreal!=0)
    {
        for (i=0; i<nreal; i++)
        {
            fprintf(fpt5,"\n Lower limit of real variable %d = %e",i+1,min_realvar[i]);
            fprintf(fpt5,"\n Upper limit of real variable %d = %e",i+1,max_realvar[i]);
        }
        fprintf(fpt5,"\n Probability of crossover of real variable = %e",pcross_real);
        fprintf(fpt5,"\n Probability of mutation of real variable = %e",pmut_real);
        fprintf(fpt5,"\n Distribution index for crossover = %e",eta_c);
        fprintf(fpt5,"\n Distribution index for mutation = %e",eta_m);
    }
    fprintf(fpt5,"\n Number of binary variables = %d",nbin);
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            fprintf(fpt5,"\n Number of bits for binary variable %d = %d",i+1,nbits[i]);
            fprintf(fpt5,"\n Lower limit of binary variable %d = %e",i+1,min_binvar[i]);
            fprintf(fpt5,"\n Upper limit of binary variable %d = %e",i+1,max_binvar[i]);
        }
        fprintf(fpt5,"\n Probability of crossover of binary variable = %e",pcross_bin);
        fprintf(fpt5,"\n Probability of mutation of binary variable = %e",pmut_bin);
    }
    fprintf(fpt5,"\n Seed for random number generator = %e",seed);
    bitlength = 0;
    if (nbin!=0)
    {
        for (i=0; i<nbin; i++)
        {
            bitlength += nbits[i];
        }
    }
    fprintf(fpt1,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt2,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt3,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation\n",nobj,ncon,nreal,bitlength);
    fprintf(fpt4,"# of objectives = %d, # of constraints = %d, # of real_var = %d, # of bits of bin_var = %d, constr_violation\n",nobj,ncon,nreal,bitlength);
    nbinmut = 0;
    nrealmut = 0;
    nbincross = 0;
    nrealcross = 0;
    currenteval = 0;
    elite_size = 0;
    randomize();
    ea = (individual *)malloc(popsize*sizeof(individual));
    array = (int *)malloc(popsize*sizeof(int));
    for (i=0; i<popsize; i++)
    {
        allocate (&ea[i]);
        initialize(&ea[i]);
        decode(&ea[i]);
        eval(&ea[i]);
    }
    report_pop (ea, fpt1);
    elite = (ind_list *)malloc(sizeof(ind_list));
    elite->ind = (individual *)malloc(sizeof(individual));
    allocate (elite->ind);
    elite->parent = NULL;
    elite->child = NULL;
    insert (elite, &ea[0]);
    for (i=1; i<popsize; i++)
    {
        update_elite (elite, &ea[i]);
    }
    child1 = (individual *)malloc(sizeof(individual));
    allocate (child1);
    child2 = (individual *)malloc(sizeof(individual));
    allocate (child2);
    cur = elite;
    while (currenteval<neval)
    {
        index1 = rnd(0, popsize-1);
        index2 = rnd(0, popsize-1);
        parent1 = tournament (&ea[index1], &ea[index2]);
        index = rnd(0, elite_size-1);
        cur = elite->child;
        for (i=1; i<=index; i++)
        {
            cur=cur->child;
        }
        parent2 = cur->ind;
        crossover (parent1, parent2, child1, child2);
        mutation (child1);
        decode (child1);
        eval (child1);
        update_elite (elite, child1);
        update_pop (ea, child1);
        mutation (child2);
        decode (child2);
        eval (child2);
        update_elite (elite, child2);
        update_pop (ea, child2);
        printf("\n Currenteval = %d and Elite_size = %d",currenteval,elite_size); 
		/* Comment following three lines if information at all
		evaluation is not desired, it will speed up execution of the code */
	fprintf(fpt4,"# eval id = %d\n",currenteval);
		report_archive (elite, fpt4);
		fflush(fpt4);
    }
    printf("\n Generations finished, now reporting solutions");
    report_pop (ea, fpt2);
    report_archive (elite, fpt3);
    if (nreal!=0)
    {
        fprintf(fpt5,"\n Number of crossover of real variable = %d",nrealcross);
        fprintf(fpt5,"\n Number of mutation of real variable = %d",nrealmut);
    }
    if (nbin!=0)
    {
        fprintf(fpt5,"\n Number of crossover of binary variable = %d",nbincross);
        fprintf(fpt5,"\n Number of mutation of binary variable = %d",nbinmut);
    }
    fflush(stdout);
    fflush(fpt1);
    fflush(fpt2);
    fflush(fpt3);
    fflush(fpt4);
    fflush(fpt5);
    fclose(fpt1);
    fclose(fpt2);
    fclose(fpt3);
    fclose(fpt4);
    fclose(fpt5);
    if (nreal!=0)
    {
        free (min_realvar);
        free (max_realvar);
    }
    if (nbin!=0)
    {
        free (min_binvar);
        free (max_binvar);
        free (nbits);
    }
    free (epsilon);
    free (min_obj);
    free (array);
    for (i=0; i<popsize; i++)
    {
        deallocate (&ea[i]);
    }
    free (ea);
    cur = elite->child;
    while (cur!=NULL)
    {
        cur = del(cur);
        cur = cur->child;
    }
    deallocate (elite->ind);
    free (elite->ind);
    free (elite);
    printf("\n Routine successfully exited \n");
    return (0);
}
Exemplo n.º 13
0
// shows a prompt to the user, gets an input line,
// calls parseCommand, then determines and calls
// the appropriate function for the command
void promptUser() {

    for (;;) {
        char *line = NULL;
        char **argv = NULL;
        size_t line_size = 0;
        size_t n = 0;

        printf("prompt>");

        getline(&line, &line_size, stdin);
        int argc = parseCommand(line, &n, &argv);
        free(line);
        // printf("%d tokens parsed\n", argc);
        if (argc > 0) {
            // int i;
            // for (i = 0 ; i < argc ; i++) {
            //     printf("argv %d: %s\n", i, argv[i]);
            // }
            if (!strcmp(argv[0], "allocate")) {
                // first check that there's an appropriate number of arguments
                if (argc == 2) {
                    // int allocate(int number_of_bytes)
                    int number_of_bytes = atoi(argv[1]);
                    if (number_of_bytes > 0)
                        allocate(number_of_bytes);
                    else
                        printf("Cannot allocate < 1 byte.\n");
                }
                else {
                    printf("Usage: allocate [number_of_bytes]\n");
                }
            }
            else if (!strcmp(argv[0], "free")) {
                if (argc == 2) {
                    // void deallocate(int block_number)
                    int block_number = atoi(argv[1]);
                    if (block_number > 0)
                        deallocate(block_number);
                    else
                        printf("Block number can not be less than 1.\n");
                }
                else {
                    printf("Usage: free [block_number]\n");
                }
            }
            else if (!strcmp(argv[0], "blocklist")) {
                // void blocklist()
                blocklist();
            }
            else if (!strcmp(argv[0], "writeheap")) {
                if (argc == 4) {
                    // void writeheap(int the_block_number, char CTW, int copies)
                    int the_block_number = atoi(argv[1]);
                    char CTW = argv[2][0];
                    int copies = atoi(argv[3]);
                    if ( (the_block_number > 0) && (copies > 0) )
                        writeheap(the_block_number, CTW, copies);
                    else if (the_block_number < 1)
                        printf("Block number can not be less than 1.\n");
                    else
                        printf("Must write at least 1 byte.\n");
                }
                else {
                    printf("Usage: writeheap [block_number] [char] [amount]\n");
                }
            }
            else if (!strcmp(argv[0], "printheap")) {
                if (argc == 3) {
                    // void printheap(int block_number, int number_of_bytes)
                    int block_number = atoi(argv[1]);
                    int number_of_bytes = atoi(argv[2]);
                    if ( (block_number > 0) && (number_of_bytes) > 0)
                        printheap(block_number, number_of_bytes);
                    else if (block_number < 1)
                        printf("Block number can not be less than 1.\n");
                    else
                        printf("Must read at least 1 byte.\n");
                }
                else {
                    printf("Usage: printheap [block_number] [amount]\n");
                }
            }
            else if (!strcmp(argv[0], "quit")) {
                // void quit()
                quit();
                break;
            }
            else {
                printf("Invalid Command\n");
            }
        }
        if (argc != -1) {
            int i;
            for (i = 0 ; i < argc ; i++) {
                free(argv[i]);
            }
        }
        free(argv);
    }
}
Exemplo n.º 14
0
/**
Default destructor. Invoked by the compiler. Only frees allocated memory
if all shallow copies in scope have been removed.
Produces an error if the double* member v is NULL.
*/
ivector::~ivector()
{
  deallocate();
}
Exemplo n.º 15
0
/* Frame to text */
static void
frameToString(jvmtiEnv *jvmti, char *buf, int buflen, jvmtiFrameInfo *finfo)
{
    jvmtiError           error;
    jclass               klass;
    char                *signature;
    char                *methodname;
    char                *methodsig;
    jboolean             isNative;
    char                *filename;
    int                  lineCount;
    jvmtiLineNumberEntry*lineTable;
    int                  lineNumber;

    /* Initialize defaults */
    buf[0]     = 0;
    klass      = NULL;
    signature  = NULL;
    methodname = NULL;
    methodsig  = NULL;
    isNative   = JNI_FALSE;
    filename   = NULL;
    lineCount  = 0;
    lineTable  = NULL;
    lineNumber = 0;

    /* Get jclass object for the jmethodID */
    error = (*jvmti)->GetMethodDeclaringClass(jvmti, finfo->method, &klass);
    check_jvmti_error(jvmti, error, "Cannot get method's class");

    /* Get the class signature */
    error = (*jvmti)->GetClassSignature(jvmti, klass, &signature, NULL);
    check_jvmti_error(jvmti, error, "Cannot get class signature");

    /* Skip all this if it's our own Tracker method */
    if ( strcmp(signature, "L" STRING(HEAP_TRACKER_class) ";" ) == 0 ) {
        deallocate(jvmti, signature);
        return;
    }

    /* Get the name and signature for the method */
    error = (*jvmti)->GetMethodName(jvmti, finfo->method,
                &methodname, &methodsig, NULL);
    check_jvmti_error(jvmti, error, "Cannot method name");

    /* Check to see if it's a native method, which means no lineNumber */
    error = (*jvmti)->IsMethodNative(jvmti, finfo->method, &isNative);
    check_jvmti_error(jvmti, error, "Cannot get method native status");

    /* Get source file name */
    error = (*jvmti)->GetSourceFileName(jvmti, klass, &filename);
    if ( error != JVMTI_ERROR_NONE && error != JVMTI_ERROR_ABSENT_INFORMATION ) {
        check_jvmti_error(jvmti, error, "Cannot get source filename");
    }

    /* Get lineNumber if we can */
    if ( !isNative ) {
        int i;

        /* Get method line table */
        error = (*jvmti)->GetLineNumberTable(jvmti, finfo->method, &lineCount, &lineTable);
        if ( error == JVMTI_ERROR_NONE ) {
            /* Search for line */
            lineNumber = lineTable[0].line_number;
            for ( i = 1 ; i < lineCount ; i++ ) {
                if ( finfo->location < lineTable[i].start_location ) {
                    break;
                }
                lineNumber = lineTable[i].line_number;
            }
        } else if ( error != JVMTI_ERROR_ABSENT_INFORMATION ) {
            check_jvmti_error(jvmti, error, "Cannot get method line table");
        }
    }

    /* Create string for this frame location.
     *    NOTE: These char* quantities are mUTF (Modified UTF-8) bytes
     *          and should actually be converted to the default system
     *          character encoding. Sending them to things like
     *          printf() without converting them is actually an I18n
     *          (Internationalization) error.
     */
    (void)sprintf(buf, "%s.%[email protected]%d[%s:%d]",
            (signature==NULL?"UnknownClass":signature),
            (methodname==NULL?"UnknownMethod":methodname),
            (int)finfo->location,
            (filename==NULL?"UnknownFile":filename),
            lineNumber);

    /* Free up JVMTI space allocated by the above calls */
    deallocate(jvmti, signature);
    deallocate(jvmti, methodname);
    deallocate(jvmti, methodsig);
    deallocate(jvmti, filename);
    deallocate(jvmti, lineTable);
}
Exemplo n.º 16
0
 void release() {
     if (refcount && CV_XADD(refcount, -1) == 1)
         deallocate();
 }
Exemplo n.º 17
0
/** Free a memory stream.
 *
 * @param io mem stream
 */
static void mem_free(IOStream *io){
    MemData *data = get_mem_data(io);
    deallocate(data->buf);
    memzero(data, sizeof(*data));
    deallocate(data);
}
Exemplo n.º 18
0
int main()
{
 
	int i, j;
	printf("\n \n Enter the no. of processes and the shared resource:");
	scanf(" %d", &ps);
	scanf(" %d", &src); 
/* Maximum resource available */
	printf("\Enter the maximum resource available matrix:");
	for(i = 1; i <= src; i++)
		scanf(" %d", &resources[i]);
		
 /* Maximum needed */
    printf("\nEnter the maximum needed:");
	for(i = 1; i <= ps; i++)
	{
		for(j = 1; j <= src; j++)
		{
			printf("\n Resource %d for Process %d :", j, i);
			scanf(" %d", &MAX_RESOURCE[i][j]);
		}
	}
/* Currently Allocated Matrix */ 
	printf("\n Enter the current allocated matrix:");
	for(i = 1; i <= ps; i++)
	{
		for(j = 1; j <= src; j++)
		{
			printf("\n Resources %d for Process %d :", j, i);
			scanf(" %d", &current[i][j]);
 
		}
	}
 /* Need Matrix can be calculated as Max - Allocated */
	for(i = 1; i <= src; i++)
	{
		for(j = 1; j <= ps; j++)
		{
			total[i] = total[i]+ current[j][i];
			need[j][i] = MAX_RESOURCE[j][i] - current[j][i];
		}
		available[i] = resources[i] - total[i];
	}
	
/* Remaining resources for allocation */ 

	printf("\n Remaining Resource: \n");		
	for(i = 1; i <= src; i++)
	{
		printf(" %d \t ", available[i]);
	}
	
	while(check(ps)!=0)
	{
		for(i = 1; i <= ps; i++)
		{
			if(finish[i] ==  0)
			{
				if(ac(i))
				{
					printf("\n \n Allocated: \n");					
					allocate(i);
					printf("\n \n Deallocated: \n");
					deallocate(i);
				}
			}
		}
	}
}
Exemplo n.º 19
0
int writeFile(fileHandleType fh, char *buffer, unsigned int size, securityIdType securityID) {

unsigned int leftToWrite;
unsigned int writePtr;
unsigned int blockOffset;
unsigned int writePos;
unsigned char *blockBuffer;
unsigned int blockSize;
void *blockForWrite;
unsigned int blockNumForWrite;
unsigned int remainingBlockSpace;
unsigned int dirEntry;
unsigned int *catalogBlock;
unsigned int blockIndexForWrite;
int retval;
int writeLength;
char tmpbuffer[32];
int retcode;

	if (fh > MAX_OPEN_FILES) {

		return ERROR_BAD_HANDLE;

	}

	if (fileCursors[fh].inUse == 0) {

		return ERROR_BAD_HANDLE;

	}

	if (buffer == 0) {

		return ERROR_BAD_VALUE;

	}

	if (size == 0) {

		return ERROR_BAD_VALUE;

	}

	if ( (securityID != fileCursors[fh].securityID) && securityID != ROOT_ID && (fileCursors[fh].othersPermissions&0x01) == 0) {

		return ERROR_NO_PERMISSION;
	}


	// treat a memory file specially 
	if (fileCursors[fh].fileType > 2 ) {

		retcode=writeMemoryFile( fh, buffer, size );

		return retcode;

	}


	leftToWrite = size;
	writePos = fileCursors[fh].writePos;

	// get a local of the blocksize just to keep code more readable
	blockSize = masterBlocks->mblock0.blockSize;

	while(leftToWrite > 0) {

		blockOffset = writePos % blockSize;

		// if blockOffset is 0 then a new block for writing needs to be allocated, unless we 
		// aren't at the end of the file

		if (blockOffset == 0 && writePos == fileCursors[fh].fileSize) {

			if (addNewBlock(fh) == -1) {

				return ERROR_NO_BLOCKS;

			}

		}

		// read block where writing will happen and go from there
		dirEntry = fileCursors[fh].dirEntryNum;

		// read the catalog for this file
		if (readBlock(rootDir->entry[dirEntry].firstCatalogBlock, (void **)&catalogBlock) != 0) {

			return ERROR_READ_ERROR;

		}

		blockNumForWrite = *(unsigned int *)(catalogBlock + (writePos / blockSize));

		deallocate(catalogBlock, blockSize);

		writeLength = minimum(blockSize - blockOffset, leftToWrite);

		if (readBlock(blockNumForWrite, &blockForWrite)!=0) {

			return ERROR_READ_ERROR;

		}

		memcpy(blockForWrite+blockOffset, buffer, writeLength);

		writeBlock(blockForWrite, blockNumForWrite);

		// free the memory for the buffer
		deallocate(blockForWrite, blockSize);

		leftToWrite -= writeLength;

		fileCursors[fh].fileSize += writeLength - (fileCursors[fh].fileSize - writePos);

		writePos += writeLength;

	}

	fileCursors[fh].writePos = writePos;

	return NO_ERROR;

}
CommandTransaction::Result::~Result()
{
  deallocate();
}
Exemplo n.º 21
0
int deleteFile( fileHandleType fh, securityIdType securityID ) {

unsigned int dirEntry;
unsigned int *catalogBlock;
unsigned int *entryPtr;
int retval;

struct memoryFileInfo { 
	unsigned int address;
	unsigned int size;
	char accessType;

	} *memoryInfo;

	if (fh > MAX_OPEN_FILES) {

		return ERROR_BAD_HANDLE;
	}

	if (fileCursors[fh].inUse == 0) {

		return ERROR_BAD_HANDLE;
	}

	if ( (securityID != fileCursors[fh].securityID) && securityID != ROOT_ID && (fileCursors[fh].othersPermissions&0x01) == 0) {

		return ERROR_NO_PERMISSION;

	}

	// read the catalog of blocks for this file
	dirEntry = fileCursors[fh].dirEntryNum;
	
	// read the catalog for this file
	retval = readBlock(rootDir->entry[dirEntry].firstCatalogBlock, (void **)&catalogBlock);

	if (retval != 0) {

		return ERROR_READ_ERROR;

	}

	if ( fileCursors[fh].fileType > 2 ) {

		memoryInfo = (struct memoryFileInfo *)catalogBlock;

		if (memoryInfo->address > 0 ) {

			free((void *)memoryInfo->address);

		}

	}
	else {
	entryPtr = catalogBlock;

		while(*entryPtr != 0) {

			eraseBlock(*entryPtr);
			setBlockAsFree(*entryPtr);
			++entryPtr;
		}
	}

	deallocate((void *)catalogBlock, masterBlocks->mblock0.blockSize);

	eraseBlock(rootDir->entry[dirEntry].firstCatalogBlock);

	setBlockAsFree(rootDir->entry[dirEntry].firstCatalogBlock);

	rootDir->entry[dirEntry].name[0] = 0;
	rootDir->entry[dirEntry].fileSize = 0;
	rootDir->entry[dirEntry].firstCatalogBlock = 0;
	rootDir->numEntries--;

	fileCursors[fh].dirEntryNum = 0;
	fileCursors[fh].inUse = 0;
	fileCursors[fh].writePos = 0;
	fileCursors[fh].readPos = 0;
	fileCursors[fh].fileSize = 0;
	fileCursors[fh].othersPermissions = 0;

	return NO_ERROR;
}
Exemplo n.º 22
0
/**
 * Description not yet available.
 * \param
 */
 dvar5_array::~dvar5_array()
 {
   deallocate();
 }
Exemplo n.º 23
0
memblock::~memblock (void) throw()		{ deallocate(); }
Exemplo n.º 24
0
int tbir_read_pixels( ptbir_image_data tid )
{
	char one[] = { ' ', '.' };
	char two[] = { ' ', '#', '*', '@' };
	char six[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
	char seven[] = {' ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_','`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~'};

	int dword_count;
	int *dwords;
	int sum = 0;

	int pixel_count;
	int index = 0;
	int pixel;
	int bits_to_consume;

	int column;
	int row;
	int count;

	if ( tid == NULL ) {
		return 0;
	}

	if ( !(tid->flags & TBIR_HEADER) || !(tid->flags & TBIR_FLAGS) 
		|| !(tid->flags & TBIR_PIXELT) || !(tid->flags & TBIR_LOADD) ) {
		return 0;
	}

	/// Should be aligned to 8 bits
	if ( tid->cbit != 0 ) {
		return 0;
	}

	tid->flags |= TBIR_PIXELS;
	
	/// Calculate the length of the pixel data. Round to next 32 bit boundary to assume padding
	dword_count = (tid->width * tid->height) * tid->pixel_type;
	bits_to_consume = ( (dword_count + 31) & 0xffffffe0) - dword_count;

	dword_count = (dword_count+bits_to_consume) / 32;

	/// Check boundaries
	if ( (dword_count * 4) + tid->cbyte > tid->max ) {
		printf("Dword count too hight: @d @d @d\n", dword_count*4, tid->cbyte, tid->max);
		return 0;
	}

	dwords = (int*)(tid->buffer + tid->cbyte);

	while ( index < dword_count ) {
		sum = sum ^ dwords[index];
		index++;
	}

	/// If the checksum has already been set then check it
	if ( tid->flags & TBIR_CHKSUM ) {
		if ( sum != tid->checksum ) {
			return 0;
		}
	} else {
		tid->checksum = sum;
	}

	tid->image_length = (tid->height * tid->width);

	if ( allocate( tid->image_length + 1, 0, (void**)&tid->image) != 0 ) {
		return 0;
	}

	cgc_memset( tid->image, ' ', tid->image_length);
	tid->image[ tid->image_length ] = '\x00';

	count = 0;
	pixel = 0;

	while ( count < tid->image_length ) {
		if ( tbir_read_nbits( tid, tid->pixel_type, &pixel) == 0 ) {
			deallocate( tid->image, tid->image_length +1);
			tid->image = NULL;
			tid->image_length = 0;
			return 0;
		}

		switch ( tid->load_direction ) {
                        case 0:
                                row = count / tid->width;
                                column = count % tid->width;
                                break;
                        case 1:
                                row =  count / tid->width;
                                column = (tid->width-1) - (count % tid->width);
                                break;
                        case 2:
                                row = (tid->height-1) - (count/tid->width);
                                column = count % tid->width;
                                break;
                        case 3:
                                row = (tid->height-1) - (count/tid->width);
                                column = (tid->width-1) - ( count % tid->width);
                                break;
                        case 4:
                                row = count % tid->height;
                                column = count / tid->height;
                                break;
                        case 5:
                                row = count % tid->height;
                                column = (tid->width-1) - (count / tid->height );
                                break;
                        case 6:
                                row = ( tid->height-1 ) - ( count % tid->height );
                                column = count / tid->height;
                                break;
                        case 7:
                                row = ( tid->height-1) - ( count % tid->height );
                                column = (tid->width-1) - ( count / tid->height );
                                break;
                        default:
				deallocate( tid->image, tid->image_length +1);
				tid->image = NULL;
				tid->image_length = 0;
                                return 0;
		};

		index = (row * tid->width ) + column;

		switch ( tid->pixel_type ) {
			case 1:
				if ( pixel > 1 ) {
					deallocate( tid->image, tid->image_length +1);
					tid->image = NULL;
					tid->image_length = 0;
					return tid->image_length;
				}

				if ( index > tid->image_length + 1 || index < 0 ) {
					deallocate( tid->image, tid->image_length +1);
					tid->image = NULL;
					tid->image_length = 0;
					return tid->image_length;
				}
					
				tid->image[index] = one[pixel];
				break;
			case 2:
				if ( pixel > 3 ) {
					deallocate( tid->image, tid->image_length +1);
					tid->image = NULL;
					tid->image_length = 0;
					return tid->image_length;
				}

				if ( index > tid->image_length + 1 || index < 0) {
					deallocate( tid->image, tid->image_length +1);
					tid->image = NULL;
					tid->image_length = 0;
					return tid->image_length;
				}

				tid->image[index] = two[pixel];
				break;
			case 6:
				if ( pixel > 61 ) {
					deallocate( tid->image, tid->image_length +1);
					/// Bug
#ifdef PATCHED
					tid->image = NULL;
					tid->image_length = 0;
#endif
					return tid->image_length;
				}

				if ( index > tid->image_length + 1 || index < 0) {
					deallocate( tid->image, tid->image_length +1);
					tid->image = NULL;
					tid->image_length = 0;
					return tid->image_length;
				}

				tid->image[index] = six[pixel];
				break;
			case 7:
				if ( pixel > 0x5e ) {
					deallocate( tid->image, tid->image_length +1);
					tid->image = NULL;
					tid->image_length = 0;
					return tid->image_length;
				}

				if ( index > tid->image_length + 1 || index < 0) {
					deallocate( tid->image, tid->image_length +1);
					tid->image = NULL;
					tid->image_length = 0;
					return tid->image_length;
				}

				tid->image[index] = seven[pixel];
				break;
			default:
				printf("[ERROR] Invalid pixel type\n");
				deallocate( tid->image, tid->image_length +1);
				tid->image = NULL;
				tid->image_length = 0;
				return tid->image_length;
				break;
		};

		//printf("Added @c at row @d column: @d type: @d direction: @d\n", tid->image[index], row, column, tid->pixel_type, tid->load_direction);

		count++;
	}

	/// Consume the remainder bits to align to 32 bits
	if ( tbir_read_nbits( tid, bits_to_consume, &index) == 0 ) {
		deallocate( tid->image, tid->image_length +1);
		tid->image = NULL;
		tid->image_length = 0;
		return 0;
	}

	return 1;

}
Exemplo n.º 25
0
void statement(int loop, Swtch swp, int lev) {
	float ref = refinc;

	if (Aflag >= 2 && lev == 15)
		warning("more than 15 levels of nested statements\n");
	switch (t) {
	case IF:       ifstmt(genlabel(2), loop, swp, lev + 1);
 break;
	case WHILE:    whilestmt(genlabel(3), swp, lev + 1); break;
	case DO:       dostmt(genlabel(3), swp, lev + 1); expect(';');
					break;

	case FOR:      forstmt(genlabel(4), swp, lev + 1);
 break;
	case BREAK:    walk(NULL, 0, 0);
		       definept(NULL);
		       if (swp && swp->lab > loop)
		       	branch(swp->lab + 1);
		       else if (loop)
		       	branch(loop + 2);
		       else
		       	error("illegal break statement\n");
		       t = gettok(); expect(';');
					   break;

	case CONTINUE: walk(NULL, 0, 0);
		       definept(NULL);
		       if (loop)
		       	branch(loop + 1);
		       else
		       	error("illegal continue statement\n");
		       t = gettok(); expect(';');
					      break;

	case SWITCH:   swstmt(loop, genlabel(2), lev + 1);
 break;
	case CASE:     {
		       	int lab = genlabel(1);
		       	if (swp == NULL)
		       		error("illegal case label\n");
		       	definelab(lab);
		       	while (t == CASE) {
		       		static char stop[] = { IF, ID, 0 };
		       		Tree p;
		       		t = gettok();
		       		p = constexpr(0);
		       		if (generic(p->op) == CNST && isint(p->type)) {
		       			if (swp) {
		       				needconst++;
		       				p = cast(p, swp->sym->type);
		       				if (p->type->op == UNSIGNED)
		       					p->u.v.i = extend(p->u.v.u, p->type);
		       				needconst--;
		       				caselabel(swp, p->u.v.i, lab);
		       			}
		       		} else
		       			error("case label must be a constant integer expression\n");

		       		test(':', stop);
		       	}
		       	statement(loop, swp, lev);
		       } break;
	case DEFAULT:  if (swp == NULL)
		       	error("illegal default label\n");
		       else if (swp->deflab)
		       	error("extra default label\n");
		       else {
		       	swp->deflab = findlabel(swp->lab);
		       	definelab(swp->deflab->u.l.label);
		       }
		       t = gettok();
		       expect(':');
		       statement(loop, swp, lev); break;
	case RETURN:   {
		       	Type rty = freturn(cfunc->type);
		       	t = gettok();
		       	definept(NULL);
		       	if (t != ';')
		       		if (rty == voidtype) {
		       			error("extraneous return value\n");
		       			expr(0);
		       			retcode(NULL);
		       		} else
		       			retcode(expr(0));
		       	else {
		       		if (rty != voidtype) {
		       			warning("missing return value\n");
		       			retcode(cnsttree(inttype, 0L));
		       		} else
		       			retcode(NULL);
		       	}
		       	branch(cfunc->u.f.label);
		       } expect(';');
					    break;

	case '{':      compound(loop, swp, lev + 1); break;
	case ';':      definept(NULL); t = gettok(); break;
	case GOTO:     walk(NULL, 0, 0);
		       definept(NULL);
		       t = gettok();
		       if (t == ID) {
		       	Symbol p = lookup(token, stmtlabs);
		       	if (p == NULL) {
				p = install(token, &stmtlabs, 0, FUNC);
				p->scope = LABELS;
				p->u.l.label = genlabel(1);
				p->src = src;
			}
		       	use(p, src);
		       	branch(p->u.l.label);
		       	t = gettok();
		       } else
		       	error("missing label in goto\n"); expect(';');
					  break;

	case ID:       if (getchr() == ':') {
		       	stmtlabel();
		       	statement(loop, swp, lev);
		       	break;
		       }
	default:       definept(NULL);
		       if (kind[t] != ID) {
		       	error("unrecognized statement\n");
		       	t = gettok();
		       } else {
		       	Tree e = expr0(0);
		       	listnodes(e, 0, 0);
		       	if (nodecount == 0 || nodecount > 200)
		       		walk(NULL, 0, 0);
		       	else if (glevel) walk(NULL, 0, 0);
		       	deallocate(STMT);
		       } expect(';');
						break;

	}
	if (kind[t] != IF && kind[t] != ID
	&& t != '}' && t != EOI) {
		static char stop[] = { IF, ID, '}', 0 };
		error("illegal statement termination\n");
		skipto(0, stop);
	}
	refinc = ref;
}
Exemplo n.º 26
0
/**
* Deallocate the chunk of memory at address ptr
* 
* @param ptr The address of the chunk to deallocate
*
* @return None
*/
void free(void* ptr) {

	Run* run_ptr=NULL, *prev_run_ptr=NULL;
	int bit_index=0;
	int ret=0;
	LargeChunk *lc_ptr=NULL, *prev_ptr=NULL;

	// Check to see if ptr is a large chunk
	if(((unsigned int)ptr & 0xfff) == 0 && largeChunks != NULL) {
		for(lc_ptr = largeChunks; lc_ptr!= NULL && lc_ptr->memory != ptr; prev_ptr=lc_ptr, lc_ptr=lc_ptr->next);
	}
	
	// If ptr is a large chunk
	if (lc_ptr != NULL) {
		if((ret = deallocate(ptr, lc_ptr->size)))
			_terminate(4);
		lc_ptr->memory = 0;
		lc_ptr->size = 0;
		if(prev_ptr == NULL)
			largeChunks = lc_ptr->next;
		else
			prev_ptr->next = lc_ptr->next;
		free(lc_ptr);
		return;
	}

	// Find the run the ptr belongs to
	int j;
	for(j=0; j<POOL_NUM; j++) {
		int found=0;
		for(run_ptr = pool[j], prev_run_ptr=NULL; run_ptr != NULL; prev_run_ptr=run_ptr, run_ptr=run_ptr->next) {
			if(run_ptr->memory == ((void *)((unsigned int)ptr & 0xfffff000))) {
				found=1;
				break;
			}
		}
		if(found)
			break;
	}

	// No run found
	if(run_ptr == NULL)
		return;

	// Free and zero chunk
	bit_index = (ptr - run_ptr->memory) / run_ptr->size;
	clearBit(run_ptr->bitmap, bit_index);
	//bzero(ptr, run_ptr->size);

	// Deallocate empty run
	if(isClear(run_ptr->bitmap)) {
		if(prev_run_ptr == NULL)
			pool[j] = run_ptr->next;
		else
			prev_run_ptr->next = run_ptr->next;
		if((ret = deallocate(run_ptr->memory, _SC_PAGESIZE)))
			_terminate(4);
		clearRun(run_ptr);
		if((ret = deallocate(run_ptr, _SC_PAGESIZE)))
			_terminate(4);
		run_ptr = NULL;

	}


}
Exemplo n.º 27
0
// Deallocate the memory used within the PMP_File structure
void PMPDeallocate(PMP_File *pmp) {
  if (pmp->data != 0) {
    deallocate(pmp->data, pmp->data_size);
  }
  pmp->data_size = 0;
}
Exemplo n.º 28
0
	~PetscContext() {
		if (deallocate() != 0) {
			PetscPrintf(_comm, "PetscContext::~PetscContext(...): deallocate() failed\n");
//			PISMEnd();
		}
	}
Exemplo n.º 29
0
/* Callback for JVMTI_EVENT_DATA_DUMP_REQUEST (Ctrl-\ or at exit) */
static void JNICALL
dataDumpRequest(jvmtiEnv *jvmti)
{
    enterAgentMonitor(jvmti); {
        if ( !gdata->vmDeathCalled && !gdata->dumpInProgress ) {
            jvmtiHeapCallbacks heapCallbacks;
            ClassDetails      *details;
            jvmtiError         err;
            jclass            *classes;
            jint               totalCount;
            jint               count;
            jint               i;

            gdata->dumpInProgress = JNI_TRUE;

            /* Get all the loaded classes */
            err = (*jvmti)->GetLoadedClasses(jvmti, &count, &classes);
            check_jvmti_error(jvmti, err, "get loaded classes");

            /* Setup an area to hold details about these classes */
            details = (ClassDetails*)calloc(sizeof(ClassDetails), count);
            if ( details == NULL ) {
                fatal_error("ERROR: Ran out of malloc space\n");
            }
            for ( i = 0 ; i < count ; i++ ) {
                char *sig;

                /* Get and save the class signature */
                err = (*jvmti)->GetClassSignature(jvmti, classes[i], &sig, NULL);
                check_jvmti_error(jvmti, err, "get class signature");
                if ( sig == NULL ) {
                    fatal_error("ERROR: No class signature found\n");
                }
                details[i].signature = strdup(sig);
                deallocate(jvmti, sig);

                /* Tag this jclass */
                err = (*jvmti)->SetTag(jvmti, classes[i],
                                    (jlong)(ptrdiff_t)(void*)(&details[i]));
                check_jvmti_error(jvmti, err, "set object tag");
            }

            /* Iterate through the heap and count up uses of jclass */
            (void)memset(&heapCallbacks, 0, sizeof(heapCallbacks));
            heapCallbacks.heap_iteration_callback = &cbHeapObject;
            totalCount = 0;
            err = (*jvmti)->IterateThroughHeap(jvmti,
                       JVMTI_HEAP_FILTER_CLASS_UNTAGGED, NULL,
                       &heapCallbacks, (const void *)&totalCount);
            check_jvmti_error(jvmti, err, "iterate through heap");

            /* Remove tags */
            for ( i = 0 ; i < count ; i++ ) {
                /* Un-Tag this jclass */
                err = (*jvmti)->SetTag(jvmti, classes[i], (jlong)0);
                check_jvmti_error(jvmti, err, "set object tag");
            }

            /* Sort details by space used */
            qsort(details, count, sizeof(ClassDetails), &compareDetails);

            /* Print out sorted table */
            stdout_message("Heap View, Total of %d objects found.\n\n",
                         totalCount);

            stdout_message("Space      Count      Class Signature\n");
            stdout_message("---------- ---------- ----------------------\n");

            for ( i = 0 ; i < count ; i++ ) {
                if ( details[i].space == 0 || i > 20 ) {
                    break;
                }
                stdout_message("%10d %10d %s\n",
                    details[i].space, details[i].count, details[i].signature);
            }
            stdout_message("---------- ---------- ----------------------\n\n");

            /* Free up all allocated space */
            deallocate(jvmti, classes);
            for ( i = 0 ; i < count ; i++ ) {
                if ( details[i].signature != NULL ) {
                    free(details[i].signature);
                }
            }
            free(details);

            gdata->dumpInProgress = JNI_FALSE;
        }
    } exitAgentMonitor(jvmti);
}
Exemplo n.º 30
0
 ~BPPottsPotential(){
   deallocate( norm_ );
 }