static void env_var_list_add (const char* env, const char* val) { env_var_t* n; if (val == 0) return; n = (env_var_t *)malloc_check (sizeof (env_var_t)); if (!n) return; if (env_var_list.first == 0) env_var_list.first = n; if (env_var_list.last) env_var_list.last->next = n; env_var_list.last = n; n->env_name = (char *)malloc_check (strlen (env) + 1); n->env_val = (char *)malloc_check (strlen (val) + 1); if (!n->env_name || !n->env_val) return; strcpy (n->env_name, env); strcpy (n->env_val, val); }
char* get_connectdb() { if (!parsed) return NULL; else { char *return_string; return_string = (char*) malloc(1024 * sizeof(char)); malloc_check(return_string); if (vector_findString(keys, "database.name") > -1) { sprintf(return_string, " dbname=%s host=%s port=%s user=%s password=%s ", (char*) vector_getItem(values, vector_findString(keys, "database.name")), (char*) vector_getItem(values, vector_findString(keys, "database.host")), (char*) vector_getItem(values, vector_findString(keys, "database.port")), (char*) vector_getItem(values, vector_findString(keys, "database.user")), (char*) vector_getItem(values, vector_findString(keys, "database.password")) ); return return_string; } else return NULL; } }
void main( int argc, char **argv ) { Display *display; int result; #ifdef USERHELP malloc_check(1); malloc_trace(0); #endif XtAppContext app; /* Initialize the toolkit and open the display */ XtToolkitInitialize(); app = XtCreateApplicationContext(); display = XtOpenDisplay(app, NULL, argv[0], "Customize", NULL, 0, &argc, argv); /* Go register the DT error handler */ XeProgName = argv[0]; result = InitializeDtcolor(display, DEFAULT_SESSION); if(result != 0) exit(0); XtAppMainLoop(app); }
void rt_shadows(t_rt *rt, t_list *spots) { uint *colors; int x; uint tmp_color; t_union uni; t_elem *elem; t_spot *spot; x = 0; malloc_check((colors = malloc(sizeof(int) * (spots->length + 1)))); spots->rewind(spots); tmp_color = rt->color; while ((elem = spots->next(spots))) if ((spot = elem->mem)) { uni.color = tmp_color; rt->inter.vx = spot->spot.xo - rt->inter.xo; rt->inter.vy = spot->spot.yo - rt->inter.yo; rt->inter.vz = spot->spot.zo - rt->inter.zo; rt_shadow(rt, &rt->inter, &uni.rgb); colors[x++] = uni.color; } rt->color = uni.color; if (x > 1) rt->color = rt_average(colors, spots->length); free(colors); }
static outs_t *alloc_outs(intmax_t k) { outs_t *r = malloc_check(sizeof(*r)) ; r->k = k ; r->c = 0 ; r->show = 0 ; r->next = r->down = NULL ; return r ; }
char* TinyWebServer::decode_url_encoded(const char* s) { if (!s) { return NULL; } char* r = (char*)malloc_check(strlen(s) + 1); if (!r){ return NULL; } char* r2 = r; const char* p = s; while (*s && (p = strchr(s, '%'))) { if (p - s) { memcpy(r2, s, p - s); r2 += (p - s); } // If the remaining number of characters is less than 3, we cannot // have a complete escape sequence. Break early. if (strlen(p) < 3) { // Move the new beginning to the value of p. s = p; break; } char hex[3]; hex[0] = *(p + 1); hex[1] = *(p + 2); hex[2] = 0; uint32_t r = strtoul(hex, NULL, 16); if (r == 0 || errno) { // No conversion could be performed, couldn't find an escape // sequence. Copy it as it is in the result. memcpy(r2, p, 3); r2 += 3; } else { *r2++ = r; } p += 3; // Move the new beginning to the value of p. s = p; } // Copy whatever is left of the string in the result. int len = strlen(s); if (len > 0) { strncpy(r2, s, len); } // Append the 0 terminator. *(r2 + len) = 0; return r; }
void AtMegaWebServer::initHeaders(const char** headers) { int size = 0; for (int i = 0; headers[i]; i++) { size++; } headers_ = (HeaderValue*)malloc_check(sizeof(HeaderValue) * (size + 1)); if (headers_) { for (int i = 0; i < size; i++) { headers_[i].header = headers[i]; headers_[i].value = NULL; } headers_[size].header = NULL; } }
void encode_polhemus_transform(stateptr state) { /* assuming you have a matrix ready, this just transforms all the picked */ /* objects by it */ #ifdef debugmalloc malloc_check(); #endif /* push the polhemus state record pointer */ setup_CPL_word_blank(&op_word,Opcode_data); op_word.word_data.CPLopcode = PUSH; setup_CPL_auxword(&as_word,CPLaux_address_data); as_word.word_data.CPLauxdata.CPLaddressdata = polhemustate; store_CPL_RAM_instruction(&op_word,&as_word); /* push all the picked objects... */ setup_CPL_word_blank(&op_word,Opcode_data); op_word.word_data.CPLopcode = PUSH; setup_CPL_word_blank(&as_word,Proplist_data); as_word.word_data.CPLproplist->first.sort->sortdata1->i = picked_prop; as_word.contents_of = TRUE; store_CPL_RAM_instruction(&op_word,&as_word); /* call the Croutine that does the ugly work */ op_word.word_data.CPLopcode = CRTN; setup_CPL_auxword(&as_word,CPLaux_Croutine_index_data); as_word.word_data.CPLauxdata.Croutine_index = transform_routine_index; store_CPL_RAM_instruction(&op_word,&as_word); /* ar word can just be blank because TRNSFRM doesn't use it when */ /* transforming features... */ #ifdef debugmalloc malloc_check(); #endif }
static void* memalign_check(size_t alignment, size_t bytes, const void *caller) { void* mem; if (alignment <= MALLOC_ALIGNMENT) return malloc_check(bytes, NULL); if (alignment < MINSIZE) alignment = MINSIZE; if (bytes+1 == 0) { __set_errno (ENOMEM); return NULL; } (void)mutex_lock(&main_arena.mutex); mem = (top_check() >= 0) ? _int_memalign(&main_arena, alignment, bytes+1) : NULL; (void)mutex_unlock(&main_arena.mutex); return mem2mem_check(mem, bytes); }
static void read_sip_file( char* sip_file ) { FILE* fp; char line[5000]; fp = fopen( sip_file, "r" ); if ( fp == (FILE*) 0 ) { perror( sip_file ); exit( 1 ); } max_sips = 100; sips = (sip*) malloc_check( max_sips * sizeof(sip) ); num_sips = 0; while ( fgets( line, sizeof(line), fp ) != (char*) 0 ) { /* Nuke trailing newline. */ if ( line[strlen( line ) - 1] == '\n' ) line[strlen( line ) - 1] = '\0'; /* Check for room in sips. */ if ( num_sips >= max_sips ) { max_sips *= 2; sips = (sip*) realloc_check( (void*) sips, max_sips * sizeof(sip) ); } /* Add to table. */ sips[num_sips].str = strdup_check( line ); (void) memset( (void*) &sips[num_sips].sa_in, 0, sizeof(sips[num_sips].sa_in) ); sips[num_sips].sa_in.sin_family = AF_INET; if ( ! inet_aton( sips[num_sips].str, &sips[num_sips].sa_in.sin_addr ) ) { (void) fprintf( stderr, "%s: cannot convert source IP address %s\n", argv0, sips[num_sips].str ); exit( 1 ); } ++num_sips; } }
GLboolean update_polhemus_state(void) { polhemusvalstruct newpolhvals; vertype deltapos,deltaorient; GLboolean polhemus_moved,polhemus_rotated; ; read_polhemus(&newpolhvals); diffpos3d(polhemustate->pos,newpolhvals.pos,deltapos); diffpos3d(polhemustate->orient,newpolhvals.orient,deltaorient); polhemus_moved = !(vector_near_zero(deltapos,1.0)); polhemus_rotated = !(vec_eq_zero(deltaorient)); if (polhemus_moved) { copypos3d(newpolhvals.pos,polhemustate->pos); copypos3d(deltapos,polhemustate->deltapos); } if (polhemus_rotated) { copypos3d(newpolhvals.orient,polhemustate->orient); copypos3d(deltaorient,polhemustate->deltaorient); } if ((polhemus_moved || polhemus_rotated) && glove_state == Gloverotatestate) update_polh_xform(); #if 0 printf("------------------------------------------------------------------\n"); printf("X: %-6.0f Y: %-6.0f Z: %-6.0f YAW: %-6.0f PITCH: %-6.0f ROLL: %-6.0f\n", polhemustate->pos[vx],polhemustate->pos[vy],polhemustate->pos[vz], polhemustate->orient[vx], polhemustate->orient[vy], polhemustate->orient[vz]); printf("thisxform:"); printmatrix(polhemustate->xform); printf("deltaxform:"); printmatrix(polhemustate->deltaxform); #endif #ifdef debugmalloc malloc_check(); #endif return(polhemus_moved); }
int main(void) { log_init(); ext_init(); mallocer_init(); mutex_init(); log_set_level(LOG_DEBUG, NULL); log_set_file("mallocer_check.log"); malloc_check(); realloc_check(); mutex_fini(); mallocer_fini(); ext_fini(); log_fini(); return EXIT_SUCCESS; }
char* get_gdb() { if (!parsed) return NULL; else { char *return_string; return_string = (char*) malloc(8192 * sizeof(char)); malloc_check(return_string); if (vector_findString(keys, GDB) > -1) { sprintf(return_string, "%s", (char*) vector_getItem(values, vector_findString(keys, GDB))); return return_string; } else return NULL; } }
// Returns a newly allocated string containing the field number `which`. // The first field's index is 0. // The caller is responsible for freeing the returned value. char* MiniWebServer::get_field(const char* buffer, int which) { char* field = NULL; boolean prev_is_space = false; int i = 0; int field_no = 0; int size = strlen(buffer); // Locate the field we need. A field is defined as an area of // non-space characters delimited by one or more space characters. for (; field_no < which; field_no++) { // Skip over space characters while (i < size && isspace(buffer[i])) { i++; } // Skip over non-space characters. while (i < size && !isspace(buffer[i])) { i++; } } // Now we identify the end of the field that we want. // Skip over space characters. while (i < size && isspace(buffer[i])) { i++; } if (field_no == which && i < size) { // Now identify where the field ends. int j = i; while (j < size && !isspace(buffer[j])) { j++; } field = (char*) malloc_check(j - i + 1); if (!field) { return NULL; } memcpy(field, buffer + i, j - i); field[j - i] = 0; } return field; }
boolean MiniWebServer::assign_header_value(const char* header, char* value) { if (!headers_) { return false; } boolean found = false; for (int i = 0; headers_[i].header; i++) { // Use pointer equality, since `header' must be the pointer // inside headers_. if (header == headers_[i].header) { headers_[i].value = (char*)malloc_check(strlen(value) + 1); if (!headers_[i].value) { return false; } strcpy(headers_[i].value, value); found = true; break; } } return found; }
void boolean_preprocess(shellptr shellA, shellptr shellB, listptr vv_list,listptr vf_list) { listptr vee_list,ef_list; ; vee_list = create_list(); ef_list = create_list(); log_pure_vvs(shellA,shellB,vv_list); log_vertex_edges(shellA,shellB,vee_list); split_from_veelist(shellA,shellB,vee_list,vv_list); resolve_edge_faces(shellA,shellB,vf_list,ef_list); #ifdef debug topology_check(shellA); topology_check(shellB); malloc_check(); #endif }
static void * memalign_check (size_t alignment, size_t bytes, const void *caller) { void *mem; if (alignment <= MALLOC_ALIGNMENT) return malloc_check (bytes, NULL); if (alignment < MINSIZE) alignment = MINSIZE; /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a power of 2 and will cause overflow in the check below. */ if (alignment > SIZE_MAX / 2 + 1) { __set_errno (EINVAL); return 0; } /* Check for overflow. */ if (bytes > SIZE_MAX - alignment - MINSIZE) { __set_errno (ENOMEM); return 0; } /* Make sure alignment is power of 2. */ if (!powerof2 (alignment)) { size_t a = MALLOC_ALIGNMENT * 2; while (a < alignment) a <<= 1; alignment = a; } (void) mutex_lock (&main_arena.mutex); mem = (top_check () >= 0) ? _int_memalign (&main_arena, alignment, bytes + 1) : NULL; (void) mutex_unlock (&main_arena.mutex); return mem2mem_check (mem, bytes); }
boolean AtMegaWebServer::assignHeaderValue(){ if (!headers_) { return false; } char *head = buffer; while(*head && isspace(*head)) head++; char *val = head; while(*val && *val != ':') val++; *val++ = 0; for (int i = 0; headers_[i].header; i++) { if (!strcmp(head, headers_[i].header)) { headers_[i].value = (char*)malloc_check(strlen(val) + 1); if (headers_[i].value) { strcpy(headers_[i].value, val); return true; } } } return false; }
char* MiniWebServer::decode_url_encoded(const char* s) { if (!s) { return NULL; } char* r = (char*)malloc_check(strlen(s) + 1); if (!r) { return NULL; } char* r2 = r; const char* p = s; while (*s && (p = strchr(s, '%'))) { if (p - s) { memcpy(r2, s, p - s); r2 += (p - s); } // If the remaining number of characters is less than 3, we cannot // have a complete escape sequence. Break early. if (strlen(p) < 3) { // Move the new beginning to the value of p. s = p; break; } uint8_t r = parseHexChar(*(p + 1)) << 4 | parseHexChar(*(p + 2)); *r2++ = r; p += 3; // Move the new beginning to the value of p. s = p; } // Copy whatever is left of the string in the result. int len = strlen(s); if (len > 0) { strncpy(r2, s, len); } // Append the 0 terminator. *(r2 + len) = 0; return r; }
TinyWebServer::TinyWebServer(PathHandler handlers[], const char** headers) : handlers_(handlers), server_(EthernetServer(8000)), path_(NULL), request_type_(UNKNOWN_REQUEST), client_(EthernetClient(255)) { if (headers) { int size = 0; for (int i = 0; headers[i]; i++) { size++; } headers_ = (HeaderValue*)malloc_check(sizeof(HeaderValue) * (size + 1)); if (headers_) { for (int i = 0; i < size; i++) { headers_[i].header = headers[i]; headers_[i].value = NULL; } headers_[size].header = NULL; } } }
/* Generates a color palette, setting palette->colors and palette->len. * Allocates new memory for palette->colors (is not freed or reallocd). * 'n_colors' defines how many colors are generated in the palette. * 'points' is a definition colors at specific intervals, 'n_points' gives the * number of palette_point_t array elements in 'points'. * 'format' is used to generate video mode specific color data. */ void make_palette(palette_t *palette, int n_colors, palette_point_t *points, int n_points, SDL_PixelFormat *format) { int i; palette->colors = malloc_check(n_colors * sizeof(Uint32)); palette->len = n_colors; palette->format = format; if (n_points < 1) { for (i = 0; i < palette->len; i++) { float val = (float)i / palette->len; set_color(palette, i, val, val, val); } return; } palette_point_t *last_p = points; palette_point_t *first_p = points; for (i = 1; i < n_points; i ++) { if (points[i].pos > last_p->pos) last_p = &points[i]; if (points[i].pos < first_p->pos) first_p = &points[i]; } if (last_p->pos > 1.0) { float norm_factor = last_p->pos; for (i = 0; i < n_points; i ++) points[i].pos /= norm_factor; } // duplicate the last point to "the left", wrap back below zero. palette_point_t p = *last_p; p.pos -= 1.0; // ...unless another point is defined there. if (p.pos >= first_p->pos) p = *first_p; // also duplicate the first point to "the right". palette_point_t post_last = *first_p; post_last.pos += 1.0; int color_pos = 0; while(color_pos < n_colors) { // look for the next point, the one with the next largest pos after p.pos palette_point_t *next_p = NULL; for (i = 0; i < n_points; i ++) { float i_pos = points[i].pos; if ((i_pos > p.pos) && ( (! next_p) || (i_pos < next_p->pos) ) ) next_p = &points[i]; } if (! next_p) next_p = &post_last; int next_color_pos = (int)(next_p->pos * n_colors) + 1; if (next_color_pos <= color_pos) next_color_pos = color_pos + 1; for (; color_pos < next_color_pos; color_pos ++) { float prevpos = p.pos; float nextpos = next_p->pos; float currentpos = ((float)color_pos) / n_colors; float fade; if ((nextpos - prevpos) < 1e-3) fade = 0.5; else fade = (currentpos - prevpos) / (nextpos - prevpos); float rfade = 1.0 - fade; float r = rfade * p.r + fade * next_p->r; float g = rfade * p.g + fade * next_p->g; float b = rfade * p.b + fade * next_p->b; set_color(palette, color_pos, r, g, b); } p = *next_p; } }
/*++++++++++++++++++++++++++++++++++++++*/ int main( int argc, char **argv ) { int n; Arg args[MAX_ARGS]; XEvent event; XPropertyEvent *pEvent=(XPropertyEvent *)&event; long mwmFunc; Boolean useMaskRtn, useIconFileCacheRtn; char *dirs = NULL; char *string; Visual *visual; #ifdef USERHELP malloc_check(1); malloc_trace(0); #endif XtSetLanguageProc(NULL, NULL, NULL); _DtEnvControl(DT_ENV_SET); /* Initialize the toolkit and open the display */ style.shell = XtInitialize(argv[0], XMCLASS, option_list, 1, (int *)&argc, argv); #ifdef __osf__ _XmColorObjCreate(style.shell, NULL, NULL); #endif /* Allow all WS manipulation functions except resize and maximize */ mwmFunc = MWM_FUNC_ALL ^ (MWM_FUNC_RESIZE | MWM_FUNC_MAXIMIZE); n = 0; XtSetArg(args[n], XmNmwmFunctions, mwmFunc); n++; XtSetArg(args[n], XmNuseAsyncGeometry, True); n++; XtSetValues(style.shell, args, n); /* initialize global style data */ style.display = XtDisplay(style.shell); style.screen = DefaultScreenOfDisplay(style.display); style.screenNum = DefaultScreen(style.display); style.colormap = DefaultColormap(style.display, style.screenNum); style.root = DefaultRootWindow(style.display); style.execName = argv[0]; style.errDialog = NULL; style.tmpXmStr = NULL; style.home = (char *) XtMalloc(strlen((char *) getenv("HOME")) + 1); strcpy(style.home, (char *) getenv("HOME")); style.colorDialog = NULL; style.backdropDialog = NULL; style.fontDialog = NULL; style.kbdDialog = NULL; style.mouseDialog = NULL; style.audioDialog = NULL; style.screenDialog = NULL; style.startupDialog = NULL; style.dtwmDialog = NULL; style.i18nDialog = NULL; visual = XDefaultVisual(style.display,style.screenNum); style.visualClass = visual->class; if (progName = DtStrrchr(argv[0], '/')) progName++; else progName = argv[0]; /* Get the lock established to ensure only one dtstyle process * is running per screen .. first malloc enough space*/ if (_DtGetLock (style.display, STYLE_LOCK) == 0) { _DtSimpleError (progName, DtError, NULL, "%s", ((char *)GETMESSAGE(2, 5, "Style Manager is already running, second attempt aborted."))); exit(1); } InitDtstyleProtocol(); SetWindowProperties(); /* Register error handlers */ XSetErrorHandler(ErrorHandler); XSetIOErrorHandler(IOErrorHandler); XtAppSetErrorHandler(XtWidgetToApplicationContext(style.shell), ToolkitErrorHandler); XtAddEventHandler(style.shell, StructureNotifyMask, 0, (XtEventHandler)MwmReparentNotify, NULL); /* set up resolution dependent layout variables */ switch (_DtGetDisplayResolution(style.display, style.screenNum)) { case LOW_RES_DISPLAY: style.horizontalSpacing = style.verticalSpacing = 3; break; case MED_RES_DISPLAY: style.horizontalSpacing = style.verticalSpacing = 5; break; case HIGH_RES_DISPLAY: style.horizontalSpacing = style.verticalSpacing = 8; break; } GetApplicationResources(); XmeGetIconControlInfo(style.screen, &useMaskRtn, &style.useMultiColorIcons, &useIconFileCacheRtn); /* add the directory $HOME/.dt/backdrops */ string = (char *)XtMalloc(strlen(style.home) + strlen("/.dt/backdrops:") + 1); sprintf(string, "%s/.dt/backdrops:", style.home); dirs = (char *)XtCalloc(1, strlen("/etc/dt/backdrops:/usr/dt/backdrops") + (style.xrdb.backdropDir == NULL ? 2 : strlen(style.xrdb.backdropDir)) + strlen(string) + 2); strcpy(dirs, string); if (style.xrdb.backdropDir) { strcat(dirs, style.xrdb.backdropDir); strcat(dirs, ":"); } strcat(dirs, "/etc/dt/backdrops:/usr/dt/backdrops"); _DtWsmSetBackdropSearchPath(style.screen, dirs, style.useMultiColorIcons); if (string != NULL) XtFree((char *)string); if (dirs != NULL) XtFree((char *)dirs); style.count = 0; /* if this is started from save session we need to set up the BMS first, otherwise do it after making the window. (for user perception for how long it takes for the dtstyle to come up) */ if(style.xrdb.session != NULL) { DtInitialize (style.display, style.shell, progName, progName); /*Restore a session or build and display the main Window.*/ if(!restoreSession(style.shell,style.xrdb.session)) init_mainWindow(style.shell); } else { init_mainWindow(style.shell); DtInitialize (style.display, style.shell, progName, progName); InitializeAtoms(); CheckMonitor(style.shell); GetDefaultPal(style.shell); } signal(SIGINT,(void (*)())activateCB_exitBtn); signal(SIGTERM,(void (*)())activateCB_exitBtn); /* to avoid defunct screen saver processes */ signal(SIGCHLD, (void (*)())WaitChildDeath); /* backdrop dialog needs to know when the workspace changes to recolor the bitmap displayed in the dialog */ ListenForWorkspaceChange(); /* if using COLOR builtin, style.workProcs is True */ if ((XmeUseColorObj() != FALSE) && style.workProcs) XtAppAddWorkProc(XtWidgetToApplicationContext(style.shell), NewCreateD, style.shell); XtAppMainLoop(XtWidgetToApplicationContext(style.shell)); return 0; }
int main() { // apply FFT to real 2D data. double *in; double *apex; int W = 640; int H = 480; int half_H = (H / 2) + 1; int x; int y; fftw_complex *out; fftw_complex *apex_f; fftw_plan plan_backward; fftw_plan plan_apex; fftw_plan plan_forward; unsigned int seed = 123456789; srand(seed); in = (double *) malloc_check(sizeof(double) * W * H); for(x = 0; x < W; x++) { for(y = 0; y < H; y++) { #if 1 in[x*H+y] = ( double ) rand ( ) / ( RAND_MAX ); #else in[x*H+y] = 0; #endif } } in[(H/2) + (W/2)*H] = 1; in[(H/2)+3 + (W/2 + 3)*H] = 1; in[10 + (20)*H] = 1; in[H-3 + (W-3)*H] = 1; y = W * H; for (x = 0; x < y; x++) { in[x] *= PALETTE_LEN -10; } apex = (double*)malloc_check(sizeof(double) * W * H); double apex_sum = 0; for(x = 0; x < W; x++) { for(y = 0; y < H; y++) { double dist = 0; int xx = x; int yy = y; if (xx >= W/2) xx = W - x; if (yy >= H/2) yy = H - y; dist = sqrt(xx*xx + yy*yy); double v = 8.01 - dist; if (v < 0) v = 0; #if 0 if (x == 2 && y == 1) v = 302.1; #endif #if 0 if (x == W / 2 && y == H / 2) v = 850; #endif #if 0 if (x < W/2 || y > H / 2) v = -v * 1.85; #endif #if 0 if (x == W/3-1 && y == H/3-1) v = 200; if (x == W/3 && y == H/3) v = -200; #endif apex_sum += v; apex[x*H+y] = v; } } double burn = 1.005; double apex_mul = (burn / (W*H)) / apex_sum; printf("%f %f\n", apex_sum, apex_mul); y = W * H; for (x = 0; x < y; x++) { apex[x] *= apex_mul; } apex_f = fftw_malloc(sizeof(fftw_complex) * W * half_H); plan_apex = fftw_plan_dft_r2c_2d(W, H, apex, apex_f, FFTW_ESTIMATE); fftw_execute(plan_apex); out = fftw_malloc(sizeof(fftw_complex) * W * half_H); plan_forward = fftw_plan_dft_r2c_2d(W, H, in, out, FFTW_ESTIMATE); plan_backward = fftw_plan_dft_c2r_2d(W, H, out, in, FFTW_ESTIMATE); int winW = W; int winH = H; SDL_Window *window; window = SDL_CreateWindow("fftw3_test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, winW, winH, 0); if (!window) { fprintf(stderr, "Unable to set %dx%d video: %s\n", winW, winH, SDL_GetError()); exit(1); } SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0); if (!renderer) { fprintf(stderr, "Unable to set %dx%d video: %s\n", winW, winH, SDL_GetError()); exit(1); } SDL_ShowCursor(SDL_DISABLE); SDL_PixelFormat *pixelformat = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888); SDL_Texture *texture = SDL_CreateTexture(renderer, pixelformat->format, SDL_TEXTUREACCESS_STREAMING, winW, winH); if (!texture) { fprintf(stderr, "Cannot create texture\n"); exit(1); } #if 0 #define n_palette_points 2 palette_point_t palette_points[n_palette_points] = { { 0., 0, 0, 0 }, { 1., 1, 1, 1 }, }; #else #define n_palette_points 11 palette_point_t palette_points[n_palette_points] = { { 0./6, 1, 1, 1 }, { 0.5/6, 1, .9, 0 }, { 1./6, 1, .1, 1 }, { 1.5/6, 0, 0, 1 }, { 3./6, .5, 0, .7 }, { 3.5/6, 0, 1, .7 }, { 4.5/6, .2, .8, .2 }, { 4.8/6, 0, 0, 1 }, { 5.25/6, .8, .8, 0 }, { 5.55/6, .8, .2, 0.4 }, { 5.85/6, .0,.60,.50 }, }; #endif palette_t palette; make_palette(&palette, PALETTE_LEN, palette_points, n_palette_points, pixelformat); bool running = true; int frame_period = 50; int last_ticks = SDL_GetTicks() - frame_period; Uint32 *winbuf = (Uint32*)malloc_check(winW * winH * sizeof(Uint32)); while (running) { bool do_render = false; int elapsed = SDL_GetTicks() - last_ticks; if (elapsed > frame_period) { last_ticks += frame_period * (elapsed / frame_period); do_render = true; } if (do_render) { render(winbuf, winW, winH, &palette, in, W, H); SDL_UpdateTexture(texture, NULL, winbuf, winW * sizeof(Uint32)); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); fftw_execute(plan_forward); #if 1 for (x = 0; x < W; x++) { for (y = 0; y < half_H; y++) { double *o = out[x*half_H + y]; double *af = apex_f[x*half_H + y]; double a, b, c, d; a = o[0]; b = o[1]; c = af[0]; d = af[1]; #if 1 o[0] = (a*c - b*d); o[1] = (b*c + a*d); #else double l = sqrt(c*c + d*d); o[0] *= l; o[1] *= l; #endif } } #endif fftw_execute(plan_backward); } else SDL_Delay(5); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: // If escape is pressed, return (and thus, quit) switch(event.key.keysym.sym) { case SDLK_ESCAPE: running = false; break; default: break; } break; case SDL_QUIT: running = false; break; } } } SDL_Quit(); fftw_destroy_plan(plan_apex); fftw_destroy_plan(plan_forward); fftw_destroy_plan(plan_backward); free(in); free(apex); fftw_free(out); fftw_free(apex_f); return 0; }
static void read_url_file( char* url_file ) { FILE* fp; char line[5000], hostname[5000]; char* get = "GET "; int get_len = strlen( get ); char* post = "POST "; int post_len = strlen( post ); char* body_start = "BODY_START"; char* body_end = "BODY_END"; char* http = "http://"; int http_len = strlen( http ); #ifdef USE_SSL char* https = "https://"; int https_len = strlen( https ); #endif int proto_len, host_len, method_len, is_body = 0; char* cp; fp = fopen( url_file, "r" ); if ( fp == (FILE*) 0 ) { perror( url_file ); exit( 1 ); } max_urls = 100; urls = (url*) malloc_check( max_urls * sizeof(url) ); num_urls = 0; while ( fgets( line, sizeof(line), fp ) != (char*) 0 ) { /* Nuke trailing newline. */ if ( line[strlen( line ) - 1] == '\n' ) line[strlen( line ) - 1] = '\0'; if ((is_body == 0) && (strncasecmp(body_start, line, strlen(body_start)) == 0 ) && ( num_urls > 0 )) { is_body = 1; continue; } else if ((is_body == 1) && (strncasecmp(body_end, line, strlen(body_end)) == 0 ) && ( num_urls > 0 )) { is_body = 0; continue; } else if (is_body == 1) { int idx = num_urls - 1; urls[idx].req_body = (char*) realloc_check( (void*) urls[idx].req_body, urls[idx].req_body_len + strlen(line)); memcpy(urls[idx].req_body + urls[idx].req_body_len, line, strlen(line)); urls[idx].req_body_len += strlen(line); continue; } is_body = 0; /* Check for room in urls. */ if ( num_urls >= max_urls ) { max_urls *= 2; urls = (url*) realloc_check( (void*) urls, max_urls * sizeof(url) ); } /* Add to table. */ urls[num_urls].url_str = strdup_check( line ); urls[num_urls].req_body = NULL; urls[num_urls].req_body_len = 0; /* Parse it. */ if ( strncasecmp(get, line, get_len) == 0 ) { method_len = get_len; urls[num_urls].method = METHOD_GET; } else if ( strncasecmp(post, line, post_len) == 0 ) { method_len = post_len; urls[num_urls].method = METHOD_POST; } else { (void) fprintf( stderr, "%s: unknown method name - %s\n", argv0, line ); exit( 1 ); } if ( strncmp( http, line + method_len, http_len ) == 0 ) { proto_len = http_len; urls[num_urls].protocol = PROTO_HTTP; } #ifdef USE_SSL else if ( strncmp( https, line + post_len, https_len ) == 0 ) { proto_len = https_len; urls[num_urls].protocol = PROTO_HTTPS; } #endif else { (void) fprintf( stderr, "%s: unknown protocol - %s\n", argv0, line ); exit( 1 ); } for ( cp = line + proto_len + method_len; *cp != '\0' && *cp != ':' && *cp != '/'; ++cp ) ; host_len = cp - line; host_len -= (proto_len + method_len); strncpy( hostname, line + proto_len + method_len, host_len ); hostname[host_len] = '\0'; urls[num_urls].hostname = strdup_check( hostname ); if ( *cp == ':' ) { urls[num_urls].port = (unsigned short) atoi( ++cp ); while ( *cp != '\0' && *cp != '/' ) ++cp; } else #ifdef USE_SSL if ( urls[num_urls].protocol == PROTO_HTTPS ) urls[num_urls].port = 443; else urls[num_urls].port = 80; #else urls[num_urls].port = 80; #endif if ( *cp == '\0' ) urls[num_urls].filename = strdup_check( "/" ); else urls[num_urls].filename = strdup_check( cp ); lookup_address( num_urls ); urls[num_urls].got_bytes = 0; urls[num_urls].got_checksum = 0; ++num_urls; } }
void cmd_cnew(const char *e_line, command *commands) { xmlNodePtr db_node = NULL; xmlChar *name = NULL, *description = NULL; char *created = NULL; char *line = NULL; unsigned long int idx = 0; #ifndef _READLINE int e_count = 0; #endif /* this is unused in this function */ commands = NULL; if ((idx = count_elements(keychain->parent->children)) >= ITEMS_MAX - 1) { dprintf(STDERR_FILENO, "ERROR: Can not create the keychain: maximum number of keychains reached, %lu.\n", ITEMS_MAX - 1); return; } line = strdup(e_line); malloc_check(line); strtok(line, " "); /* remove the command from the line */ name = BAD_CAST strtok(NULL, " "); /* assign the command's first parameter (name) */ if (name) { name = xmlStrdup(name); } else { /* if we didn't get a name as a parameter */ strlcpy(prompt_context, "NEW keychain name", sizeof(prompt_context)); #ifndef _READLINE /* disable history temporarily */ if (el_set(e, EL_HIST, history, NULL) != 0) { perror("ERROR: el_set(EL_HIST)"); } e_line = el_gets(e, &e_count); /* re-enable history */ if (el_set(e, EL_HIST, history, eh) != 0) { perror("ERROR: el_set(EL_HIST)"); } #else e_line = readline(prompt_str()); #endif if (e_line) { name = xmlStrdup(BAD_CAST e_line); malloc_check(name); #ifndef _READLINE name[xmlStrlen(name) - 1] = '\0'; /* remove the newline */ #else free((char *)e_line); e_line = NULL; #endif } else { #ifndef _READLINE el_reset(e); #endif strlcpy(prompt_context, "", sizeof(prompt_context)); return; } } free(line); line = NULL; strlcpy(prompt_context, "NEW keychain description", sizeof(prompt_context)); #ifndef _READLINE /* disable history temporarily */ if (el_set(e, EL_HIST, history, NULL) != 0) { perror("ERROR: el_set(EL_HIST)"); } e_line = el_gets(e, &e_count); /* re-enable history */ if (el_set(e, EL_HIST, history, eh) != 0) { perror("ERROR: el_set(EL_HIST)"); } #else e_line = readline(prompt_str()); #endif if (e_line) { description = xmlStrdup(BAD_CAST e_line); malloc_check(description); #ifndef _READLINE description[xmlStrlen(description) - 1] = '\0'; /* remove the newline */ #else free((char *)e_line); e_line = NULL; #endif } else { #ifndef _READLINE el_reset(e); #endif strlcpy(prompt_context, "", sizeof(prompt_context)); return; } strlcpy(prompt_context, "", sizeof(prompt_context)); db_node = find_keychain(name, 1); if (!db_node) { created = malloc(TIME_MAXLEN); malloc_check(created); snprintf(created, TIME_MAXLEN, "%d", (int)time(NULL)); /* XXX reloading a saved document inserts a 'text' element between each visible node (why?) * so we must reproduce this */ xmlAddChild(keychain->parent, xmlNewText(BAD_CAST "\t")); db_node = xmlNewChild(keychain->parent, NULL, BAD_CAST "keychain", NULL); xmlNewProp(db_node, BAD_CAST "name", name); xmlNewProp(db_node, BAD_CAST "created", BAD_CAST created); xmlNewProp(db_node, BAD_CAST "modified", BAD_CAST created); xmlNewProp(db_node, BAD_CAST "description", description); /* make the XML document prettttyyy */ xmlAddChild(db_node, xmlNewText(BAD_CAST "\n\t")); printf("Created keychain: %lu. %s\n", idx, name); /* XXX reloading a saved document inserts a 'text' element between each visible node (why?) * so we must reproduce this */ xmlAddChild(keychain->parent, xmlNewText(BAD_CAST "\n")); db_params.dirty = 1; } else { printf("Keychain '%s' already exists!\n", name); } xmlFree(name); name = NULL; xmlFree(description); description = NULL; free(created); created = NULL; } /* cmd_cnew() */
boolean AtMegaWebServer::processRequest() { client_ = server_.available(); if (!client_.connected() || !client_.available()) { return false; } #if DEBUG Serial << F("WebServer: New request:\n"); #endif if(!readLine() || !*buffer){ sendHttpResult(408); // 408 Request Time-out client_.stop(); return false; } char* start = buffer; while(isspace(*start)) start++; if (!strncmp("GET", start, 3)) { request_type_ = GET; } else if (!strncmp("POST", start, 4)) { request_type_ = POST; } else if (!strncmp("PUT", start, 3)) { request_type_ = PUT; } else if (!strncmp("DELETE", start, 6)) { request_type_ = DELETE; } else if (!strncmp("MOVE", start, 4)) { request_type_ = MOVE; }else request_type_ = UNKNOWN_REQUEST; while(*start && !isspace(*start)) start++; // end of request_type_ while(*start && isspace(*start)) start++; // skip spaces, begin of path unescapeChars(start); // decode %-sequences of path char *end = start; while(*end && !isspace(*end)) end++; // end of path path_ = (char*) malloc_check(end - start + 1); if (path_) { memcpy(path_, start, end - start); path_[end - start] = 0; } boolean found = false, success = false; while(readLine()){ if(!*buffer){ success = true; // there are 2 x CRLF at end of header break; } found |= assignHeaderValue(); } // if found == true: at least 1 header value could be assigned // success indicates that there 2 x CRLF at end, so every thing is fine // if not you can sendHttpResult(404); or try to find a handler, maybe the 1st line // has been correct. If this fails sendHttpResult(404); // is called anyhow // Header processing finished. Identify the handler to call. boolean should_close = true; found = false; for (int i = 0; handlers_[i].path; i++) { int len = strlen(handlers_[i].path); boolean match = !strcmp(path_, handlers_[i].path); if (!match && handlers_[i].path[len - 1] == '*') { match = !strncmp(path_, handlers_[i].path, len - 1); } if (match && (handlers_[i].type == ANY || handlers_[i].type == request_type_)) { found = true; should_close = (handlers_[i].handler)(*this); break; } } if (!found) { sendHttpResult(404); } if (should_close) { client_.stop(); } freeHeaders(); free(path_); return true; }
static void read_url_file( char* url_file ) { FILE* fp; char line[5000], hostname[5000]; char* http = "http://"; int http_len = strlen( http ); #ifdef USE_SSL char* https = "https://"; int https_len = strlen( https ); #endif int proto_len, host_len; char* cp; fp = fopen( url_file, "r" ); if ( fp == (FILE*) 0 ) { perror( url_file ); exit( 1 ); } max_urls = 100; urls = (url*) malloc_check( max_urls * sizeof(url) ); num_urls = 0; while ( fgets( line, sizeof(line), fp ) != (char*) 0 ) { /* Nuke trailing newline. */ if ( line[strlen( line ) - 1] == '\n' ) line[strlen( line ) - 1] = '\0'; // printf("Parsing [%s]...\n", line); /* Check for room in urls. */ if ( num_urls >= max_urls ) { max_urls *= 2; urls = (url*) realloc_check( (void*) urls, max_urls * sizeof(url) ); } /* Add to table. */ urls[num_urls].url_str = strdup_check( line ); /* Parse it. */ if ( strncmp( http, line, http_len ) == 0 ) { proto_len = http_len; urls[num_urls].protocol = PROTO_HTTP; } #ifdef USE_SSL else if ( strncmp( https, line, https_len ) == 0 ) { proto_len = https_len; urls[num_urls].protocol = PROTO_HTTPS; } #endif else { (void) fprintf( stderr, "%s: unknown protocol - %s\n", argv0, line ); exit( 1 ); } for ( cp = line + proto_len; *cp != '\0' && *cp != ':' && *cp != '/'; ++cp ) ; host_len = cp - line; host_len -= proto_len; strncpy( hostname, line + proto_len, host_len ); hostname[host_len] = '\0'; urls[num_urls].hostname = strdup_check( hostname ); if ( *cp == ':' ) { urls[num_urls].port = (unsigned short) atoi( ++cp ); while ( *cp != '\0' && *cp != '/' ) ++cp; } else #ifdef USE_SSL if ( urls[num_urls].protocol == PROTO_HTTPS ) urls[num_urls].port = 443; else urls[num_urls].port = 80; #else urls[num_urls].port = 80; #endif if ( *cp == '\0' ) urls[num_urls].filename = strdup_check( "/" ); else urls[num_urls].filename = strdup_check( cp ); if( urls[num_urls].port != 80) continue; if( !lookup_address( num_urls )) continue; urls[num_urls].got_bytes = 0; urls[num_urls].got_checksum = 0; ++num_urls; } }
int main( int argc, char** argv ) { int argn; int start; #define START_NONE 0 #define START_PARALLEL 1 #define START_RATE 2 int start_parallel = -1, start_rate = -1; int end; #define END_NONE 0 #define END_FETCHES 1 #define END_SECONDS 2 int end_fetches = -1, end_seconds = -1; int cnum; char* url_file; char* sip_file; #ifdef RLIMIT_NOFILE struct rlimit limits; #endif /* RLIMIT_NOFILE */ fd_set rfdset; fd_set wfdset; struct timeval now; int i, r; max_connections = 64 - RESERVED_FDS; /* a guess */ #ifdef RLIMIT_NOFILE /* Try and increase the limit on # of files to the maximum. */ if ( getrlimit( RLIMIT_NOFILE, &limits ) == 0 ) { if ( limits.rlim_cur != limits.rlim_max ) { if ( limits.rlim_max == RLIM_INFINITY ) limits.rlim_cur = 8192; /* arbitrary */ else if ( limits.rlim_max > limits.rlim_cur ) limits.rlim_cur = limits.rlim_max; (void) setrlimit( RLIMIT_NOFILE, &limits ); } max_connections = limits.rlim_cur - RESERVED_FDS; } #endif /* RLIMIT_NOFILE */ /* Parse args. */ argv0 = argv[0]; argn = 1; do_checksum = do_throttle = do_verbose = do_jitter = do_proxy = 0; throttle = THROTTLE; sip_file = (char*) 0; idle_secs = IDLE_SECS; start = START_NONE; end = END_NONE; while ( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' ) { if ( strncmp( argv[argn], "-checksum", strlen( argv[argn] ) ) == 0 ) do_checksum = 1; else if ( strncmp( argv[argn], "-throttle", strlen( argv[argn] ) ) == 0 ) do_throttle = 1; else if ( strncmp( argv[argn], "-Throttle", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) { do_throttle = 1; throttle = atoi( argv[++argn] ) / 10.0; } else if ( strncmp( argv[argn], "-verbose", strlen( argv[argn] ) ) == 0 ) do_verbose = 1; else if ( strncmp( argv[argn], "-timeout", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) idle_secs = atoi( argv[++argn] ); else if ( strncmp( argv[argn], "-jitter", strlen( argv[argn] ) ) == 0 ) do_jitter = 1; else if ( strncmp( argv[argn], "-parallel", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) { start = START_PARALLEL; start_parallel = atoi( argv[++argn] ); if ( start_parallel < 1 ) { (void) fprintf( stderr, "%s: parallel must be at least 1\n", argv0 ); exit( 1 ); } if ( start_parallel > max_connections ) { (void) fprintf( stderr, "%s: parallel may be at most %d\n", argv0, max_connections ); exit( 1 ); } } else if ( strncmp( argv[argn], "-rate", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) { start = START_RATE; start_rate = atoi( argv[++argn] ); if ( start_rate < 1 ) { (void) fprintf( stderr, "%s: rate must be at least 1\n", argv0 ); exit( 1 ); } if ( start_rate > 1000 ) { (void) fprintf( stderr, "%s: rate may be at most 1000\n", argv0 ); exit( 1 ); } } else if ( strncmp( argv[argn], "-fetches", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) { end = END_FETCHES; end_fetches = atoi( argv[++argn] ); if ( end_fetches < 1 ) { (void) fprintf( stderr, "%s: fetches must be at least 1\n", argv0 ); exit( 1 ); } } else if ( strncmp( argv[argn], "-seconds", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) { end = END_SECONDS; end_seconds = atoi( argv[++argn] ); if ( end_seconds < 1 ) { (void) fprintf( stderr, "%s: seconds must be at least 1\n", argv0 ); exit( 1 ); } } else if ( strncmp( argv[argn], "-sip", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) sip_file = argv[++argn]; #ifdef USE_SSL else if ( strncmp( argv[argn], "-cipher", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) { cipher = argv[++argn]; if ( strcasecmp( cipher, "fastsec" ) == 0 ) cipher = "RC4-MD5"; else if ( strcasecmp( cipher, "highsec" ) == 0 ) cipher = "DES-CBC3-SHA"; else if ( strcasecmp( cipher, "paranoid" ) == 0 ) cipher = "AES256-SHA"; } #endif /* USE_SSL */ else if ( strncmp( argv[argn], "-proxy", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) { char* colon; do_proxy = 1; proxy_hostname = argv[++argn]; colon = strchr( proxy_hostname, ':' ); if ( colon == (char*) 0 ) proxy_port = 80; else { proxy_port = (unsigned short) atoi( colon + 1 ); *colon = '\0'; } } else usage(); ++argn; } if ( argn + 1 != argc ) usage(); if ( start == START_NONE || end == END_NONE ) usage(); if ( do_jitter && start != START_RATE ) usage(); url_file = argv[argn]; /* Read in and parse the URLs. */ printf("Loading url file..."); read_url_file( url_file ); printf("Total %d urls loaded.\n", num_urls); /* Read in the source IP file, if specified. */ if ( sip_file != (char*) 0 ) read_sip_file( sip_file ); /* Initialize the connections table. */ if ( start == START_PARALLEL ) max_connections = start_parallel; connections = (connection*) malloc_check( max_connections * sizeof(connection) ); for ( cnum = 0; cnum < max_connections; ++cnum ) connections[cnum].conn_state = CNST_FREE; num_connections = max_parallel = 0; /* Initialize the HTTP status-code histogram. */ for ( i = 0; i < 1000; ++i ) http_status_counts[i] = 0; /* Initialize the statistics. */ fetches_started = 0; connects_completed = 0; responses_completed = 0; fetches_completed = 0; total_bytes = 0; total_connect_usecs = 0; max_connect_usecs = 0; min_connect_usecs = 1000000000L; total_response_usecs = 0; max_response_usecs = 0; min_response_usecs = 1000000000L; total_timeouts = 0; total_badbytes = 0; total_badchecksums = 0; /* Initialize the random number generator. */ #ifdef HAVE_SRANDOMDEV srandomdev(); #else srandom( (int) time( (time_t*) 0 ) ^ getpid() ); #endif /* Initialize the rest. */ tmr_init(); (void) gettimeofday( &now, (struct timezone*) 0 ); start_at = now; if ( do_verbose ) (void) tmr_create( &now, progress_report, JunkClientData, PROGRESS_SECS * 1000L, 1 ); if ( start == START_RATE ) { start_interval = 1000L / start_rate; if ( do_jitter ) { low_interval = start_interval * 9 / 10; high_interval = start_interval * 11 / 10; range_interval = high_interval - low_interval + 1; } (void) tmr_create( &now, start_timer, JunkClientData, start_interval, ! do_jitter ); } if ( end == END_SECONDS ) (void) tmr_create( &now, end_timer, JunkClientData, end_seconds * 1000L, 0 ); (void) signal( SIGPIPE, SIG_IGN ); /* Main loop. */ for (;;) { if ( end == END_FETCHES && fetches_completed >= end_fetches ) finish( &now ); if ( start == START_PARALLEL ) { /* See if we need to start any new connections; but at most 10. */ for ( i = 0; i < 10 && num_connections < start_parallel && ( end != END_FETCHES || fetches_started < end_fetches ); ++i ) { start_connection( &now ); (void) gettimeofday( &now, (struct timezone*) 0 ); tmr_run( &now ); } } /* Build the fdsets. */ FD_ZERO( &rfdset ); FD_ZERO( &wfdset ); for ( cnum = 0; cnum < max_connections; ++cnum ) switch ( connections[cnum].conn_state ) { case CNST_CONNECTING: FD_SET( connections[cnum].conn_fd, &wfdset ); break; case CNST_HEADERS: case CNST_READING: FD_SET( connections[cnum].conn_fd, &rfdset ); break; } r = select( FD_SETSIZE, &rfdset, &wfdset, (fd_set*) 0, tmr_timeout( &now ) ); if ( r < 0 ) { perror( "select" ); exit( 1 ); } (void) gettimeofday( &now, (struct timezone*) 0 ); /* Service them. */ for ( cnum = 0; cnum < max_connections; ++cnum ) switch ( connections[cnum].conn_state ) { case CNST_CONNECTING: if ( FD_ISSET( connections[cnum].conn_fd, &wfdset ) ) handle_connect( cnum, &now, 1 ); break; case CNST_HEADERS: case CNST_READING: if ( FD_ISSET( connections[cnum].conn_fd, &rfdset ) ) handle_read( cnum, &now ); break; } /* And run the timers. */ tmr_run( &now ); } /* NOT_REACHED */ }
static void* realloc_check(void* oldmem, size_t bytes, const void *caller) { INTERNAL_SIZE_T nb; void* newmem = 0; unsigned char *magic_p; if (bytes+1 == 0) { __set_errno (ENOMEM); return NULL; } if (oldmem == 0) return malloc_check(bytes, NULL); if (bytes == 0) { free_check (oldmem, NULL); return NULL; } (void)mutex_lock(&main_arena.mutex); const mchunkptr oldp = mem2chunk_check(oldmem, &magic_p); (void)mutex_unlock(&main_arena.mutex); if(!oldp) { malloc_printerr(check_action, "realloc(): invalid pointer", oldmem); return malloc_check(bytes, NULL); } const INTERNAL_SIZE_T oldsize = chunksize(oldp); checked_request2size(bytes+1, nb); (void)mutex_lock(&main_arena.mutex); if (chunk_is_mmapped(oldp)) { #if HAVE_MREMAP mchunkptr newp = mremap_chunk(oldp, nb); if(newp) newmem = chunk2mem(newp); else #endif { /* Note the extra SIZE_SZ overhead. */ if(oldsize - SIZE_SZ >= nb) newmem = oldmem; /* do nothing */ else { /* Must alloc, copy, free. */ if (top_check() >= 0) newmem = _int_malloc(&main_arena, bytes+1); if (newmem) { MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ); munmap_chunk(oldp); } } } } else { if (top_check() >= 0) { INTERNAL_SIZE_T nb; checked_request2size(bytes + 1, nb); newmem = _int_realloc(&main_arena, oldp, oldsize, nb); } } /* mem2chunk_check changed the magic byte in the old chunk. If newmem is NULL, then the old chunk will still be used though, so we need to invert that change here. */ if (newmem == NULL) *magic_p ^= 0xFF; (void)mutex_unlock(&main_arena.mutex); return mem2mem_check(newmem, bytes); }
int parse (char* file_name) { FILE *file_pointer; int line_size = 4096; int line_length = 0; int token_length = 0; int prepend_length = 0; char *token; char *prepend = NULL; char *temp1; char *temp2; keys = vector_new(); values = vector_new(); // malloc the buffer, necessary for getline char *buffer; buffer = (char *) malloc(line_size * sizeof(char)); malloc_check(buffer); // Open the file if ((file_pointer = fopen(file_name, "r")) == NULL ) { fprintf(stderr, "can't open %s\n", file_name); return EXIT_FAILURE; } // Begin Reading the File int is_a_key; int saved_key_value; while (line_length > -1) { // while not EOF is_a_key = FALSE; saved_key_value = FALSE; line_length = getline(&buffer, &line_size, file_pointer); if (line_length > 1) { // if not an empty line token = strtok(buffer, DELIMITERS); if (token[0] != 35) { // if first token doesn't start with # while (token != NULL) { token_length = strlen(token); if (token[token_length-1] == 58) { // we have a key token[token_length-1] = '\0'; // erase the last ':' is_a_key = TRUE; if (prepend == NULL) { temp1 = (char *) malloc(token_length * sizeof(char)); malloc_check(temp1); strcpy(temp1, token); } else { // prepend the key name temp1 = (char *) malloc((token_length+strlen(prepend)) * sizeof(char)); malloc_check(temp1); strcpy(temp1, prepend); strcat(temp1, token); } } token = strtok(NULL, DELIMITERS); if (token != NULL) { // if there is another token if (is_a_key) { // if the previous token was a key save the pair token_length = strlen(token); temp2 = (char *) malloc(token_length * sizeof(char)); malloc_check(temp2); strcpy(temp2, token); vector_addItem(keys, temp1); vector_addItem(values, temp2); saved_key_value = TRUE; } else { free(temp1); break; // don't need the rest of the line } } if (!saved_key_value) { // we have a prepend if (prepend == NULL) prepend = (char *) malloc((token_length+1) * sizeof(char)); else { prepend_length = strlen(prepend); prepend = (char *) realloc(prepend, (token_length+prepend_length+1) * sizeof(char)); } malloc_check(prepend); strcpy(prepend, temp1); prepend_length = strlen(prepend); prepend[strlen(prepend)] = '.'; // add a . prepend[strlen(prepend)] = '\0'; } } } } else { // if this is an empty line if (prepend != NULL) { free(prepend); prepend = NULL; } } } // while !EOF // Close and Exit fclose(file_pointer); //int i; //for (i=0; i<vector_size(keys); i++) { // printf("V(%i)=\"%s\",\"%s\"\n", i, // (char*) vector_getItem(keys, i), // (char*) vector_getItem(values, i)); //} parsed = TRUE; return EXIT_SUCCESS; }