int main(void) { int i; void* orig_ds = sbrk(0); void* ds = orig_ds; void* vals[10]; void* res; void *prev; #define EOL ((void*)( ~(long)0 )) vals[0] = (void*)0; vals[1] = (void*)1; vals[2] = ds - 0x1; // small shrink vals[3] = ds; vals[4] = ds + 0x1000; // small growth vals[5] = ds + 0x40000000; // too-big growth vals[6] = ds + 0x500; // shrink a little, but still above start size vals[7] = ds - 0x1; // shrink below start size // vals[8] = ds - 0x1000; // shrink a lot below start size (into text) // vals[9] = EOL; vals[8] = EOL; for (i = 0; EOL != vals[i]; i++) { res = brk(vals[i]); } assert( 0 == brk(orig_ds) ); // libc brk() for (i = 0; EOL != vals[i]; i++) { res = (void*)brk(vals[i]); } return 0; }
void *sbrk(intptr_t incr) { uintptr_t oldbrk; /* If we don't have a saved break, find it from the kernel */ if (!__curbrk) { if (0 > (long)(__curbrk = (void *) trap(SYS_brk, (uint32_t) NULL))) { return (void *) -1; } } oldbrk = (uintptr_t) __curbrk; /* Increment or decrement the saved break */ if (incr < 0) { if ((uintptr_t) - incr > oldbrk) { return (void *) -1; } else if (brk((void *)(oldbrk - (uintptr_t) - incr)) < 0) { return (void *) -1; } } else if (incr > 0) { if (brk((void *)(oldbrk + (uintptr_t) incr)) < 0) { return (void *) -1; } } return (void *) oldbrk; }
void * sbrk(unsigned int ptrdiff) { void *newend; /* have we been initialized yet? */ if (curheap == 0) { curheap = (void *) brk(0); } /* are they just querying the current heap? */ if (ptrdiff == 0) { return curheap; } /* where we want our new heap to end */ newend = curheap + ptrdiff; /* can we get the memory? */ if (brk(newend) < 0) { return 0; } /* we got the memory */ curheap = newend; return curheap - ptrdiff; }
int openbsd_gt_pch_use_address (void *base, size_t size, int fd ATTRIBUTE_UNUSED, size_t off ATTRIBUTE_UNUSED) { void *addr; if (size == 0) return -1; /* sanity check base address */ addr = sbrk(0); if (addr == (void *)-1 || base < addr) return -1; /* set base for sbrk */ if (brk(base) != 0) return -1; /* attempt to get the memory */ addr = sbrk(size); if (addr == (void *)-1) return -1; /* sanity check the result */ if (addr != base) { brk(base); return -1; } return 0; }
void * openbsd_gt_pch_get_address (size_t size, int fd ATTRIBUTE_UNUSED) { void *base, *addr; size_t pgsz; if (size > INT_MAX) return NULL; pgsz = sysconf(_SC_PAGESIZE); if (pgsz == (size_t)-1) return NULL; base = sbrk(0); /* round up to nearest page */ base = (void *)(((long)base + (pgsz - 1)) & ~(pgsz - 1)); if (brk(base) != 0) return NULL; /* attempt to allocate size */ addr = sbrk(size); if (addr == (void *)-1) return NULL; /* deallocate the memory */ if (brk(base) != 0) return NULL; /* confirm addr is as expected */ if (addr != base) return NULL; return base; }
int main(void) { //获取起始地址 void* p = sbrk(0); printf("p = %p\n",p); //申请4个字节内存空间 int res = brk(p+4); if(-1 == res) { perror("brk"),exit(-1); } printf("成功申请了4个字节的内存\n"); void* cur = sbrk(0); printf("cur = %p\n",cur); //申请了4个字节 brk(p+8); cur = sbrk(0); printf("cur = %p\n",cur); //释放了4个字节内存 brk(p+4); cur = sbrk(0); printf("cur = %p\n",cur); //释放所有内存 brk(p); return 0; }
void free(void *ptr) { if (unlikely(!ptr)) { return; } pthread_mutex_lock(&list_lock); metadata_t* block_ptr = get_block(ptr); merge_block(block_ptr); if (unlikely(block_ptr->free != 0 || block_ptr->magic1 != MAGIC_USED || block_ptr->magic1 != block_ptr->magic2)) { printf(SEGFAULT); exit(-1); } alloc_count--; if (unlikely(alloc_count == 0)){ brk(base); base = 0; } else if (block_ptr->next == NULL){ block_ptr->prev->next = NULL; brk(block_ptr); } else { block_ptr->free = 1; block_ptr->magic1 = MAGIC_FREE; block_ptr->magic2 = MAGIC_FREE; } pthread_mutex_unlock(&list_lock); }
void *sbrk(ssize_t increment) { void *newbrk, *oldbrk; oldbrk= brk(0); if (!increment) return oldbrk; newbrk= brk(oldbrk + increment); if (newbrk == oldbrk) return (void *)-1; return oldbrk; }
int main () { if (1) { if (x > 1 ) { foo(); brk(); } } else aaa(); if (1) while (x > 1 ) { foo(); brk(); } else aaa(); foo(); brk(); }
/* * Try to spend as much time as possible in kernelspace * to elapse ITIMER_PROF. */ static void kernel_loop(void) { void *addr = sbrk(0); while (!done) { brk(addr + 4096); brk(addr); } }
/* * ---------------------------------------------------------------------------- * Free space previously allocated by malloc. This memory can now be used again * Also, colless any contiguous free nodes into one large free node to make * larger spaces available for larger allocation requests * ---------------------------------------------------------------------------- */ void my_free(void *ptr){ // Mark the node as free Node n = (Node)ptr - 1; n->free = 1; // If contiguous free space nodes exist, combine them into a single node // AKA: coalesce! // First look and see if a node has extra space behind it if (n->prev != NULL){ if (n->prev->free == 1){ n->prev->size = n->size + sizeof(struct node); n->prev->next = n->next; if (last == n) last = n->prev; if (cur == n) cur = n->prev; n = n->prev; } } //Now look and see if a node in front of the node is free if (n->next != NULL){ if (n->next->free == 1){ n->size += n->next->size + sizeof(struct node); n->next = n->next->next; } } // When the last node is free, we can cut it off and resize the heap to // contain only wnat we need // AKA: truncating if (n == last){ if (last == first){ first = 0; cur = 0; last = 0; brk((void*)(n)); } else if (last == cur){ cur = cur->prev; last = last->prev; last->next = NULL; brk((void*)(n-1)); } else{ last = last->prev; last->next = NULL; brk((void*)(n-1)); } } }
/* * Try to spend as much time as possible in kernelspace * to elapse ITIMER_PROF. */ static void kernel_loop(void) { void *addr = sbrk(0); int err = 0; while (!done && !err) { err = brk(addr + 4096); err |= brk(addr); } }
TEST(UNISTD_TEST, brk) { void* initial_break = get_brk(); // The kernel aligns the break to a page. void* new_break = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(initial_break) + 1); ASSERT_EQ(0, brk(new_break)); ASSERT_GE(get_brk(), new_break); new_break = page_align(reinterpret_cast<uintptr_t>(initial_break) + sysconf(_SC_PAGE_SIZE)); ASSERT_EQ(0, brk(new_break)); ASSERT_EQ(get_brk(), new_break); }
int main() { //1.找到空闲空间的首地址 int* p=(int*)sbrk(0); printf("sbrk(0):%p\n",p); //2.分配空间 brk(p+1); printf("brk:%p\n",p); //3.使用空间 *p=800; //4. 释放空间 brk(p); return 0; }
void testcase(unsigned long long *iterations) { void *addr = sbrk(0); unsigned long page_size = getpagesize(); while (1) { addr += page_size; brk(addr); addr -= page_size; brk(addr); (*iterations) += 2; } }
int main() { void *addr; char *str; int i; /* get the current brk point */ addr = sbrk(0); /* create a new brk point that is higher than the current and also page aligned */ addr = (void*)(((int)addr & 0xfffff000)+ 0x2000); /* set the new brk to addr */ if (brk(addr) != 0) { fprintf(stderr, "brk() failed: %s\n", strerror(errno)); return -1; } str = ((char *)addr) - 10; /* fill in the string up to the brk point */ for(i = 0; i < 10; i++) str[i] = 'f'; /* call foo and cross our fingers */ //printf("%s\n",str ); foo(str); return 0; }
static bool getYesterdayTodayAndTomorrow(JNIEnv* env, jobject localeData, const Locale& locale, const char* locale_name) { UErrorCode status = U_ZERO_ERROR; ScopedResourceBundle root(ures_open(NULL, locale_name, &status)); ScopedResourceBundle fields(ures_getByKey(root.get(), "fields", NULL, &status)); ScopedResourceBundle day(ures_getByKey(fields.get(), "day", NULL, &status)); ScopedResourceBundle relative(ures_getByKey(day.get(), "relative", NULL, &status)); if (U_FAILURE(status)) { return false; } UnicodeString yesterday(ures_getUnicodeStringByKey(relative.get(), "-1", &status)); UnicodeString today(ures_getUnicodeStringByKey(relative.get(), "0", &status)); UnicodeString tomorrow(ures_getUnicodeStringByKey(relative.get(), "1", &status)); if (U_FAILURE(status)) { ALOGE("Error getting yesterday/today/tomorrow for %s: %s", locale_name, u_errorName(status)); return false; } // We title-case the strings so they have consistent capitalization (http://b/14493853). UniquePtr<BreakIterator> brk(BreakIterator::createSentenceInstance(locale, status)); if (U_FAILURE(status)) { ALOGE("Error getting yesterday/today/tomorrow break iterator for %s: %s", locale_name, u_errorName(status)); return false; } yesterday.toTitle(brk.get(), locale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT); today.toTitle(brk.get(), locale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT); tomorrow.toTitle(brk.get(), locale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT); setStringField(env, localeData, "yesterday", yesterday); setStringField(env, localeData, "today", today); setStringField(env, localeData, "tomorrow", tomorrow); return true; }
int main () { int i; int inc_dec; int delta; intptr_t brk_stat; // loop to first increase, then decrease for (inc_dec = 1; inc_dec >= -1; inc_dec-=2) { // loop to increase(decrease) with small then big delta for (delta = 1; delta <= 400; delta+=399) { if (0) printf("initial brk value for inc_dec %d delta %d: %p\n", inc_dec, delta, sbrk(0)); for (i=0; i<MAX; i++) { brk_stat = (intptr_t)brk(sbrk(0) + inc_dec * delta); if (brk_stat == -1) { printf("brk value at failure: %p\n", sbrk(0)); perror ("brk() failed!\n"); return 0; } } if (0) printf("resulting brk value for inc_dec %d delta %d: %p\n", inc_dec, delta, sbrk(0)); } } return 0; }
void free(void *ptr){ sum_frees++; num_allocated--; block_t current; if (valid_address(ptr)){ current = get_block(ptr); current->free = 1; if(current->prev && current->prev->free){ //merge with prev block if works current = merge_block(current->prev); } if (current->next){ //merge with next merge_block(current); } else { if (current->prev){ current->prev->next = NULL; } else { //no more blocks base = NULL; } brk(current); } } else { perror("invalid ptr at free"); } }
void * _PDCLIB_allocpages( int const n ) { if ( membreak == NULL ) { /* first call, make sure end-of-heap is page-aligned */ intptr_t unaligned = 0; membreak = sbrk( 0 ); unaligned = _PDCLIB_PAGESIZE - (intptr_t)membreak % _PDCLIB_PAGESIZE; if ( unaligned < _PDCLIB_PAGESIZE ) { /* end-of-heap not page-aligned - adjust */ if ( sbrk( unaligned ) != membreak ) { /* error */ return NULL; } membreak = (char *)membreak + unaligned; } } /* increasing or decreasing heap - standard operation */ void * oldbreak = membreak; membreak = (void *)( (char *)membreak + ( n * _PDCLIB_PAGESIZE ) ); if ( brk( membreak ) == 0 ) { /* successful */ return oldbreak; } else { /* out of memory */ membreak = oldbreak; return NULL; } }
void* mm_malloc(size_t size) { s_block_ptr active = first; s_block_ptr segment = NULL; s_block_ptr extend = sbrk(0); //returns break address //Search for free block in memory *last = active; if(active!=NULL) { } //Split block into segments if active size is less than block size segment = active; size_t comparisonsize = active->size; if((comparisonsize) < (sizeof(struct s_block))) { segment->free = 'true'; active->free = 'false'; } //Increase heap size when block too small else{ if(extend !=NULL) { while(extend->size < active-size) { extend->size = extend->size + 4096; //4096 = page size } int result = brk(*extend); if(result == 0) extend->free = 'false'; } } }
void *_sbrk(intptr_t incr) { void *oldbrk = curbrk; if (brk(oldbrk + incr) == -1) return (void *)-1; return oldbrk; }
int main() { char *s; // sbrkはヒープ領域のブレーク値を加算して変更します。 // プロセスのメモリ未割り当て領域を「ヒープ」といい、ヒープ上の未割り当てメモリの先頭アドレスを「ブレーク値」といいます。 // // sbrkシステムコールはブレーク値をバイト数指定で加算します。 // 整数を指定してsbrkを実行すると、ヒープ領域にメモリを動的に割り当てます。 // 負数を指定してsbrkを実行すると、その分のメモリは解放されます。 // [memo] "warning: comparison between pointer and integer [enabled by default]"のwarningエラーのため(void*)でキャストする if ((s = sbrk(13)) == (void*)-1) { // 13 = "Hello World\n" perror("sbrk"); return 1; } strcpy(s, "Hello World\n"); write(1, s, 12); // brkシステムコール及びsbrkシステムコールを利用してブレーク値を変更することで、メモリの割り当てと解放を行うことができます。 // // brkシステムコールはプロセスに新しいブレーク値を任意に設定します。 // 指定したブレーク値が現在のブレーク値より大きい場合には、ヒープ領域にメモリを割り当てます。 // 指定したブレーク値が現在のブレーク値より小さい場合には、ヒープ領域に動的に割り当てられたメモリを解放します。 if (brk(s) < 0) { perror("brk"); return 1; } return 0; }
int main(){ printf("below are address of type of process's mem\n"); printf("Text location代码段:\n"); printf("\tAddress of main(Code Segment):%p\n",main); printf("__________________________________\n"); int stack_var0 = 2; printf("Stack Location栈段:\n"); printf("\tInitial end of stack:%p\n",&stack_var0); int stack_var1 = 3; printf("\t new end of stack:%p\n",&stack_var1); printf("__________________________________\n"); printf("Data Location:数据段\n"); printf("\tAddress of data_var(Data Segment):%p\n",&data_var0); static int data_var1= 4; printf("\t NEW ned of data_var(Data Segment):%p\n",&data_var1); printf("__________________________________\n"); printf("BSS Location:bss段\n"); printf("\tAddress of bss_var:%p\n",&bss_var); printf("__________________________________\n"); char *b = sbrk((ptrdiff_t)0); printf("Heap Location:\n"); printf("\t Initial end of heap:%p\n",b); brk(b+4); b=sbrk((ptrdiff_t)0); printf("\tNew end of heap:%p\n",b); return 0; }
/* Restore checkpoint header */ int ckptRestoreHeader(ckptImage * image, size_t size, void **stack_start) { struct ckptCheckpointHdr header; ckptReadChunkData(image, &header); if (header.np != CKPT_NP) { ckptLog(CKPT_LOG_ERROR, "Number of processes mismatch: was %d, now %d", header.np, CKPT_NUMBER); abort(); } if (!ckptDisableMtimeCheck && header.mtime != ckptElfGetMtime()) { ckptLog(CKPT_LOG_ERROR, "Wrong program image file (%lu != %lu)", header.mtime, ckptElfGetMtime()); abort(); } if (brk((void *)header.brk) != 0) { ckptLog(CKPT_LOG_ERROR, "Unable to set new break @%p", header.brk); abort(); } *stack_start = (void *)header.stack_start; return 1; }
void PowerON_Reset_PC(void) { set_intb((void*)__sectop("C$VECT")); // set_fpsw(FPSW_init); _INITSCT(); // _INIT_IOLIB(); // Remove the comment when you use SIM I/O // errno=0; // Remove the comment when you use errno // srand((_UINT)1); // Remove the comment when you use rand() // _s1ptr=NULL; // Remove the comment when you use strtok() // HardwareSetup(); // Use Hardware Setup nop(); // _CALL_INIT(); // Remove the comment when you use global class object set_psw(PSW_init); // Set Ubit & Ibit for PSW // Change_PSW_PM_to_UserMode(); // DO NOT CHANGE TO USER MODE IF USING FREERTOS! ( void ) Change_PSW_PM_to_UserMode; // Just to avoid compiler warnings. main(); // _CLOSEALL(); // Use SIM I/O // _CALL_END(); // Remove the comment when you use global class object brk(); }
void _free(void *ptr) { t_block *block; RETURN(!ptr || ptr > LAST_PTR() || ptr < FIRST_PTR()); block = GET_BLOCK(ptr); RETURN(block->isFree); block->isFree = true; if (block->parent == last && last->startBlock == last->lastBlock) { if (!(last = last->prev)) blocks = NULL; else last->next = NULL; brk(block->parent); } else if (block == block->parent->lastBlock) { if (!(block->parent->lastBlock = block->prev)) block->parent->startBlock = NULL; block->parent->freeSize += B_SIZE(block->size); } else if (block->parent->maxFreeSize < block->size) block->parent->maxFreeSize = block->size; }
static struct memh *brkmore(size_t nb) { struct memh *p; if (nb < BRKSIZE) nb = BRKSIZE; /* Here be dragons: sbrk takes a signed value. We can however in C malloc a size_t: We also assume nobody else misaligns the brk boundary, we won't fix it if so - maybe we should ? */ /* Current end of memory */ p = sbrk(0); if (p == (struct memh *) -1) return NULL; /* Overflow catch */ if (p + nb < p) return NULL; /* Move our break point. Using brk this way avoids the sign problems */ if (brk(p + nb)) return NULL; /* Fake it as a used block and free it into the free list */ p->size = nb; free(p + 1); return __mfreeptr; }
void PowerON_Reset_PC(void) { #ifdef __RXV2 set_extb(__sectop("EXCEPTVECT")); #endif set_intb(__sectop("C$VECT")); #ifdef __ROZ /* Initialize FPSW */ #define _ROUND 0x00000001 /* Let FPSW RMbits=01 (round to zero) */ #else #define _ROUND 0x00000000 /* Let FPSW RMbits=00 (round to nearest) */ #endif #ifdef __DOFF #define _DENOM 0x00000100 /* Let FPSW DNbit=1 (denormal as zero) */ #else #define _DENOM 0x00000000 /* Let FPSW DNbit=0 (denormal as is) */ #endif set_fpsw(FPSW_init | _ROUND | _DENOM); _INITSCT(); /* Initialize Sections */ HardwareSetup(); /* Use Hardware Setup */ nop(); set_psw(PSW_init); /* Set Ubit & Ibit for PSW */ main(); brk(); }
static void sbrk_test(void) { #if defined(__s390__) && __WORDSIZE == 32 void *ret1, *ret2; /* set bkr to 0x10000000 */ tst_res(TINFO, "initial brk: %d", brk((void *)0x10000000)); /* add 0x10000000, up to total of 0x20000000 */ tst_res(TINFO, "sbrk increm: %p", sbrk(0x10000000)); ret1 = sbrk(0); /* sbrk() returns -1 on s390, but still does overflowed brk() */ tst_res(TINFO, "sbrk increm: %p", sbrk(0x70000000)); ret2 = sbrk(0); if (ret1 != ret2) { tst_res(TFAIL, "Bug! sbrk: %p", ret2); return; } tst_res(TPASS, "sbrk verify: %p", ret2); #else tst_res(TCONF, "Only works in 32bit on s390 series system"); #endif }