void * malloc(uint64_t size) { void * ret = sbrk(0); // pido la direccion actual sbrk(size); // "incremento" el segmento de datos return ret; }
static void* get_brk() { return sbrk(0); }
int main(int ac, char **av) { int lc; /* loop counter */ const char *msg; /* message returned from parse_opts */ long tret; /*************************************************************** * parse standard options ***************************************************************/ if ( (msg=parse_opts(ac, av, (option_t *) NULL, NULL)) != (char *) NULL ) { tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); tst_exit(0); } /*************************************************************** * perform global setup for test ***************************************************************/ setup(); /*************************************************************** * check looping state if -c option given ***************************************************************/ for (lc=0; TEST_LOOPING(lc); lc++) { /* reset Tst_count in case we are looping. */ Tst_count=0; /* * TEST CASE: * Increase by 8192 bytes */ Increment = 8192; /* Call sbrk(2) */ #if defined(sgi) tret=(long)sbrk(Increment); /* Remove -64 IRIX compiler warning */ TEST_ERRNO=errno; #else TEST(sbrk(Increment)); tret=TEST_RETURN; #endif /* check return code */ if ( tret == -1 ) { TEST_ERROR_LOG(TEST_ERRNO); tst_resm(TFAIL, "sbrk - Increase by 8192 bytes failed, errno=%d : %s", TEST_ERRNO, strerror(TEST_ERRNO)); } else { /*************************************************************** * only perform functional verification if flag set (-f not given) ***************************************************************/ if ( STD_FUNCTIONAL_TEST ) { /* No Verification test, yet... */ tst_resm(TPASS, "sbrk - Increase by 8192 bytes returned %d", tret); } } /* * TEST CASE: * Decrease to original size */ Increment=(Increment * -1); /* Call sbrk(2) */ #ifdef CRAY TEST(sbrk(Increment)); tret=TEST_RETURN; #else tret=(long)sbrk(Increment); TEST_ERRNO=errno; #endif /* check return code */ if ( tret == -1 ) { TEST_ERROR_LOG(TEST_ERRNO); tst_resm(TFAIL, "sbrk - Decrease to original size failed, errno=%d : %s", TEST_ERRNO, strerror(TEST_ERRNO)); } else { /*************************************************************** * only perform functional verification if flag set (-f not given) ***************************************************************/ if ( STD_FUNCTIONAL_TEST ) { /* No Verification test, yet... */ tst_resm(TPASS, "sbrk - Decrease to original size returned %d", tret); } } } /* End for TEST_LOOPING */ /*************************************************************** * cleanup and exit ***************************************************************/ cleanup(); return 0; } /* End main */
auto struct scnhdr f_thdr; /* Text section header */ auto struct scnhdr f_dhdr; /* Data section header */ auto struct scnhdr f_bhdr; /* Bss section header */ auto struct scnhdr scntemp; /* Temporary section header */ register int scns; unsigned int bss_start; unsigned int data_start; pagemask = getpagesize () - 1; /* Adjust text/data boundary. */ data_start = (int) DATA_START; data_start = ADDR_CORRECT (data_start); data_start = data_start & ~pagemask; /* (Down) to page boundary. */ bss_start = ADDR_CORRECT (sbrk (0)) + pagemask; bss_start &= ~ pagemask; if (data_start > bss_start) /* Can't have negative data size. */ { ERROR2 ("unexec: data_start (%u) can't be greater than bss_start (%u)", data_start, bss_start); } coff_offset = 0L; /* stays zero, except in DJGPP */ /* Salvage as much info from the existing file as possible */ if (a_out >= 0) { #ifdef MSDOS /* Support the coff-go32-exe format with a prepended stub, since
int main(void) { char *p; char *q; char *temp; int i, n, t1, t2, flag=0; // sbrk allocation phase t1 = uptime(); for(n = 0; n < NUM_ALLOCS; n++) { p = sbrk(4096); if(flag == 0) { flag = 1; temp = p; } } t2 = uptime(); printf(1, "Time for sbrk in allocation phase is %d, average %d\n", t2 - t1, (t2 - t1) / NUM_ALLOCS); // sbrk writing phase p = temp; printf(1, "Address of first page in sbrk is 0x%x\n", p); flag = 0; t1 = uptime(); for(n = 0; n < NUM_ALLOCS; n++) { for(i = 0; i < 4096; i++) { *(p+i)='a'; } p+=4096; } t2 = uptime(); printf(1, "Time for sbrk in writing phase is %d, average %d\n", t2 - t1, (t2 - t1) / NUM_ALLOCS); // dsbrk allocation phase t1 = uptime(); for(n = 0; n < NUM_ALLOCS; n++) { q = dsbrk(4096); if(flag == 0) { flag = 1; temp = q; } } t2 = uptime(); printf(1,"Time for dsbrk in allocation phase is %d, average %d\n", t2 - t1, (t2 - t1) / NUM_ALLOCS); // dsbrk writing phase q = temp; printf(1, "Address of first page in dsbrk is 0x%x\n", q); flag = 0; t1 = uptime(); for(n = 0;n < NUM_ALLOCS; n++) { for(i = 0;i < 4096; i++) { *(q+i)='a'; } q+=4096; } t2 = uptime(); printf(1,"Time for dsbrk in writing phase is %d, average %d\n", t2 - t1, (t2 - t1) / NUM_ALLOCS); exit(); }
/* NOTE: 1999-04-30 This is the asynchronous version of the command_loop function. The command_loop function will be obsolete when we switch to use the event loop at every execution of gdb. */ static void command_handler (char *command) { struct cleanup *old_chain; int stdin_is_tty = ISATTY (stdin); struct continuation_arg *arg1; struct continuation_arg *arg2; long time_at_cmd_start; #ifdef HAVE_SBRK long space_at_cmd_start = 0; #endif extern int display_time; extern int display_space; quit_flag = 0; if (instream == stdin && stdin_is_tty) reinitialize_more_filter (); old_chain = make_cleanup (null_cleanup, 0); /* If readline returned a NULL command, it means that the connection with the terminal is gone. This happens at the end of a testsuite run, after Expect has hung up but GDB is still alive. In such a case, we just quit gdb killing the inferior program too. */ if (command == 0) quit_command ((char *) 0, stdin == instream); time_at_cmd_start = get_run_time (); if (display_space) { #ifdef HAVE_SBRK char *lim = (char *) sbrk (0); space_at_cmd_start = lim - lim_at_start; #endif } execute_command (command, instream == stdin); /* Set things up for this function to be compete later, once the execution has completed, if we are doing an execution command, otherwise, just go ahead and finish. */ if (target_can_async_p () && target_executing) { arg1 = (struct continuation_arg *) xmalloc (sizeof (struct continuation_arg)); arg2 = (struct continuation_arg *) xmalloc (sizeof (struct continuation_arg)); arg1->next = arg2; arg2->next = NULL; arg1->data.longint = time_at_cmd_start; #ifdef HAVE_SBRK arg2->data.longint = space_at_cmd_start; #endif add_continuation (command_line_handler_continuation, arg1); } /* Do any commands attached to breakpoint we stopped at. Only if we are always running synchronously. Or if we have just executed a command that doesn't start the target. */ if (!target_can_async_p () || !target_executing) { bpstat_do_actions (&stop_bpstat); do_cleanups (old_chain); if (display_time) { long cmd_time = get_run_time () - time_at_cmd_start; printf_unfiltered ("Command execution time: %ld.%06ld\n", cmd_time / 1000000, cmd_time % 1000000); } if (display_space) { #ifdef HAVE_SBRK char *lim = (char *) sbrk (0); long space_now = lim - lim_at_start; long space_diff = space_now - space_at_cmd_start; printf_unfiltered ("Space used: %ld (%c%ld for this command)\n", space_now, (space_diff >= 0 ? '+' : '-'), space_diff); #endif } } }
void * bsdmalloc(size_t nbytes) { union overhead *op; int bucket, n; unsigned amt; /* * First time malloc is called, setup page size and * align break pointer so all data will be page aligned. */ if (pagesz == 0) { pagesz = n = getpagesize(); op = (union overhead *)sbrk(0); n = n - sizeof (*op) - ((int)op & (n - 1)); if (n < 0) n += pagesz; if (n) { if (sbrk(n) == (char *)-1) { return (NULL); }; } bucket = 0; amt = 8; while (pagesz > amt) { amt <<= 1; bucket++; } pagebucket = bucket; } /* * Convert amount of memory requested into closest block size * stored in hash buckets which satisfies request. * Account for space used per block for accounting. */ if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) { #ifndef RCHECK amt = 8; /* size of first bucket */ bucket = 0; #else amt = 16; /* size of first bucket */ bucket = 1; #endif n = -(sizeof (*op) + RSLOP); } else { amt = pagesz; bucket = pagebucket; } while (nbytes > amt + n) { amt <<= 1; if (amt == 0) { return (NULL); }; bucket++; } /* * If nothing in hash bucket right now, * request more memory from the system. */ if ((op = nextf[bucket]) == NULL) { bsdmorecore(bucket); if ((op = nextf[bucket]) == NULL) { return (NULL); }; } /* remove from linked list */ nextf[bucket] = op->ov_next; op->ov_magic = MAGIC; op->ov_index = bucket; #ifdef MSTATS nmalloc[bucket]++; #endif #ifdef RCHECK /* * Record allocated size of block and * bound space with magic numbers. */ op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); op->ov_rmagic = RMAGIC; *(unsigned short *)((char *)(op + 1) + op->ov_size) = RMAGIC; #endif return ((char *)(op + 1)); }
char * get_high_address() { return (char *)sbrk(0) + 16384; }
void *dos_getmaxlockedmem(int *size) { __dpmi_free_mem_info meminfo; __dpmi_meminfo info; int working_size; void *working_memory; int last_locked; int extra, i, j, allocsize; static char *msg = "Locking data..."; int m, n; byte *x; // first lock all the current executing image so the locked count will // be accurate. It doesn't hurt to lock the memory multiple times last_locked = __djgpp_selector_limit + 1; info.size = last_locked - 4096; info.address = __djgpp_base_address + 4096; if (lockmem) { if(__dpmi_lock_linear_region(&info)) { Sys_Error ("Lock of current memory at 0x%lx for %ldKb failed!\n", info.address, info.size/1024); } } __dpmi_get_free_memory_information(&meminfo); if (!win95) /* Not windows or earlier than Win95 */ { working_size = meminfo.maximum_locked_page_allocation_in_pages * 4096; } else { working_size = meminfo.largest_available_free_block_in_bytes - LEAVE_FOR_CACHE; } working_size &= ~0xffff; /* Round down to 64K */ working_memory += 0x10000; do { working_size -= 0x10000; /* Decrease 64K and try again */ working_memory = sbrk(working_size); } while (working_memory == (void *)-1); extra = 0xfffc - ((unsigned)sbrk(0) & 0xffff); if (extra > 0) { sbrk(extra); working_size += extra; } // now grab the memory info.address = last_locked + __djgpp_base_address; if (!win95) { info.size = __djgpp_selector_limit + 1 - last_locked; while (info.size > 0 && __dpmi_lock_linear_region(&info)) { info.size -= 0x1000; working_size -= 0x1000; sbrk(-0x1000); } } else { /* Win95 section */ j = COM_CheckParm("-winmem"); if (j) { allocsize = ((int)(Q_atoi(com_argv[j+1]))) * 0x100000 + LOCKED_FOR_MALLOC; if (allocsize < (MINIMUM_WIN_MEMORY + LOCKED_FOR_MALLOC)) allocsize = MINIMUM_WIN_MEMORY + LOCKED_FOR_MALLOC; } else { allocsize = MINIMUM_WIN_MEMORY + LOCKED_FOR_MALLOC; } if (!lockmem) { // we won't lock, just sbrk the memory info.size = allocsize; goto UpdateSbrk; } // lock the memory down write (STDOUT, msg, strlen (msg)); for (j=allocsize ; j>(MINIMUM_WIN_MEMORY + LOCKED_FOR_MALLOC) ; j -= 0x100000) { info.size = j; if (!__dpmi_lock_linear_region(&info)) goto Locked; write (STDOUT, ".", 1); } // finally, try with the absolute minimum amount for (i=0 ; i<10 ; i++) { info.size = MINIMUM_WIN_MEMORY + LOCKED_FOR_MALLOC; if (!__dpmi_lock_linear_region(&info)) goto Locked; } Sys_Error ("Can't lock memory; %d Mb lockable RAM required. " "Try shrinking smartdrv.", info.size / 0x100000); Locked: UpdateSbrk: info.address += info.size; info.address -= __djgpp_base_address + 4; // ending point, malloc align working_size = info.address - (int)working_memory; sbrk(info.address-(int)sbrk(0)); // negative adjustment } if (lockunlockmem) { __dpmi_unlock_linear_region (&info); printf ("Locked and unlocked %d Mb data\n", working_size / 0x100000); } else if (lockmem) { printf ("Locked %d Mb data\n", working_size / 0x100000); } else { printf ("Allocated %d Mb data\n", working_size / 0x100000); } // touch all the memory to make sure it's there. The 16-page skip is to // keep Win 95 from thinking we're trying to page ourselves in (we are // doing that, of course, but there's no reason we shouldn't) x = (byte *)working_memory; for (n=0 ; n<4 ; n++) { for (m=0 ; m<(working_size - 16 * 0x1000) ; m += 4) { sys_checksum += *(int *)&x[m]; sys_checksum += *(int *)&x[m + 16 * 0x1000]; } } // give some of what we locked back for malloc before returning. Done // by cheating and passing a negative value to sbrk working_size -= LOCKED_FOR_MALLOC; sbrk( -(LOCKED_FOR_MALLOC)); *size = working_size; return working_memory; }
static void vfstest_s5fs_vm(void) { int fd, newfd, ret; char buf[2048]; struct stat oldstatbuf, newstatbuf; void *addr; syscall_success(mkdir("s5fs", 0)); syscall_success(chdir("s5fs")); /* Open some stuff */ syscall_success(fd = open("oldchld", O_RDWR | O_CREAT, 0)); syscall_success(mkdir("parent", 0)); /* link/unlink tests */ syscall_success(link("oldchld", "newchld")); /* Make sure stats match */ syscall_success(stat("oldchld", &oldstatbuf)); syscall_success(stat("newchld", &newstatbuf)); test_assert(0 == memcmp(&oldstatbuf, &newstatbuf, sizeof(struct stat)), NULL); /* Make sure contents match */ syscall_success(newfd = open("newchld", O_RDWR, 0)); syscall_success(ret = write(fd, TESTSTR, strlen(TESTSTR))); test_assert(ret == (int)strlen(TESTSTR), NULL); syscall_success(ret = read(newfd, buf, strlen(TESTSTR))); test_assert(ret == (int)strlen(TESTSTR), NULL); test_assert(0 == strncmp(buf, TESTSTR, strlen(TESTSTR)), "string is %.*s, expected %s", strlen(TESTSTR), buf, TESTSTR); syscall_success(close(fd)); syscall_success(close(newfd)); /* Remove one, make sure the other remains */ syscall_success(unlink("oldchld")); syscall_fail(mkdir("newchld", 0), EEXIST); syscall_success(link("newchld", "oldchld")); /* Link/unlink error cases */ syscall_fail(link("oldchld", "newchld"), EEXIST); syscall_fail(link("oldchld", LONGNAME), ENAMETOOLONG); syscall_fail(link("parent", "newchld"), EISDIR); /* only rename test */ /*syscall_success(rename("oldchld", "newchld"));*/ /* mmap/munmap tests */ syscall_success(fd = open("newchld", O_RDWR, 0)); test_assert(MAP_FAILED != (addr = mmap(0, strlen(TESTSTR), PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)), NULL); /* Check contents of memory */ test_assert(0 == memcmp(addr, TESTSTR, strlen(TESTSTR)), NULL); /* Write to it -> we shouldn't pagefault */ memcpy(addr, SHORTSTR, strlen(SHORTSTR)); test_assert(0 == memcmp(addr, SHORTSTR, strlen(SHORTSTR)), NULL); /* mmap the same thing on top of it, but shared */ test_assert(MAP_FAILED != mmap(addr, strlen(TESTSTR), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0), NULL); /* Make sure the old contents were restored (the mapping was private) */ test_assert(0 == memcmp(addr, TESTSTR, strlen(TESTSTR)), NULL); /* Now change the contents */ memcpy(addr, SHORTSTR, strlen(SHORTSTR)); /* mmap it on, private, on top again */ test_assert(MAP_FAILED != mmap(addr, strlen(TESTSTR), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, fd, 0), NULL); /* Make sure it changed */ test_assert(0 == memcmp(addr, SHORTSTR, strlen(SHORTSTR)), NULL); /* Fork and try changing things */ if (!fork()) { /* Child changes private mapping */ memcpy(addr, TESTSTR, strlen(TESTSTR)); exit(0); } /* Wait until child is done */ syscall_success(wait(0)); /* Make sure it's actually private */ test_assert(0 == memcmp(addr, SHORTSTR, strlen(SHORTSTR)), NULL); /* Unmap it */ syscall_success(munmap(addr, 2048)); /* mmap errors */ test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_PRIVATE, 12, 0), NULL); test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_PRIVATE, -1, 0), NULL); test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, 0, fd, 0), NULL); test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_FIXED, fd, 0), NULL); test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_FIXED | MAP_PRIVATE, fd, 0), NULL); test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_PRIVATE, fd, 0x12345), NULL); test_assert(MAP_FAILED == mmap((void *) 0x12345, 1024, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0), NULL); test_assert(MAP_FAILED == mmap(0, 0, PROT_READ, MAP_PRIVATE, fd, 0), NULL); test_assert(MAP_FAILED == mmap(0, -1, PROT_READ, MAP_PRIVATE, fd, 0), NULL); test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0), NULL); syscall_success(close(fd)); syscall_success(fd = open("newchld", O_RDONLY, 0)); test_assert(MAP_FAILED == mmap(0, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0), NULL); syscall_success(close(fd)); /* TODO ENODEV (mmap a terminal) EOVERFLOW (mmap SO MUCH of /dev/zero that fpointer would overflow) */ /* Also should test opening too many file descriptors somewhere */ /* munmap errors */ syscall_fail(munmap((void *) 0x12345, 15), EINVAL); syscall_fail(munmap(0x0, 15), EINVAL); syscall_fail(munmap(addr, 0), EINVAL); syscall_fail(munmap(addr, -1), EINVAL); /* brk tests */ /* Set the break, and use the memory in question */ test_assert((void *) - 1 != (addr = sbrk(128)), NULL); memcpy(addr, TESTSTR, 128); test_assert(0 == memcmp(addr, TESTSTR, 128), NULL); /* Make sure that the brk is being saved properly */ test_assert((void *)((unsigned long) addr + 128) == sbrk(0), NULL); /* Knock the break back down */ syscall_success(brk(addr)); /* brk errors */ syscall_fail(brk((void *)(&"brk")), ENOMEM); syscall_fail(brk((void *) 1), ENOMEM); syscall_fail(brk((void *) &addr), ENOMEM); syscall_success(chdir("..")); }
int main(int argc, char**argv) { void *heapA; void *pointers[TESTSIZE]; xbt_init(&argc,argv); XBT_INFO("Allocating a new heap"); heapA = xbt_mheap_new(-1, ((char*)sbrk(0)) + BUFFSIZE); if (heapA == NULL) { perror("attach 1 failed"); fprintf(stderr, "bye\n"); exit(1); } XBT_INFO("HeapA allocated"); int i, size; for (i = 0; i < TESTSIZE; i++) { size = size_of_block(i); pointers[i] = mmalloc(heapA, size); XBT_INFO("%d bytes allocated with offset %tx", size, ((char*)pointers[i])-((char*)heapA)); } XBT_INFO("All blocks were correctly allocated. Free every second block"); for (i = 0; i < TESTSIZE; i+=2) { size = size_of_block(i); mfree(heapA,pointers[i]); } XBT_INFO("Memset every second block to zero (yeah, they are not currently allocated :)"); for (i = 0; i < TESTSIZE; i+=2) { size = size_of_block(i); memset(pointers[i],0, size); } XBT_INFO("Re-allocate every second block"); for (i = 0; i < TESTSIZE; i+=2) { size = size_of_block(i); pointers[i] = mmalloc(heapA, size); } XBT_INFO("free all blocks (each one twice, to check that double free are correctly catched)"); for (i = 0; i < TESTSIZE; i++) { xbt_ex_t e; int gotit = 1; mfree(heapA, pointers[i]); TRY { mfree(heapA, pointers[i]); gotit = 0; } CATCH(e) { xbt_ex_free(e); } if (!gotit) xbt_die("FAIL: A double-free went undetected (for size:%d)",size_of_block(i)); } XBT_INFO("free again all blocks (to really check that double free are correctly catched)"); for (i = 0; i < TESTSIZE; i++) { xbt_ex_t e; int gotit = 1; TRY { mfree(heapA, pointers[i]); gotit = 0; } CATCH(e) { xbt_ex_free(e); } if (!gotit) xbt_die("FAIL: A double-free went undetected (for size:%d)",size_of_block(i)); } XBT_INFO("Damnit, I cannot break mmalloc this time. That's SO disappointing."); return 0; }
f_adr C_SBRK (f_int * n) { return (f_adr)sbrk(*n); }
f_adr c_sbrk_(f_int * n) { return (f_adr)sbrk(*n); }
int main (int argc, char **argv) { char *emulation; long start_time = get_run_time (); #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES) setlocale (LC_MESSAGES, ""); #endif #if defined (HAVE_SETLOCALE) setlocale (LC_CTYPE, ""); #endif bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); program_name = argv[0]; xmalloc_set_program_name (program_name); START_PROGRESS (program_name, 0); expandargv (&argc, &argv); bfd_init (); bfd_set_error_program_name (program_name); xatexit (remove_output); /* Set up the sysroot directory. */ ld_sysroot = get_sysroot (argc, argv); if (*ld_sysroot) { if (*TARGET_SYSTEM_ROOT == 0) { einfo ("%P%F: this linker was not configured to use sysroots\n"); ld_sysroot = ""; } else ld_canon_sysroot = lrealpath (ld_sysroot); } if (ld_canon_sysroot) ld_canon_sysroot_len = strlen (ld_canon_sysroot); else ld_canon_sysroot_len = -1; /* Set the default BFD target based on the configured target. Doing this permits the linker to be configured for a particular target, and linked against a shared BFD library which was configured for a different target. The macro TARGET is defined by Makefile. */ if (! bfd_set_default_target (TARGET)) { einfo (_("%X%P: can't set BFD default target to `%s': %E\n"), TARGET); xexit (1); } #if YYDEBUG { extern int yydebug; yydebug = 1; } #endif config.build_constructors = TRUE; config.rpath_separator = ':'; config.split_by_reloc = (unsigned) -1; config.split_by_file = (bfd_size_type) -1; config.make_executable = TRUE; config.magic_demand_paged = TRUE; config.text_read_only = TRUE; command_line.warn_mismatch = TRUE; command_line.warn_search_mismatch = TRUE; command_line.check_section_addresses = -1; command_line.disable_target_specific_optimizations = -1; /* We initialize DEMANGLING based on the environment variable COLLECT_NO_DEMANGLE. The gcc collect2 program will demangle the output of the linker, unless COLLECT_NO_DEMANGLE is set in the environment. Acting the same way here lets us provide the same interface by default. */ demangling = getenv ("COLLECT_NO_DEMANGLE") == NULL; link_info.allow_undefined_version = TRUE; link_info.keep_memory = TRUE; link_info.combreloc = TRUE; link_info.strip_discarded = TRUE; link_info.emit_hash = TRUE; link_info.callbacks = &link_callbacks; link_info.input_bfds_tail = &link_info.input_bfds; /* SVR4 linkers seem to set DT_INIT and DT_FINI based on magic _init and _fini symbols. We are compatible. */ link_info.init_function = "_init"; link_info.fini_function = "_fini"; link_info.relax_pass = 1; link_info.pei386_auto_import = -1; link_info.spare_dynamic_tags = 5; link_info.path_separator = ':'; ldfile_add_arch (""); emulation = get_emulation (argc, argv); ldemul_choose_mode (emulation); default_target = ldemul_choose_target (argc, argv); config.maxpagesize = bfd_emul_get_maxpagesize (default_target); config.commonpagesize = bfd_emul_get_commonpagesize (default_target); lang_init (); ldemul_before_parse (); lang_has_input_file = FALSE; parse_args (argc, argv); if (config.hash_table_size != 0) bfd_hash_set_default_size (config.hash_table_size); ldemul_set_symbols (); if (link_info.relocatable) { if (command_line.check_section_addresses < 0) command_line.check_section_addresses = 0; if (link_info.shared) einfo (_("%P%F: -r and -shared may not be used together\n")); } /* We may have -Bsymbolic, -Bsymbolic-functions, --dynamic-list-data, --dynamic-list-cpp-new, --dynamic-list-cpp-typeinfo and --dynamic-list FILE. -Bsymbolic and -Bsymbolic-functions are for shared libraries. -Bsymbolic overrides all others and vice versa. */ switch (command_line.symbolic) { case symbolic_unset: break; case symbolic: /* -Bsymbolic is for shared library only. */ if (link_info.shared) { link_info.symbolic = TRUE; /* Should we free the unused memory? */ link_info.dynamic_list = NULL; command_line.dynamic_list = dynamic_list_unset; } break; case symbolic_functions: /* -Bsymbolic-functions is for shared library only. */ if (link_info.shared) command_line.dynamic_list = dynamic_list_data; break; } switch (command_line.dynamic_list) { case dynamic_list_unset: break; case dynamic_list_data: link_info.dynamic_data = TRUE; case dynamic_list: link_info.dynamic = TRUE; break; } if (! link_info.shared) { if (command_line.filter_shlib) einfo (_("%P%F: -F may not be used without -shared\n")); if (command_line.auxiliary_filters) einfo (_("%P%F: -f may not be used without -shared\n")); } if (! link_info.shared || link_info.pie) link_info.executable = TRUE; /* Treat ld -r -s as ld -r -S -x (i.e., strip all local symbols). I don't see how else this can be handled, since in this case we must preserve all externally visible symbols. */ if (link_info.relocatable && link_info.strip == strip_all) { link_info.strip = strip_debugger; if (link_info.discard == discard_sec_merge) link_info.discard = discard_all; } /* If we have not already opened and parsed a linker script, try the default script from command line first. */ if (saved_script_handle == NULL && command_line.default_script != NULL) { ldfile_open_command_file (command_line.default_script); parser_input = input_script; yyparse (); } /* If we have not already opened and parsed a linker script read the emulation's appropriate default script. */ if (saved_script_handle == NULL) { int isfile; char *s = ldemul_get_script (&isfile); if (isfile) ldfile_open_default_command_file (s); else { lex_string = s; lex_redirect (s); } parser_input = input_script; yyparse (); lex_string = NULL; } if (trace_file_tries) { if (saved_script_handle) info_msg (_("using external linker script:")); else info_msg (_("using internal linker script:")); info_msg ("\n==================================================\n"); if (saved_script_handle) { static const int ld_bufsz = 8193; size_t n; char *buf = (char *) xmalloc (ld_bufsz); rewind (saved_script_handle); while ((n = fread (buf, 1, ld_bufsz - 1, saved_script_handle)) > 0) { buf[n] = 0; info_msg (buf); } rewind (saved_script_handle); free (buf); } else { int isfile; info_msg (ldemul_get_script (&isfile)); } info_msg ("\n==================================================\n"); } lang_final (); if (!lang_has_input_file) { if (version_printed) xexit (0); einfo (_("%P%F: no input files\n")); } if (trace_files) info_msg (_("%P: mode %s\n"), emulation); ldemul_after_parse (); if (config.map_filename) { if (strcmp (config.map_filename, "-") == 0) { config.map_file = stdout; } else { config.map_file = fopen (config.map_filename, FOPEN_WT); if (config.map_file == (FILE *) NULL) { bfd_set_error (bfd_error_system_call); einfo (_("%P%F: cannot open map file %s: %E\n"), config.map_filename); } } } lang_process (); /* Print error messages for any missing symbols, for any warning symbols, and possibly multiple definitions. */ if (link_info.relocatable) link_info.output_bfd->flags &= ~EXEC_P; else link_info.output_bfd->flags |= EXEC_P; ldwrite (); if (config.map_file != NULL) lang_map (); if (command_line.cref) output_cref (config.map_file != NULL ? config.map_file : stdout); if (nocrossref_list != NULL) check_nocrossrefs (); lang_finish (); /* Even if we're producing relocatable output, some non-fatal errors should be reported in the exit status. (What non-fatal errors, if any, do we want to ignore for relocatable output?) */ if (!config.make_executable && !force_make_executable) { if (trace_files) einfo (_("%P: link errors found, deleting executable `%s'\n"), output_filename); /* The file will be removed by remove_output. */ xexit (1); } else { if (! bfd_close (link_info.output_bfd)) einfo (_("%F%B: final close failed: %E\n"), link_info.output_bfd); /* If the --force-exe-suffix is enabled, and we're making an executable file and it doesn't end in .exe, copy it to one which does. */ if (! link_info.relocatable && command_line.force_exe_suffix) { int len = strlen (output_filename); if (len < 4 || (strcasecmp (output_filename + len - 4, ".exe") != 0 && strcasecmp (output_filename + len - 4, ".dll") != 0)) { FILE *src; FILE *dst; const int bsize = 4096; char *buf = (char *) xmalloc (bsize); int l; char *dst_name = (char *) xmalloc (len + 5); strcpy (dst_name, output_filename); strcat (dst_name, ".exe"); src = fopen (output_filename, FOPEN_RB); dst = fopen (dst_name, FOPEN_WB); if (!src) einfo (_("%X%P: unable to open for source of copy `%s'\n"), output_filename); if (!dst) einfo (_("%X%P: unable to open for destination of copy `%s'\n"), dst_name); while ((l = fread (buf, 1, bsize, src)) > 0) { int done = fwrite (buf, 1, l, dst); if (done != l) einfo (_("%P: Error writing file `%s'\n"), dst_name); } fclose (src); if (fclose (dst) == EOF) einfo (_("%P: Error closing file `%s'\n"), dst_name); free (dst_name); free (buf); } } } END_PROGRESS (program_name); if (config.stats) { #ifdef HAVE_SBRK char *lim = (char *) sbrk (0); #endif long run_time = get_run_time () - start_time; fprintf (stderr, _("%s: total time in link: %ld.%06ld\n"), program_name, run_time / 1000000, run_time % 1000000); #ifdef HAVE_SBRK fprintf (stderr, _("%s: data size %ld\n"), program_name, (long) (lim - (char *) &environ)); #endif } /* Prevent remove_output from doing anything, after a successful link. */ output_filename = NULL; xexit (0); return 0; }
static uintptr_t get_rusage_data_via_setrlimit (void) { uintptr_t result; struct rlimit orig_limit; # ifdef __hpux /* On HP-UX 11.00, setrlimit() RLIMIT_DATA of does not work: It cannot restore the previous limits. On HP-UX 11.11, setrlimit() RLIMIT_DATA of does not work: It sometimes has no effect on the next sbrk() call. */ { struct utsname buf; if (uname (&buf) == 0 && strlen (buf.release) >= 5 && (strcmp (buf.release + strlen (buf.release) - 5, "11.00") == 0 || strcmp (buf.release + strlen (buf.release) - 5, "11.11") == 0)) return 0; } # endif /* Record the original limit. */ if (getrlimit (RLIMIT_DATA, &orig_limit) < 0) return 0; if (orig_limit.rlim_max != RLIM_INFINITY && (orig_limit.rlim_cur == RLIM_INFINITY || orig_limit.rlim_cur > orig_limit.rlim_max)) /* We may not be able to restore the current rlim_cur value. So bail out. */ return 0; { /* The granularity is a single page. */ const intptr_t pagesize = getpagesize (); uintptr_t low_bound = 0; uintptr_t high_bound; for (;;) { /* Here we know that the data segment size is >= low_bound. */ struct rlimit try_limit; uintptr_t try_next = 2 * low_bound + pagesize; if (try_next < low_bound) /* Overflow. */ try_next = ((uintptr_t) (~ 0) / pagesize) * pagesize; /* There's no point in trying a value > orig_limit.rlim_max, as setrlimit would fail anyway. */ if (orig_limit.rlim_max != RLIM_INFINITY && orig_limit.rlim_max < try_next) try_next = orig_limit.rlim_max; /* Avoid endless loop. */ if (try_next == low_bound) { /* try_next could not be increased. */ result = low_bound; goto done; } try_limit.rlim_max = orig_limit.rlim_max; try_limit.rlim_cur = try_next; if (setrlimit (RLIMIT_DATA, &try_limit) == 0) { /* Allocate a page of memory, to compare the current data segment size with try_limit.rlim_cur. */ void *new_page = sbrk (pagesize); if (new_page != (void *)(-1)) { /* The page could be added successfully. Free it. */ sbrk (- pagesize); /* We know that the data segment size is < try_limit.rlim_cur. */ high_bound = try_next; break; } else { /* We know that the data segment size is >= try_limit.rlim_cur. */ low_bound = try_next; } } else { /* Here we expect only EINVAL or (on AIX) EFAULT, not EPERM. */ if (! errno_expected ()) abort (); /* We know that the data segment size is >= try_limit.rlim_cur. */ low_bound = try_next; } } /* Here we know that the data segment size is >= low_bound and < high_bound. */ while (high_bound - low_bound > pagesize) { struct rlimit try_limit; uintptr_t try_next = low_bound + (((high_bound - low_bound) / 2) / pagesize) * pagesize; /* Here low_bound <= try_next < high_bound. */ try_limit.rlim_max = orig_limit.rlim_max; try_limit.rlim_cur = try_next; if (setrlimit (RLIMIT_DATA, &try_limit) == 0) { /* Allocate a page of memory, to compare the current data segment size with try_limit.rlim_cur. */ void *new_page = sbrk (pagesize); if (new_page != (void *)(-1)) { /* The page could be added successfully. Free it. */ sbrk (- pagesize); /* We know that the data segment size is < try_limit.rlim_cur. */ high_bound = try_next; } else { /* We know that the data segment size is >= try_limit.rlim_cur. */ low_bound = try_next; } } else { /* Here we expect only EINVAL or (on AIX) EFAULT, not EPERM. */ if (! errno_expected ()) abort (); /* We know that the data segment size is >= try_limit.rlim_cur. */ low_bound = try_next; } } result = low_bound; } done: /* Restore the original rlim_cur value. */ if (setrlimit (RLIMIT_DATA, &orig_limit) < 0) abort (); return result; }
void* mysbrk(uint32_t size) { return sbrk(size); }
int check_mem_leak(char *where) { void *addr; addr = sbrk(0); printf("\tsbrk(0) %s: addr = %u\n", where, addr); }
int main(int argc, char **argv) { printf("\n*** Testing netcdf-4 file functions, some more.\n"); last_sbrk = sbrk(0); /* printf("Test for memory consumption of simple HDF5 file read...\n"); */ /* { */ /* #define NUM_TRIES 200000 */ /* #define CHUNK_CACHE_NELEMS_1 1009 */ /* #define CHUNK_CACHE_SIZE_1 1000000 */ /* #define CHUNK_CACHE_PREEMPTION_1 .75 */ /* #define MAX_OBJ 2 */ /* #define FILE_NAME2 "ref_tst_kirk.nc" */ /* int mem_used, mem_used1, mem_used2; */ /* hid_t fapl_id, fileid, grpid, datasetid; */ /* int try; */ /* int num_scales; */ /* printf("\t\t\tbef_open\taft_open\taft_close\tused_open\tused_closed\n"); */ /* for (try = 0; try < NUM_TRIES; try++) */ /* { */ /* char obj_name2[] = "Captain_Kirk"; */ /* get_mem_used2(&mem_used); */ /* /\* Reopen the file. *\/ */ /* if ((fapl_id = H5Pcreate(H5P_FILE_ACCESS)) < 0) ERR; */ /* if ((fileid = H5Fopen(FILE_NAME2, H5F_ACC_RDONLY, H5P_DEFAULT)) < 0) ERR; */ /* if ((grpid = H5Gopen(fileid, "/")) < 0) ERR; */ /* if ((datasetid = H5Dopen2(grpid, obj_name2, H5P_DEFAULT)) < 0) ERR; */ /* num_scales = H5DSget_num_scales(datasetid, 0); */ /* get_mem_used2(&mem_used1); */ /* /\* Close everything. *\/ */ /* if (H5Dclose(datasetid)) ERR_RET; */ /* if (H5Pclose(fapl_id)) ERR_RET; */ /* if (H5Gclose(grpid) < 0) ERR_RET; */ /* if (H5Fclose(fileid) < 0) ERR_RET; */ /* get_mem_used2(&mem_used2); */ /* if (mem_used2 - mem_used) */ /* { */ /* printf("try %d - \t\t%d\t\t%d\t\t%d\t\t%d\t\t%d \n", try, */ /* mem_used, mem_used1, mem_used2, mem_used1 - mem_used, */ /* mem_used2 - mem_used); */ /* /\*if (try > 1) */ /* ERR_RET;*\/ */ /* } */ /* } */ /* } */ /* SUMMARIZE_ERR; */ /* printf("Test for memory consumption of HDF5 file read...\n"); */ /* { */ /* #define NUM_TRIES 2000 */ /* #define CHUNK_CACHE_NELEMS_1 1009 */ /* #define CHUNK_CACHE_SIZE_1 1000000 */ /* #define CHUNK_CACHE_PREEMPTION_1 .75 */ /* #define MAX_OBJ 2 */ /* #define FILE_NAME2 "ref_tst_kirk.nc" */ /* hsize_t num_obj, i; */ /* int mem_used, mem_used1, mem_used2; */ /* hid_t fapl_id, fileid, grpid, datasetid[MAX_OBJ]; */ /* hid_t access_pid, spaceid; */ /* char obj_name[NC_MAX_NAME + 1]; */ /* int try; */ /* H5O_info_t obj_info; */ /* H5_index_t idx_field = H5_INDEX_CRT_ORDER; */ /* ssize_t size; */ /* int ndims; */ /* hsize_t dims[NC_MAX_DIMS], max_dims[NC_MAX_DIMS]; */ /* int is_scale = 0; */ /* get_mem_used2(&mem_used); */ /* mem_used1 = mem_used; */ /* mem_used2 = mem_used; */ /* printf("start: memuse= %d\t%d\t%d \n",mem_used, mem_used1, */ /* mem_used2); */ /* /\* if (H5Eset_auto(NULL, NULL) < 0) ERR;*\/ */ /* printf("bef_open\taft_open\taft_close\tused_open\tused_closed\n"); */ /* for (try = 0; try < NUM_TRIES; try++) */ /* { */ /* get_mem_used2(&mem_used); */ /* /\* Reopen the file. *\/ */ /* if ((fapl_id = H5Pcreate(H5P_FILE_ACCESS)) < 0) ERR; */ /* if (H5Pset_fclose_degree(fapl_id, H5F_CLOSE_SEMI)) ERR; */ /* if (H5Pset_cache(fapl_id, 0, CHUNK_CACHE_NELEMS_1, CHUNK_CACHE_SIZE_1, */ /* CHUNK_CACHE_PREEMPTION_1) < 0) ERR; */ /* if (H5Pset_libver_bounds(fapl_id, H5F_LIBVER_LATEST, */ /* H5F_LIBVER_LATEST) < 0) ERR; */ /* if ((fileid = H5Fopen(FILE_NAME2, H5F_ACC_RDONLY, fapl_id)) < 0) ERR; */ /* if ((grpid = H5Gopen(fileid, "/")) < 0) ERR; */ /* if (H5Gget_num_objs(grpid, &num_obj) < 0) ERR; */ /* if (num_obj > MAX_OBJ) ERR; */ /* for (i = 0; i < num_obj; i++) */ /* { */ /* if (H5Oget_info_by_idx(grpid, ".", H5_INDEX_CRT_ORDER, H5_ITER_INC, */ /* i, &obj_info, H5P_DEFAULT) < 0) ERR; */ /* if ((size = H5Lget_name_by_idx(grpid, ".", idx_field, H5_ITER_INC, i, */ /* NULL, 0, H5P_DEFAULT)) < 0) ERR; */ /* if (H5Lget_name_by_idx(grpid, ".", idx_field, H5_ITER_INC, i, */ /* obj_name, size+1, H5P_DEFAULT) < 0) ERR; */ /* if ((datasetid[i] = H5Dopen2(grpid, obj_name, H5P_DEFAULT)) < 0) ERR; */ /* if ((access_pid = H5Dget_access_plist(datasetid[i])) < 0) ERR; */ /* if ((spaceid = H5Dget_space(datasetid[i])) < 0) ERR; */ /* if ((ndims = H5Sget_simple_extent_ndims(spaceid)) < 0) ERR; */ /* if (H5Sget_simple_extent_dims(spaceid, dims, max_dims) < 0) ERR; */ /* if ((is_scale = H5DSis_scale(datasetid[i])) < 0) ERR; */ /* if (is_scale) */ /* { */ /* char dimscale_name_att[NC_MAX_NAME + 1]; */ /* int natts, a; */ /* hid_t attid = 0; */ /* char att_name[NC_MAX_HDF5_NAME + 1]; */ /* if ((natts = H5Aget_num_attrs(datasetid[i])) < 0) ERR; */ /* for (a = 0; a < natts; a++) */ /* { */ /* if ((attid = H5Aopen_idx(datasetid[i], (unsigned int)a)) < 0) ERR; */ /* if (H5Aget_name(attid, NC_MAX_HDF5_NAME, att_name) < 0) ERR; */ /* if (H5Aclose(attid) < 0) ERR; */ /* } */ /* if (H5DSget_scale_name(datasetid[i], dimscale_name_att, NC_MAX_NAME) < 0) ERR; */ /* } */ /* else */ /* { */ /* int num_scales; */ /* size_t chunk_cache_size, chunk_cache_nelems; */ /* double rdcc_w0; */ /* hid_t propid; */ /* num_scales = H5DSget_num_scales(datasetid[i], 0); */ /* if ((H5Pget_chunk_cache(access_pid, &chunk_cache_nelems, */ /* &chunk_cache_size, &rdcc_w0)) < 0) ERR; */ /* if ((propid = H5Dget_create_plist(datasetid[i])) < 0) ERR; */ /* if (H5Pclose(propid)) ERR; */ /* } */ /* if (H5Pclose(access_pid)) ERR; */ /* if (H5Sclose(spaceid)) ERR; */ /* } */ /* get_mem_used2(&mem_used1); */ /* /\* Close everything. *\/ */ /* for (i = 0; i < num_obj; i++) */ /* if (H5Dclose(datasetid[i])) ERR; */ /* if (H5Pclose(fapl_id)) ERR; */ /* if (H5Gclose(grpid) < 0) ERR; */ /* if (H5Fclose(fileid) < 0) ERR; */ /* get_mem_used2(&mem_used2); */ /* if (mem_used2 - mem_used) */ /* { */ /* printf("try %d - %d\t\t%d\t\t%d\t\t%d\t\t%d \n", try, */ /* mem_used, mem_used1, mem_used2, mem_used1 - mem_used, */ /* mem_used2 - mem_used); */ /* if (try > 1) */ /* ERR_RET; */ /* } */ /* } */ /* } */ /* SUMMARIZE_ERR; */ FINAL_RESULTS; }
void simple_allocator_init(){ heap_start_address = sbrk(0); heap_len = 0; }
int main( int argc, char *argv[]) { char *id = "main"; struct hostent *hp; int go, c, errflg = 0; int lockfds; int t = 1; pid_t pid; char host[100]; char *homedir = PBS_SERVER_HOME; unsigned int port; char *dbfile = "sched_out"; struct sigaction act; sigset_t oldsigs; caddr_t curr_brk = 0; caddr_t next_brk; extern char *optarg; extern int optind, opterr; extern int rpp_fd; fd_set fdset; int schedinit(int argc, char **argv); int schedule(int com, int connector); glob_argv = argv; alarm_time = 180; /* The following is code to reduce security risks */ /* move this to a place where nss_ldap doesn't hold a socket yet */ c = sysconf(_SC_OPEN_MAX); while (--c > 2) (void)close(c); /* close any file desc left open by parent */ port = get_svrport(PBS_SCHEDULER_SERVICE_NAME, "tcp", PBS_SCHEDULER_SERVICE_PORT); pbs_rm_port = get_svrport(PBS_MANAGER_SERVICE_NAME, "tcp", PBS_MANAGER_SERVICE_PORT); strcpy(pbs_current_user, "Scheduler"); msg_daemonname = strdup("pbs_sched"); opterr = 0; while ((c = getopt(argc, argv, "L:S:R:d:p:c:a:-:")) != EOF) { switch (c) { case '-': if ((optarg == NULL) || (optarg[0] == '\0')) { errflg = 1; } if (!strcmp(optarg, "version")) { fprintf(stderr, "version: %s\n", PACKAGE_VERSION); exit(0); } else { errflg = 1; } break; case 'L': logfile = optarg; break; case 'S': port = atoi(optarg); if (port == 0) { fprintf(stderr, "%s: illegal port\n", optarg); errflg = 1; } break; case 'R': if ((pbs_rm_port = atoi(optarg)) == 0) { (void)fprintf(stderr, "%s: bad -R %s\n", argv[0], optarg); return 1; } break; case 'd': homedir = optarg; break; case 'p': dbfile = optarg; break; case 'c': configfile = optarg; break; case 'a': alarm_time = atoi(optarg); if (alarm_time == 0) { fprintf(stderr, "%s: bad alarm time\n", optarg); errflg = 1; } break; case '?': errflg = 1; break; } } if (errflg) { fprintf(stderr, "usage: %s %s\n", argv[0], usage); exit(1); } #ifndef DEBUG if (IamRoot() == 0) { return (1); } #endif /* DEBUG */ /* Save the original working directory for "restart" */ if ((oldpath = getcwd((char *)NULL, MAXPATHLEN)) == NULL) { fprintf(stderr, "cannot get current working directory\n"); exit(1); } (void)sprintf(log_buffer, "%s/sched_priv", homedir); #if !defined(DEBUG) && !defined(NO_SECURITY_CHECK) c = chk_file_sec(log_buffer, 1, 0, S_IWGRP | S_IWOTH, 1, NULL); c |= chk_file_sec(PBS_ENVIRON, 0, 0, S_IWGRP | S_IWOTH, 0, NULL); if (c != 0) exit(1); #endif /* not DEBUG and not NO_SECURITY_CHECK */ if (chdir(log_buffer) == -1) { perror("chdir"); exit(1); } (void)sprintf(path_log, "%s/sched_logs", homedir); (void)sprintf(path_acct, "%s/%s", log_buffer, PBS_ACCT); /* The following is code to reduce security risks */ /* start out with standard umask, system resource limit infinite */ umask(022); if (setup_env(PBS_ENVIRON) == -1) exit(1); c = getgid(); (void)setgroups(1, (gid_t *)&c); /* secure suppl. groups */ #ifndef DEBUG #ifdef _CRAY (void)limit(C_JOB, 0, L_CPROC, 0); (void)limit(C_JOB, 0, L_CPU, 0); (void)limit(C_JOBPROCS, 0, L_CPU, 0); (void)limit(C_PROC, 0, L_FD, 255); (void)limit(C_JOB, 0, L_FSBLK, 0); (void)limit(C_JOBPROCS, 0, L_FSBLK, 0); (void)limit(C_JOB, 0, L_MEM , 0); (void)limit(C_JOBPROCS, 0, L_MEM , 0); #else /* not _CRAY */ { struct rlimit rlimit; rlimit.rlim_cur = RLIM_INFINITY; rlimit.rlim_max = RLIM_INFINITY; (void)setrlimit(RLIMIT_CPU, &rlimit); (void)setrlimit(RLIMIT_FSIZE, &rlimit); (void)setrlimit(RLIMIT_DATA, &rlimit); (void)setrlimit(RLIMIT_STACK, &rlimit); #ifdef RLIMIT_RSS (void)setrlimit(RLIMIT_RSS , &rlimit); #endif /* RLIMIT_RSS */ #ifdef RLIMIT_VMEM (void)setrlimit(RLIMIT_VMEM , &rlimit); #endif /* RLIMIT_VMEM */ } #endif /* not _CRAY */ #endif /* DEBUG */ if (log_open(logfile, path_log) == -1) { fprintf(stderr, "%s: logfile could not be opened\n", argv[0]); exit(1); } if (gethostname(host, sizeof(host)) == -1) { log_err(errno, id, "gethostname"); die(0); } if ((hp = gethostbyname(host)) == NULL) { log_err(errno, id, "gethostbyname"); die(0); } if ((server_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { log_err(errno, id, "socket"); die(0); } if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&t, sizeof(t)) == -1) { log_err(errno, id, "setsockopt"); die(0); } saddr.sin_family = AF_INET; saddr.sin_port = htons(port); memcpy(&saddr.sin_addr, hp->h_addr, hp->h_length); if (bind(server_sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) { log_err(errno, id, "bind"); die(0); } if (listen(server_sock, 5) < 0) { log_err(errno, id, "listen"); die(0); } okclients = (pbs_net_t *)calloc(START_CLIENTS, sizeof(pbs_net_t)); addclient("localhost"); /* who has permission to call MOM */ addclient(host); if (configfile) { if (read_config(configfile) != 0) die(0); } lockfds = open("sched.lock", O_CREAT | O_TRUNC | O_WRONLY, 0644); if (lockfds < 0) { log_err(errno, id, "open lock file"); exit(1); } lock_out(lockfds, F_WRLCK); fullresp(0); if (sigemptyset(&allsigs) == -1) { perror("sigemptyset"); exit(1); } if (sigprocmask(SIG_SETMASK, &allsigs, NULL) == -1) /* unblock */ { perror("sigprocmask"); exit(1); } act.sa_flags = 0; sigaddset(&allsigs, SIGHUP); /* remember to block these */ sigaddset(&allsigs, SIGINT); /* during critical sections */ sigaddset(&allsigs, SIGTERM); /* so we don't get confused */ act.sa_mask = allsigs; act.sa_handler = restart; /* do a restart on SIGHUP */ sigaction(SIGHUP, &act, NULL); act.sa_handler = toolong; /* handle an alarm call */ sigaction(SIGALRM, &act, NULL); act.sa_handler = die; /* bite the biscuit for all following */ sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); /* * Catch these signals to ensure we core dump even if * our rlimit for core dumps is set to 0 initially. * * Chris Samuel - VPAC * [email protected] - 29th July 2003 * * Now conditional on the PBSCOREDUMP environment variable */ if (getenv("PBSCOREDUMP")) { act.sa_handler = catch_abort; /* make sure we core dump */ sigaction(SIGSEGV, &act, NULL); sigaction(SIGBUS, &act, NULL); sigaction(SIGFPE, &act, NULL); sigaction(SIGILL, &act, NULL); sigaction(SIGTRAP, &act, NULL); sigaction(SIGSYS, &act, NULL); } /* * Local initialization stuff */ if (schedinit(argc, argv)) { (void) sprintf(log_buffer, "local initialization failed, terminating"); log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer); exit(1); } if (getenv("PBSDEBUG") == NULL) { lock_out(lockfds, F_UNLCK); #ifdef DISABLE_DAEMONS pid = getpid(); #else if ((pid = fork()) == -1) { /* error on fork */ perror("fork"); exit(1); } else if (pid > 0) /* parent exits */ { exit(0); } if ((pid = setsid()) == -1) { perror("setsid"); exit(1); } #endif /* DISABLE_DAEMONS */ lock_out(lockfds, F_WRLCK); if (freopen(dbfile, "a", stdout) == NULL) { perror("opening lockfile"); exit(1); } setvbuf(stdout, NULL, _IOLBF, 0); dup2(fileno(stdout), fileno(stderr)); } else { setvbuf(stdout, NULL, _IOLBF, 0); setvbuf(stderr, NULL, _IOLBF, 0); pid = getpid(); } if (freopen("/dev/null", "r", stdin) == NULL) { perror("opening /dev/null"); exit(1); } /* write scheduler's pid into lockfile */ (void)sprintf(log_buffer, "%ld\n", (long)pid); if (write(lockfds, log_buffer, strlen(log_buffer) + 1) != (ssize_t)(strlen(log_buffer) + 1)) { perror("writing to lockfile"); exit(1); } #if (PLOCK_DAEMONS & 2) (void)plock(PROCLOCK); /* lock daemon into memory */ #endif sprintf(log_buffer, "%s startup pid %ld", argv[0], (long)pid); log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer); FD_ZERO(&fdset); for (go = 1;go;) { int cmd; if (rpp_fd != -1) FD_SET(rpp_fd, &fdset); FD_SET(server_sock, &fdset); if (select(FD_SETSIZE, &fdset, NULL, NULL, NULL) == -1) { if (errno != EINTR) { log_err(errno, id, "select"); die(0); } continue; } if (rpp_fd != -1 && FD_ISSET(rpp_fd, &fdset)) { if (rpp_io() == -1) log_err(errno, id, "rpp_io"); } if (!FD_ISSET(server_sock, &fdset)) continue; cmd = server_command(); if (sigprocmask(SIG_BLOCK, &allsigs, &oldsigs) == -1) log_err(errno, id, "sigprocmaskSIG_BLOCK)"); alarm(alarm_time); if (schedule(cmd, connector)) /* magic happens here */ go = 0; alarm(0); if (connector >= 0 && server_disconnect(connector)) { log_err(errno, id, "server_disconnect"); die(0); } next_brk = (caddr_t)sbrk(0); if (next_brk > curr_brk) { sprintf(log_buffer, "brk point %ld", (long)next_brk); log_record(PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER, id, log_buffer); curr_brk = next_brk; } if (sigprocmask(SIG_SETMASK, &oldsigs, NULL) == -1) log_err(errno, id, "sigprocmask(SIG_SETMASK)"); } sprintf(log_buffer, "%s normal finish pid %ld", argv[0], (long)pid); log_record(PBSEVENT_SYSTEM, PBS_EVENTCLASS_SERVER, id, log_buffer); close(server_sock); exit(0); } /* END main() */
/* * implementation of malloc */ void* sf_malloc(size_t size){ unsigned long long int header = 0x0000000000000000; unsigned long long int free_block_info=0x0000000000000000; if(size > FOUR_GB){ errno=ENOMEM; return NULL; } else { if(free_header==NULL){ printf("first\n"); /*free header null*/ if(size>INIT_MEM){ printf("size>init\n"); int result= size/INIT_MEM; int mod=size%INIT_MEM; if(mod != 0){ result=result+1; INIT_MEM=INIT_MEM*result; ptr_1=sbrk(INIT_MEM); sbrk_counter= sbrk_counter +INIT_MEM; ptr_2=sbrk(0); } else{ INIT_MEM=INIT_MEM*result; ptr_1=sbrk(INIT_MEM); sbrk_counter= sbrk_counter +INIT_MEM; ptr_2=sbrk(0); } } ptr_1=sbrk(INIT_MEM); /*pointer 1 point at the begining of the heap*/ sbrk_counter= sbrk_counter +INIT_MEM; ptr_2=sbrk(0);/*the pointer 2 point at the end addr*/ /*padding*/ /*free header null*/ }else{ ptr_1=free_header; printf("not first\n"); if(size>remain_size){ printf("size>remain\n"); int result= size/INIT_MEM; int mod=size%INIT_MEM; if(mod != 0){ result=result+1; INIT_MEM=INIT_MEM*result; sbrk(INIT_MEM); sbrk_counter= sbrk_counter +INIT_MEM; } else{ INIT_MEM=INIT_MEM*result; sbrk(INIT_MEM); sbrk_counter= sbrk_counter +INIT_MEM; } } } buff=ptr_1+size; /*move buff to the end of block*/ unsigned long addr = (unsigned long) buff; if(addr%16!=0){ unsigned long long int small_size=size; if(size<8){ small_size=size+8; } unsigned long long int size_result= small_size/8; unsigned long long int size_mod =small_size%8; if(size_mod!=0){ ac_size = 8*(size_result+1); } else{ ac_size=size_result*8; } // unsigned long long int ac_size=size+8; header=header|a; unsigned long long int m_size= size<<32; header=header|m_size; unsigned long long int b_size =16+ac_size; unsigned long long int b_size1=b_size<<3; header = header|b_size1; unsigned long long int *assign_header =(unsigned long long int *)ptr_1 ; unsigned long long int *assign_footer =(unsigned long long int *)buff; *assign_header = header; *assign_footer = header; printf("%016llx\n",*assign_header); /*assign free block header, footer, next and prev*/ free_header=buff+8;/*header */ remain_size= INIT_MEM-b_size; unsigned long long int shif_remain=remain_size<<3; free_block_info=free_block_info|shif_remain; unsigned long long int *assign_freeh =(unsigned long long int *)free_header ; unsigned long long int *assign_freef =(unsigned long long int *)ptr_2 ; *assign_freeh = free_block_info; *assign_freef = free_block_info; size_total=size_total+b_size; // void *next = free_header+8; // void *prev = free_header+16; } else{ header=header|a; unsigned long long int m_size=size<<32; header=header|m_size; unsigned long long int b_size =16+size; unsigned long long int b_size2=b_size<<3; header = header|b_size2; unsigned long long int *assign_header =(unsigned long long int *)ptr_1 ; unsigned long long int *assign_footer =(unsigned long long int *)buff ; *assign_header = header; *assign_footer = header; printf("%016llx\n",*assign_header); /*assign free block header, footer, next and prev*/ remain_size= INIT_MEM-b_size; unsigned long long int shif_remain=remain_size<<3; free_block_info=free_block_info|shif_remain; free_header=buff; unsigned long long int *assign_freeh =(unsigned long long int *)free_header; unsigned long long int *assign_freef =(unsigned long long int *)ptr_2 ; *assign_freeh = free_block_info; *assign_freef = free_block_info; size_total=size_total+b_size; // void *next = free_header+8; //void *prev = free_header+16; } return ptr_1+8; } }
static struct block *block_alloc(size_t size) { struct block *block; u8_t *dataptr, *p, *ptr; unsigned page_index, page_index_max; size_t sizerem, totalsize; u64_t tsc; LOG(("block_alloc; size=0x%x\n", size)); assert(size > 0); /* round size up to machine word size */ sizerem = size % sizeof(long); if (sizerem) size += sizeof(long) - sizerem; /* initialize address range */ if (!ptr_min && !ptr_max) { /* keep a safe distance from areas that are in use: * - 4MB from the break (should not change if traditional * malloc is not used so a small margin is sufficient * - 256MB from the stack (big margin because memory beyond * this may be allocated by mmap when the address space * starts to fill up) */ ptr_min = page_round_up_ptr((u8_t *) sbrk(0) + 0x400000); ptr_max = page_round_down_ptr((u8_t *) &size - 0x10000000); } assert(ptr_min); assert(ptr_max); assert(ptr_min < ptr_max); /* select address at random */ read_tsc_64(&tsc); totalsize = block_get_totalsize(size); page_index_max = (ptr_max - ptr_min - totalsize) / PAGE_SIZE; page_index = (page_index_max > 0) ? (tsc.lo % page_index_max) : 0; ptr = ptr_min + page_index * PAGE_SIZE; /* allocate block */ block = (struct block *) mmap( ptr, /* addr */ totalsize, /* len */ PROT_READ|PROT_WRITE, /* prot */ MAP_PREALLOC, /* flags */ -1, /* fd */ 0); /* offset */ if (block == MAP_FAILED) { /* mmap call failed */ abort(); } /* block may not be at the requested location if that is in use */ if (ptr_min > (u8_t *) block) ptr_min = (u8_t *) block; if (ptr_max < (u8_t *) block) ptr_max = (u8_t *) block; /* initialize block, including fillers */ block->size = size; block->magic = block_compute_magic(block); dataptr = block_get_dataptr(block); for (p = (u8_t *) (block + 1); p < dataptr; p++) *p = ((unsigned long) p & 0xff); LOG(("block_alloc; block=0x%x\n", block)); return block; }
/** * @brief change data segment size * * @param incr change of the location of the program break, * which defines the end of the process's data segment * * @return On success,returns zero. * On error, -1 is returned, and errno is set. */ caddr_t _sbrk(int incr) { return sbrk(incr); }
void print_resource_track(e2fsck_t ctx, const char *desc, struct resource_track *track, io_channel channel) { #ifdef HAVE_GETRUSAGE struct rusage r; #endif #ifdef HAVE_MALLINFO struct mallinfo malloc_info; #endif struct timeval time_end; if ((desc && !(ctx->options & E2F_OPT_TIME2)) || (!desc && !(ctx->options & E2F_OPT_TIME))) return; e2fsck_clear_progbar(ctx); gettimeofday(&time_end, 0); if (desc) log_out(ctx, "%s: ", desc); #ifdef HAVE_MALLINFO #define kbytes(x) (((unsigned long)(x) + 1023) / 1024) malloc_info = mallinfo(); log_out(ctx, _("Memory used: %luk/%luk (%luk/%luk), "), kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd), kbytes(malloc_info.uordblks), kbytes(malloc_info.fordblks)); #else log_out(ctx, _("Memory used: %lu, "), (unsigned long) (((char *) sbrk(0)) - ((char *) track->brk_start))); #endif #ifdef HAVE_GETRUSAGE getrusage(RUSAGE_SELF, &r); log_out(ctx, _("time: %5.2f/%5.2f/%5.2f\n"), timeval_subtract(&time_end, &track->time_start), timeval_subtract(&r.ru_utime, &track->user_start), timeval_subtract(&r.ru_stime, &track->system_start)); #else log_out(ctx, _("elapsed time: %6.3f\n"), timeval_subtract(&time_end, &track->time_start)); #endif #define mbytes(x) (((x) + 1048575) / 1048576) if (channel && channel->manager && channel->manager->get_stats) { io_stats delta = 0; unsigned long long bytes_read = 0; unsigned long long bytes_written = 0; if (desc) log_out(ctx, "%s: ", desc); channel->manager->get_stats(channel, &delta); if (delta) { bytes_read = delta->bytes_read - track->bytes_read; bytes_written = delta->bytes_written - track->bytes_written; } log_out(ctx, "I/O read: %lluMB, write: %lluMB, " "rate: %.2fMB/s\n", mbytes(bytes_read), mbytes(bytes_written), (double)mbytes(bytes_read + bytes_written) / timeval_subtract(&time_end, &track->time_start)); } }
int main(int ac, char **av) { int lc; char *msg; void *tret; /*************************************************************** * parse standard options ***************************************************************/ if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) { tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); } /*************************************************************** * perform global setup for test ***************************************************************/ setup(); /*************************************************************** * check looping state if -c option given ***************************************************************/ for (lc = 0; TEST_LOOPING(lc); lc++) { Tst_count = 0; /* * TEST CASE: * Increase by 8192 bytes */ Increment = 8192; /* Call sbrk(2) */ errno = 0; tret = sbrk(Increment); /* Remove -64 IRIX compiler warning */ TEST_ERRNO = errno; /* check return code */ if (tret == (void *)-1) { TEST_ERROR_LOG(TEST_ERRNO); tst_resm(TFAIL, "sbrk - Increase by 8192 bytes failed, errno=%d : %s", TEST_ERRNO, strerror(TEST_ERRNO)); } else { /*************************************************************** * only perform functional verification if flag set (-f not given) ***************************************************************/ if (STD_FUNCTIONAL_TEST) { /* No Verification test, yet... */ tst_resm(TPASS, "sbrk - Increase by 8192 bytes returned %p", tret); } } /* * TEST CASE: * Decrease to original size */ Increment = (Increment * -1); /* Call sbrk(2) */ errno = 0; tret = sbrk(Increment); TEST_ERRNO = errno; /* check return code */ if (tret == (void *)-1) { TEST_ERROR_LOG(TEST_ERRNO); tst_resm(TFAIL, "sbrk - Decrease to original size failed, errno=%d : %s", TEST_ERRNO, strerror(TEST_ERRNO)); } else { /*************************************************************** * only perform functional verification if flag set (-f not given) ***************************************************************/ if (STD_FUNCTIONAL_TEST) { /* No Verification test, yet... */ tst_resm(TPASS, "sbrk - Decrease to original size returned %p", tret); } } } /*************************************************************** * cleanup and exit ***************************************************************/ cleanup(); tst_exit(); }
int main(int ac, char **av) { int lc; /* loop counter */ char *msg; /* message returned from parse_opts */ int incr; /* increment */ long nbrkpt; /* new brk point value */ long cur_brk_val; /* current size returned by sbrk */ long aft_brk_val; /* current size returned by sbrk */ if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); setup(); /* * Attempt to control how fast we get to test max size. * Every MAX_SIZE_LC'th lc will be fastest test will reach max size. */ incr = (Max_brk_byte_size - Beg_brk_val) / (MAX_SIZE_LC / 2); if ((incr * 2) < 4096) /* make sure that process will grow */ incr += 4096 / 2; for (lc = 0; TEST_LOOPING(lc); lc++) { Tst_count = 0; /* * Determine new value to give brk * Every even lc value, grow by 2 incr and * every odd lc value, strink by one incr. * If lc is equal to 3, no change, special case. */ cur_brk_val = (long)sbrk(0); if (lc == 3) { nbrkpt = cur_brk_val; /* no change, special one time case */ } else if ((lc % 2) == 0) { /* * grow */ nbrkpt = cur_brk_val + (2 * incr); if (nbrkpt > Max_brk_byte_size) nbrkpt = Beg_brk_val; /* start over */ } else { /* * shrink */ nbrkpt = cur_brk_val - incr; } /**** printf("cur_brk_val = %d, nbrkpt = %d, incr = %d, lc = %d\n", cur_brk_val, nbrkpt, incr, lc); ****/ /* * Call brk(2) */ TEST(brk((char *)nbrkpt)); /* check return code */ if (TEST_RETURN == -1) { aft_brk_val = (long)sbrk(0); tst_resm(TFAIL|TTERRNO, "brk(%ld) failed (size before %ld, after %ld)", nbrkpt, cur_brk_val, aft_brk_val); } else { if (STD_FUNCTIONAL_TEST) { aft_brk_val = (long)sbrk(0); if (aft_brk_val == nbrkpt) { tst_resm(TPASS, "brk(%ld) returned %ld, new size verified by sbrk", nbrkpt, TEST_RETURN); } else { tst_resm(TFAIL, "brk(%ld) returned %ld, sbrk before %ld, after %ld", nbrkpt, TEST_RETURN, cur_brk_val, aft_brk_val); } } } } cleanup(); tst_exit(); }
TEST(unistd, sbrk_ENOMEM) { #if defined(__BIONIC__) && !defined(__LP64__) // There is no way to guarantee that all overflow conditions can be tested // without manipulating the underlying values of the current break. extern void* __bionic_brk; class ScopedBrk { public: ScopedBrk() : saved_brk_(__bionic_brk) {} virtual ~ScopedBrk() { __bionic_brk = saved_brk_; } private: void* saved_brk_; }; ScopedBrk scope_brk; // Set the current break to a point that will cause an overflow. __bionic_brk = reinterpret_cast<void*>(static_cast<uintptr_t>(PTRDIFF_MAX) + 2); // Can't increase by so much that we'd overflow. ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(PTRDIFF_MAX)); ASSERT_EQ(ENOMEM, errno); // Set the current break to a point that will cause an overflow. __bionic_brk = reinterpret_cast<void*>(static_cast<uintptr_t>(PTRDIFF_MAX)); ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(PTRDIFF_MIN)); ASSERT_EQ(ENOMEM, errno); __bionic_brk = reinterpret_cast<void*>(static_cast<uintptr_t>(PTRDIFF_MAX) - 1); ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(PTRDIFF_MIN + 1)); ASSERT_EQ(ENOMEM, errno); #else class ScopedBrk { public: ScopedBrk() : saved_brk_(get_brk()) {} virtual ~ScopedBrk() { brk(saved_brk_); } private: void* saved_brk_; }; ScopedBrk scope_brk; uintptr_t cur_brk = reinterpret_cast<uintptr_t>(get_brk()); if (cur_brk < static_cast<uintptr_t>(-(SBRK_MIN+1))) { // Do the overflow test for a max negative increment. ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(SBRK_MIN)); #if defined(__BIONIC__) // GLIBC does not set errno in overflow case. ASSERT_EQ(ENOMEM, errno); #endif } uintptr_t overflow_brk = static_cast<uintptr_t>(SBRK_MAX) + 2; if (cur_brk < overflow_brk) { // Try and move the value to PTRDIFF_MAX + 2. cur_brk = reinterpret_cast<uintptr_t>(sbrk(overflow_brk)); } if (cur_brk >= overflow_brk) { ASSERT_EQ(reinterpret_cast<void*>(-1), sbrk(SBRK_MAX)); #if defined(__BIONIC__) // GLIBC does not set errno in overflow case. ASSERT_EQ(ENOMEM, errno); #endif } #endif }
void setup() { unsigned long max_size; int ncpus; unsigned long ulim_sz; unsigned long usr_mem_sz; struct rlimit lim; tst_sig(NOFORK, DEF_HANDLER, cleanup); /*if ((ulim_sz=ulimit(3,0)) == -1) tst_brkm(TBROK|TERRNO, cleanup, "ulimit(3,0) failed"); */ if (getrlimit(RLIMIT_DATA, &lim) == -1) tst_brkm(TBROK|TERRNO, cleanup, "getrlimit(RLIMIT_DATA,%p) failed", &lim); ulim_sz = lim.rlim_cur; #ifdef CRAY if ((usr_mem_sz = sysconf(_SC_CRAY_USRMEM)) == -1) tst_brkm(TBROK|TERRNO, cleanup, "sysconf(_SC_CRAY_USRMEM) failed"); usr_mem_sz *= 8; /* convert to bytes */ #else /* * On IRIX, which is a demand paged system, memory is managed * different than on Crays systems. For now, pick some value. */ usr_mem_sz = 1024 * 1024 * sizeof(long); #endif #ifdef __linux__ #define _SC_NPROC_ONLN _SC_NPROCESSORS_ONLN #endif if ((ncpus = sysconf(_SC_NPROC_ONLN)) == -1) tst_brkm(TBROK|TERRNO, cleanup, "sysconf(_SC_NPROC_ONLN) failed"); /* * allow 2*ncpus copies to run. * never attempt to take more than a * 1/4 of memory (by single test) */ if (ulim_sz < usr_mem_sz) max_size = ulim_sz; else max_size = usr_mem_sz; max_size = max_size / (2 * ncpus); if (max_size > (usr_mem_sz / 4)) max_size = usr_mem_sz / 4; /* only fourth mem by single test */ Beg_brk_val = (long)sbrk(0); /* * allow at least 4 times a big as current. * This will override above code. */ if (max_size < Beg_brk_val * 4) /* running on small mem and/or high # cpus */ max_size = Beg_brk_val * 4; Max_brk_byte_size = max_size; TEST_PAUSE; }
static int captured_main (void *data) { struct captured_main_args *context = data; int argc = context->argc; char **argv = context->argv; int count; static int quiet = 0; static int batch = 0; static int set_args = 0; static int already_initialized = 0; /* Pointers to various arguments from command line. */ char *symarg = NULL; char *execarg = NULL; char *corearg = NULL; char *cdarg = NULL; char *ttyarg = NULL; /* These are static so that we can take their address in an initializer. */ static int print_help; static int print_version; /* Pointers to all arguments of --command option. */ struct cmdarg { enum { CMDARG_FILE, CMDARG_COMMAND } type; char *string; } *cmdarg; /* Allocated size of cmdarg. */ int cmdsize; /* Number of elements of cmdarg used. */ int ncmd; /* Indices of all arguments of --directory option. */ char **dirarg; /* Allocated size. */ int dirsize; /* Number of elements used. */ int ndir; struct stat homebuf, cwdbuf; char *homedir; int i; long time_at_startup = get_run_time (); #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES) setlocale (LC_MESSAGES, ""); #endif #if defined (HAVE_SETLOCALE) setlocale (LC_CTYPE, ""); #endif bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); #ifdef HAVE_SBRK lim_at_start = (char *) sbrk (0); #endif #if defined (ALIGN_STACK_ON_STARTUP) i = (int) &count & 0x3; if (i != 0) alloca (4 - i); #endif /* (TiEmu 20050514 Kevin Kofler) Skip all these in case of a restart. */ cmdsize = 1; cmdarg = (struct cmdarg *) xmalloc (cmdsize * sizeof (*cmdarg)); ncmd = 0; dirsize = 1; dirarg = (char **) xmalloc (dirsize * sizeof (*dirarg)); ndir = 0; quit_flag = 0; line = (char *) xmalloc (linesize); line[0] = '\0'; /* Terminate saved (now empty) cmd line */ if (already_initialized) { /* (TiEmu 20050512 Kevin Kofler) Reinitialize Insight in case of a restart. */ gdbtk_started = 0; gdbtk_disable_fputs = 1; } else { instream = stdin; getcwd (gdb_dirbuf, sizeof (gdb_dirbuf)); current_directory = gdb_dirbuf; gdb_stdout = stdio_fileopen (stdout); gdb_stderr = stdio_fileopen (stderr); gdb_stdlog = gdb_stderr; /* for moment */ gdb_stdtarg = gdb_stderr; /* for moment */ gdb_stdin = stdio_fileopen (stdin); gdb_stdtargerr = gdb_stderr; /* for moment */ gdb_stdtargin = gdb_stdin; /* for moment */ /* Set the sysroot path. */ #ifdef TARGET_SYSTEM_ROOT_RELOCATABLE gdb_sysroot = make_relative_prefix (argv[0], BINDIR, TARGET_SYSTEM_ROOT); if (gdb_sysroot) { struct stat s; int res = 0; if (stat (gdb_sysroot, &s) == 0) if (S_ISDIR (s.st_mode)) res = 1; if (res == 0) { xfree (gdb_sysroot); gdb_sysroot = TARGET_SYSTEM_ROOT; } } else gdb_sysroot = TARGET_SYSTEM_ROOT; #else #if defined (TARGET_SYSTEM_ROOT) gdb_sysroot = TARGET_SYSTEM_ROOT; #else gdb_sysroot = ""; #endif #endif /* There will always be an interpreter. Either the one passed into this captured main, or one specified by the user at start up, or the console. Initialize the interpreter to the one requested by the application. */ interpreter_p = xstrdup (context->interpreter_p); /* Parse arguments and options. */ { int c; /* When var field is 0, use flag field to record the equivalent short option (or arbitrary numbers starting at 10 for those with no equivalent). */ enum { OPT_SE = 10, OPT_CD, OPT_ANNOTATE, OPT_STATISTICS, OPT_TUI, OPT_NOWINDOWS, OPT_WINDOWS }; static struct option long_options[] = { #if defined(TUI) {"tui", no_argument, 0, OPT_TUI}, #endif {"xdb", no_argument, &xdb_commands, 1}, {"dbx", no_argument, &dbx_commands, 1}, {"readnow", no_argument, &readnow_symbol_files, 1}, {"r", no_argument, &readnow_symbol_files, 1}, {"quiet", no_argument, &quiet, 1}, {"q", no_argument, &quiet, 1}, {"silent", no_argument, &quiet, 1}, {"nx", no_argument, &inhibit_gdbinit, 1}, {"n", no_argument, &inhibit_gdbinit, 1}, {"batch-silent", no_argument, 0, 'B'}, {"batch", no_argument, &batch, 1}, {"epoch", no_argument, &epoch_interface, 1}, /* This is a synonym for "--annotate=1". --annotate is now preferred, but keep this here for a long time because people will be running emacses which use --fullname. */ {"fullname", no_argument, 0, 'f'}, {"f", no_argument, 0, 'f'}, {"annotate", required_argument, 0, OPT_ANNOTATE}, {"help", no_argument, &print_help, 1}, {"se", required_argument, 0, OPT_SE}, {"symbols", required_argument, 0, 's'}, {"s", required_argument, 0, 's'}, {"exec", required_argument, 0, 'e'}, {"e", required_argument, 0, 'e'}, {"core", required_argument, 0, 'c'}, {"c", required_argument, 0, 'c'}, {"pid", required_argument, 0, 'p'}, {"p", required_argument, 0, 'p'}, {"command", required_argument, 0, 'x'}, {"eval-command", required_argument, 0, 'X'}, {"version", no_argument, &print_version, 1}, {"x", required_argument, 0, 'x'}, {"ex", required_argument, 0, 'X'}, #ifdef GDBTK {"tclcommand", required_argument, 0, 'z'}, {"enable-external-editor", no_argument, 0, 'y'}, {"editor-command", required_argument, 0, 'w'}, #endif {"ui", required_argument, 0, 'i'}, {"interpreter", required_argument, 0, 'i'}, {"i", required_argument, 0, 'i'}, {"directory", required_argument, 0, 'd'}, {"d", required_argument, 0, 'd'}, {"cd", required_argument, 0, OPT_CD}, {"tty", required_argument, 0, 't'}, {"baud", required_argument, 0, 'b'}, {"b", required_argument, 0, 'b'}, {"nw", no_argument, NULL, OPT_NOWINDOWS}, {"nowindows", no_argument, NULL, OPT_NOWINDOWS}, {"w", no_argument, NULL, OPT_WINDOWS}, {"windows", no_argument, NULL, OPT_WINDOWS}, {"statistics", no_argument, 0, OPT_STATISTICS}, {"write", no_argument, &write_files, 1}, {"args", no_argument, &set_args, 1}, {"l", required_argument, 0, 'l'}, {"return-child-result", no_argument, &return_child_result, 1}, {0, no_argument, 0, 0} }; while (1) { int option_index; c = getopt_long_only (argc, argv, "", long_options, &option_index); if (c == EOF || set_args) break; /* Long option that takes an argument. */ if (c == 0 && long_options[option_index].flag == 0) c = long_options[option_index].val; switch (c) { case 0: /* Long option that just sets a flag. */ break; case OPT_SE: symarg = optarg; execarg = optarg; break; case OPT_CD: cdarg = optarg; break; case OPT_ANNOTATE: /* FIXME: what if the syntax is wrong (e.g. not digits)? */ annotation_level = atoi (optarg); break; case OPT_STATISTICS: /* Enable the display of both time and space usage. */ display_time = 1; display_space = 1; break; case OPT_TUI: /* --tui is equivalent to -i=tui. */ xfree (interpreter_p); interpreter_p = xstrdup (INTERP_TUI); break; case OPT_WINDOWS: /* FIXME: cagney/2003-03-01: Not sure if this option is actually useful, and if it is, what it should do. */ #ifdef GDBTK /* --windows is equivalent to -i=insight. */ xfree (interpreter_p); interpreter_p = xstrdup (INTERP_INSIGHT); #endif use_windows = 1; break; case OPT_NOWINDOWS: /* -nw is equivalent to -i=console. */ xfree (interpreter_p); interpreter_p = xstrdup (INTERP_CONSOLE); use_windows = 0; break; case 'f': annotation_level = 1; /* We have probably been invoked from emacs. Disable window interface. */ use_windows = 0; break; case 's': symarg = optarg; break; case 'e': execarg = optarg; break; case 'c': corearg = optarg; break; case 'p': /* "corearg" is shared by "--core" and "--pid" */ corearg = optarg; break; case 'x': cmdarg[ncmd].type = CMDARG_FILE; cmdarg[ncmd++].string = optarg; if (ncmd >= cmdsize) { cmdsize *= 2; cmdarg = xrealloc ((char *) cmdarg, cmdsize * sizeof (*cmdarg)); } break; case 'X': cmdarg[ncmd].type = CMDARG_COMMAND; cmdarg[ncmd++].string = optarg; if (ncmd >= cmdsize) { cmdsize *= 2; cmdarg = xrealloc ((char *) cmdarg, cmdsize * sizeof (*cmdarg)); } break; case 'B': batch = batch_silent = 1; gdb_stdout = ui_file_new(); break; #ifdef GDBTK case 'z': { extern int gdbtk_test (char *); if (!gdbtk_test (optarg)) { fprintf_unfiltered (gdb_stderr, _("%s: unable to load tclcommand file \"%s\""), argv[0], optarg); exit (1); } break; } case 'y': /* Backwards compatibility only. */ break; case 'w': { external_editor_command = xstrdup (optarg); break; } #endif /* GDBTK */ case 'i': xfree (interpreter_p); interpreter_p = xstrdup (optarg); break; case 'd': dirarg[ndir++] = optarg; if (ndir >= dirsize) { dirsize *= 2; dirarg = (char **) xrealloc ((char *) dirarg, dirsize * sizeof (*dirarg)); } break; case 't': ttyarg = optarg; break; case 'q': quiet = 1; break; case 'b': { int i; char *p; i = strtol (optarg, &p, 0); if (i == 0 && p == optarg) /* Don't use *_filtered or warning() (which relies on current_target) until after initialize_all_files(). */ fprintf_unfiltered (gdb_stderr, _("warning: could not set baud rate to `%s'.\n"), optarg); else baud_rate = i; } break; case 'l': { int i; char *p; i = strtol (optarg, &p, 0); if (i == 0 && p == optarg) /* Don't use *_filtered or warning() (which relies on current_target) until after initialize_all_files(). */ fprintf_unfiltered (gdb_stderr, _("warning: could not set timeout limit to `%s'.\n"), optarg); else remote_timeout = i; } break; case '?': fprintf_unfiltered (gdb_stderr, _("Use `%s --help' for a complete list of options.\n"), argv[0]); exit (1); } } /* If --help or --version, disable window interface. */ if (print_help || print_version) { use_windows = 0; } if (set_args) { /* The remaining options are the command-line options for the inferior. The first one is the sym/exec file, and the rest are arguments. */ if (optind >= argc) { fprintf_unfiltered (gdb_stderr, _("%s: `--args' specified but no program specified\n"), argv[0]); exit (1); } symarg = argv[optind]; execarg = argv[optind]; ++optind; set_inferior_args_vector (argc - optind, &argv[optind]); } else { /* OK, that's all the options. The other arguments are filenames. */ count = 0; for (; optind < argc; optind++) switch (++count) { case 1: symarg = argv[optind]; execarg = argv[optind]; break; case 2: /* The documentation says this can be a "ProcID" as well. We will try it as both a corefile and a pid. */ corearg = argv[optind]; break; case 3: fprintf_unfiltered (gdb_stderr, _("Excess command line arguments ignored. (%s%s)\n"), argv[optind], (optind == argc - 1) ? "" : " ..."); break; } } if (batch) quiet = 1; } /* Initialize all files. Give the interpreter a chance to take control of the console via the deprecated_init_ui_hook (). */ gdb_init (argv[0]); already_initialized = 1; } /* Do these (and anything which might call wrap_here or *_filtered) after initialize_all_files() but before the interpreter has been installed. Otherwize the help/version messages will be eaten by the interpreter's output handler. */ if (print_version) { print_gdb_version (gdb_stdout); wrap_here (""); printf_filtered ("\n"); exit (0); } if (print_help) { print_gdb_help (gdb_stdout); fputs_unfiltered ("\n", gdb_stdout); exit (0); } /* FIXME: cagney/2003-02-03: The big hack (part 1 of 2) that lets GDB retain the old MI1 interpreter startup behavior. Output the copyright message before the interpreter is installed. That way it isn't encapsulated in MI output. */ if (!quiet && strcmp (interpreter_p, INTERP_MI1) == 0) { /* Print all the junk at the top, with trailing "..." if we are about to read a symbol file (possibly slowly). */ print_gdb_version (gdb_stdout); if (symarg) printf_filtered (".."); wrap_here (""); printf_filtered ("\n"); gdb_flush (gdb_stdout); /* Force to screen during slow operations */ } /* Install the default UI. All the interpreters should have had a look at things by now. Initialize the default interpreter. */ { /* Find it. */ struct interp *interp = interp_lookup (interpreter_p); if (interp == NULL) error (_("Interpreter `%s' unrecognized"), interpreter_p); /* Install it. */ if (!interp_set (interp)) { fprintf_unfiltered (gdb_stderr, "Interpreter `%s' failed to initialize.\n", interpreter_p); exit (1); } } /* FIXME: cagney/2003-02-03: The big hack (part 2 of 2) that lets GDB retain the old MI1 interpreter startup behavior. Output the copyright message after the interpreter is installed when it is any sane interpreter. */ if (!quiet && !current_interp_named_p (INTERP_MI1)) { /* Print all the junk at the top, with trailing "..." if we are about to read a symbol file (possibly slowly). */ print_gdb_version (gdb_stdout); if (symarg) printf_filtered (".."); wrap_here (""); printf_filtered ("\n"); gdb_flush (gdb_stdout); /* Force to screen during slow operations */ } /* Set off error and warning messages with a blank line. */ error_pre_print = "\n"; quit_pre_print = error_pre_print; warning_pre_print = _("\nwarning: "); /* Read and execute $HOME/.gdbinit file, if it exists. This is done *before* all the command line arguments are processed; it sets global parameters, which are independent of what file you are debugging or what directory you are in. */ homedir = getenv ("HOME"); if (homedir) { char *homeinit = xstrprintf ("%s/%s", homedir, gdbinit); if (!inhibit_gdbinit) { catch_command_errors (source_script, homeinit, 0, RETURN_MASK_ALL); } /* Do stats; no need to do them elsewhere since we'll only need them if homedir is set. Make sure that they are zero in case one of them fails (this guarantees that they won't match if either exists). */ memset (&homebuf, 0, sizeof (struct stat)); memset (&cwdbuf, 0, sizeof (struct stat)); stat (homeinit, &homebuf); stat (gdbinit, &cwdbuf); /* We'll only need this if homedir was set. */ xfree (homeinit); } /* Now perform all the actions indicated by the arguments. */ if (cdarg != NULL) { catch_command_errors (cd_command, cdarg, 0, RETURN_MASK_ALL); } for (i = 0; i < ndir; i++) catch_command_errors (directory_switch, dirarg[i], 0, RETURN_MASK_ALL); xfree (dirarg); if (execarg != NULL && symarg != NULL && strcmp (execarg, symarg) == 0) { /* The exec file and the symbol-file are the same. If we can't open it, better only print one error message. catch_command_errors returns non-zero on success! */ if (catch_command_errors (exec_file_attach, execarg, !batch, RETURN_MASK_ALL)) catch_command_errors (symbol_file_add_main, symarg, 0, RETURN_MASK_ALL); } else { if (execarg != NULL) catch_command_errors (exec_file_attach, execarg, !batch, RETURN_MASK_ALL); if (symarg != NULL) catch_command_errors (symbol_file_add_main, symarg, 0, RETURN_MASK_ALL); } if (corearg != NULL) { /* corearg may be either a corefile or a pid. If its first character is a digit, try attach first and then corefile. Otherwise try corefile first. */ if (isdigit (corearg[0])) { if (catch_command_errors (attach_command, corearg, !batch, RETURN_MASK_ALL) == 0) catch_command_errors (core_file_command, corearg, !batch, RETURN_MASK_ALL); } else /* Can't be a pid, better be a corefile. */ catch_command_errors (core_file_command, corearg, !batch, RETURN_MASK_ALL); } if (ttyarg != NULL) catch_command_errors (tty_command, ttyarg, !batch, RETURN_MASK_ALL); /* Error messages should no longer be distinguished with extra output. */ error_pre_print = NULL; quit_pre_print = NULL; warning_pre_print = _("warning: "); /* Read the .gdbinit file in the current directory, *if* it isn't the same as the $HOME/.gdbinit file (it should exist, also). */ if (!homedir || memcmp ((char *) &homebuf, (char *) &cwdbuf, sizeof (struct stat))) if (!inhibit_gdbinit) { catch_command_errors (source_script, gdbinit, 0, RETURN_MASK_ALL); } for (i = 0; i < ncmd; i++) { #if 0 /* NOTE: cagney/1999-11-03: SET_TOP_LEVEL() was a macro that expanded into a call to setjmp(). */ if (!SET_TOP_LEVEL ()) /* NB: This is #if 0'd out */ { /* NOTE: I am commenting this out, because it is not clear where this feature is used. It is very old and undocumented. ezannoni: 1999-05-04 */ #if 0 if (cmdarg[i][0] == '-' && cmdarg[i][1] == '\0') read_command_file (stdin); else #endif source_script (cmdarg[i], !batch); do_cleanups (ALL_CLEANUPS); } #endif if (cmdarg[i].type == CMDARG_FILE) catch_command_errors (source_script, cmdarg[i].string, !batch, RETURN_MASK_ALL); else /* cmdarg[i].type == CMDARG_COMMAND */ catch_command_errors (execute_command, cmdarg[i].string, !batch, RETURN_MASK_ALL); } xfree (cmdarg); /* Read in the old history after all the command files have been read. */ init_history (); if (batch) { /* We have hit the end of the batch file. */ quit_force (NULL, 0); } /* Do any host- or target-specific hacks. This is used for i960 targets to force the user to set a nindy target and spec its parameters. */ #ifdef BEFORE_MAIN_LOOP_HOOK BEFORE_MAIN_LOOP_HOOK; #endif /* Show time and/or space usage. */ if (display_time) { long init_time = get_run_time () - time_at_startup; printf_unfiltered (_("Startup time: %ld.%06ld\n"), init_time / 1000000, init_time % 1000000); } if (display_space) { #ifdef HAVE_SBRK extern char **environ; char *lim = (char *) sbrk (0); printf_unfiltered (_("Startup size: data size %ld\n"), (long) (lim - (char *) &environ)); #endif } #if 0 /* FIXME: cagney/1999-11-06: The original main loop was like: */ while (1) { if (!SET_TOP_LEVEL ()) { do_cleanups (ALL_CLEANUPS); /* Do complete cleanup */ /* GUIs generally have their own command loop, mainloop, or whatever. This is a good place to gain control because many error conditions will end up here via longjmp(). */ if (deprecated_command_loop_hook) deprecated_command_loop_hook (); else deprecated_command_loop (); quit_command ((char *) 0, instream == stdin); } } /* NOTE: If the command_loop() returned normally, the loop would attempt to exit by calling the function quit_command(). That function would either call exit() or throw an error returning control to SET_TOP_LEVEL. */ /* NOTE: The function do_cleanups() was called once each time round the loop. The usefulness of the call isn't clear. If an error was thrown, everything would have already been cleaned up. If command_loop() returned normally and quit_command() was called, either exit() or error() (again cleaning up) would be called. */ #endif /* NOTE: cagney/1999-11-07: There is probably no reason for not moving this loop and the code found in captured_command_loop() into the command_loop() proper. The main thing holding back that change - SET_TOP_LEVEL() - has been eliminated. */ while (1) { catch_errors (captured_command_loop, 0, "", RETURN_MASK_ALL); } /* No exit -- exit is through quit_command. */ }
void* mysbrk(ulong size) { return (void*)sbrk(size); }