int main(int argc, char **argv) { Images images; #ifdef HAS_ENCODER int mode = 0; // 0 = encode, 1 = decode, 2 = transcode flifEncodingOptional method; int learn_repeats = -1; int acb = -1; // try auto color buckets int frame_delay = 100; int palette_size = -1; int lookback = 1; int divisor=CONTEXT_TREE_COUNT_DIV; int min_size=CONTEXT_TREE_MIN_SUBTREE_SIZE; int split_threshold=CONTEXT_TREE_SPLIT_THRESHOLD; int yiq = 1; int plc = 1; bool alpha_zero_special = true; #else int mode = 1; #endif int quality = 100; // 100 = everything, positive value: partial decode, negative value: only rough data int scale = 1; bool showhelp = false; if (strcmp(argv[0],"flif") == 0) mode = 0; if (strcmp(argv[0],"dflif") == 0) mode = 1; if (strcmp(argv[0],"deflif") == 0) mode = 1; if (strcmp(argv[0],"decflif") == 0) mode = 1; static struct option optlist[] = { {"help", 0, NULL, 'h'}, {"decode", 0, NULL, 'd'}, {"verbose", 0, NULL, 'v'}, {"quality", 1, NULL, 'q'}, {"scale", 1, NULL, 's'}, {"identify", 1, NULL, 'I'}, #ifdef HAS_ENCODER {"encode", 0, NULL, 'e'}, {"transcode", 0, NULL, 't'}, {"interlace", 0, NULL, 'i'}, {"no-interlace", 0, NULL, 'n'}, {"acb", 0, NULL, 'a'}, {"no-acb", 0, NULL, 'b'}, {"palette", 1, NULL, 'p'}, {"repeats", 1, NULL, 'r'}, {"frame-delay", 1, NULL, 'f'}, {"lookback", 1, NULL, 'l'}, {"divisor", 1, NULL, 'D'}, {"min-size", 1, NULL, 'M'}, {"split-threshold", 1, NULL, 'S'}, {"rgb", 0, NULL, 'R'}, {"no-plc", 0, NULL, 'C'}, {"keep-alpha-zero", 0, NULL, 'A'}, #endif {0, 0, 0, 0} }; int i,c; #ifdef HAS_ENCODER while ((c = getopt_long (argc, argv, "hedtvIinabq:s:p:r:f:l:D:M:S:RCA", optlist, &i)) != -1) { #else while ((c = getopt_long (argc, argv, "hdvIq:s:", optlist, &i)) != -1) { #endif switch (c) { case 'd': mode=1; break; case 'v': increase_verbosity(); break; case 'q': quality=atoi(optarg); if (quality < 0 || quality > 100) {e_printf("Not a sensible number for option -q\n"); return 1; } break; case 's': scale=atoi(optarg); if (scale < 1 || scale > 128) {e_printf("Not a sensible number for option -s\n"); return 1; } break; case 'I': scale = -1; break; #ifdef HAS_ENCODER case 'e': mode=0; break; case 't': mode=2; break; case 'i': method.encoding=flifEncoding::interlaced; break; case 'n': method.encoding=flifEncoding::nonInterlaced; break; case 'a': acb=1; break; case 'b': acb=0; break; case 'p': palette_size=atoi(optarg); if (palette_size < 0 || palette_size > 30000) {e_printf("Not a sensible number for option -p\n"); return 1; } if (palette_size == 0) {v_printf(2,"Palette disabled\n"); } break; case 'r': learn_repeats=atoi(optarg); if (learn_repeats < 0 || learn_repeats > 20) {e_printf("Not a sensible number for option -r\n"); return 1; } break; case 'f': frame_delay=atoi(optarg); if (frame_delay < 0 || frame_delay > 60000) {e_printf("Not a sensible number for option -f\n"); return 1; } break; case 'l': lookback=atoi(optarg); if (lookback < -1 || lookback > 256) {e_printf("Not a sensible number for option -l\n"); return 1; } break; case 'D': divisor=atoi(optarg); if (divisor <= 0 || divisor > 0xFFFFFFF) {e_printf("Not a sensible number for option -D\n"); return 1; } break; case 'M': min_size=atoi(optarg); if (min_size < 0 || min_size > CONTEXT_TREE_MAX_COUNT) {e_printf("Not a sensible number for option -M\n"); return 1; } break; case 'S': split_threshold=atoi(optarg); if (split_threshold <= 0 || split_threshold > 100000) {e_printf("Not a sensible number for option -S\n"); return 1; } split_threshold *= 5461; break; case 'R': yiq=0; break; case 'C': plc=0; break; case 'A': alpha_zero_special=false; break; #endif case 'h': showhelp=true; break; default: show_help(); return 0; } } argc -= optind; argv += optind; show_banner(); if (argc == 0 || showhelp) { //e_printf("Input file missing.\n"); if (get_verbosity() == 1 || showhelp) show_help(); return 1; } if (argc == 1 && scale != -1) { show_help(); e_printf("\nOutput file missing.\n"); return 1; } if (scale == -1) mode = 1; if (file_exists(argv[0])) { char *f = strrchr(argv[0],'/'); char *ext = f ? strrchr(f,'.') : strrchr(argv[0],'.'); #ifdef HAS_ENCODER if (mode == 0 && file_is_flif(argv[0])) { char *f = strrchr(argv[1],'/'); char *ext = f ? strrchr(f,'.') : strrchr(argv[1],'.'); if (check_compatible_extension(ext)) { v_printf(3,"Input file is a FLIF file, adding implicit -d\n"); mode = 1; } else if ((ext && ( !strcasecmp(ext,".flif") || ( !strcasecmp(ext,".flf") )))) { v_printf(3,"Input and output file are both FLIF file, adding implicit -t\n"); mode = 2; } } if (mode != 0) { #endif if (!(ext && ( !strcasecmp(ext,".flif") || ( !strcasecmp(ext,".flf") )))) { e_printf("Warning: expected file name extension \".flif\" for input file, trying anyway...\n"); } #ifdef HAS_ENCODER } else { if (!check_compatible_extension(ext)) { e_printf("Warning: expected \".png\", \".pnm\" or \".pam\" file name extension for input file, trying anyway...\n"); } } #endif } else if (argc>0) { e_printf("Input file does not exist: %s\n",argv[0]); return 1; } if (mode > 0 && argc > 2 && scale != -1) { e_printf("Too many arguments.\n"); return 1; } #ifdef HAS_ENCODER if (mode == 0) { if (!handle_encode(argc, argv, images, palette_size, acb, method, lookback, learn_repeats, frame_delay, divisor, min_size, split_threshold, yiq, plc, alpha_zero_special)) return 2; } else if (mode == 1) { #endif return handle_decode(argc, argv, images, quality, scale); #ifdef HAS_ENCODER } else if (mode == 2) { if (scale > 1) {e_printf("Not yet supported: transcoding downscaled image; use decode + encode!\n");} if (!decode_flif(argv, images, quality, scale)) return 2; argc--; argv++; if (!encode_flif(argc, argv, images, palette_size, acb, method, lookback, learn_repeats, frame_delay, divisor, min_size, split_threshold, yiq, plc)) return 2; } #endif return 0; }
void pixbuf_init (void) { if (file_exists ("../gdk-pixbuf/libpixbufloader-pnm.la")) g_setenv ("GDK_PIXBUF_MODULE_FILE", "../gdk-pixbuf/gdk-pixbuf.loaders", TRUE); }
static void inquire_via_filename (st_parameter_inquire *iqp) { const char *p; GFC_INTEGER_4 cf = iqp->common.flags; if ((cf & IOPARM_INQUIRE_HAS_EXIST) != 0) *iqp->exist = file_exists (iqp->file, iqp->file_len); if ((cf & IOPARM_INQUIRE_HAS_OPENED) != 0) *iqp->opened = 0; if ((cf & IOPARM_INQUIRE_HAS_NUMBER) != 0) *iqp->number = -1; if ((cf & IOPARM_INQUIRE_HAS_NAMED) != 0) *iqp->named = 1; if ((cf & IOPARM_INQUIRE_HAS_NAME) != 0) fstrcpy (iqp->name, iqp->name_len, iqp->file, iqp->file_len); if ((cf & IOPARM_INQUIRE_HAS_ACCESS) != 0) cf_strcpy (iqp->access, iqp->access_len, undefined); if ((cf & IOPARM_INQUIRE_HAS_SEQUENTIAL) != 0) { p = "UNKNOWN"; cf_strcpy (iqp->sequential, iqp->sequential_len, p); } if ((cf & IOPARM_INQUIRE_HAS_DIRECT) != 0) { p = "UNKNOWN"; cf_strcpy (iqp->direct, iqp->direct_len, p); } if ((cf & IOPARM_INQUIRE_HAS_FORM) != 0) cf_strcpy (iqp->form, iqp->form_len, undefined); if ((cf & IOPARM_INQUIRE_HAS_FORMATTED) != 0) { p = "UNKNOWN"; cf_strcpy (iqp->formatted, iqp->formatted_len, p); } if ((cf & IOPARM_INQUIRE_HAS_UNFORMATTED) != 0) { p = "UNKNOWN"; cf_strcpy (iqp->unformatted, iqp->unformatted_len, p); } if ((cf & IOPARM_INQUIRE_HAS_RECL_OUT) != 0) *iqp->recl_out = 0; if ((cf & IOPARM_INQUIRE_HAS_NEXTREC) != 0) *iqp->nextrec = 0; if ((cf & IOPARM_INQUIRE_HAS_BLANK) != 0) cf_strcpy (iqp->blank, iqp->blank_len, undefined); if ((cf & IOPARM_INQUIRE_HAS_PAD) != 0) cf_strcpy (iqp->pad, iqp->pad_len, undefined); if (cf & IOPARM_INQUIRE_HAS_FLAGS2) { GFC_INTEGER_4 cf2 = iqp->flags2; if ((cf2 & IOPARM_INQUIRE_HAS_ENCODING) != 0) cf_strcpy (iqp->encoding, iqp->encoding_len, undefined); if ((cf2 & IOPARM_INQUIRE_HAS_DELIM) != 0) cf_strcpy (iqp->delim, iqp->delim_len, undefined); if ((cf2 & IOPARM_INQUIRE_HAS_DECIMAL) != 0) cf_strcpy (iqp->decimal, iqp->decimal_len, undefined); if ((cf2 & IOPARM_INQUIRE_HAS_DELIM) != 0) cf_strcpy (iqp->delim, iqp->delim_len, undefined); if ((cf2 & IOPARM_INQUIRE_HAS_PAD) != 0) cf_strcpy (iqp->pad, iqp->pad_len, undefined); if ((cf2 & IOPARM_INQUIRE_HAS_ENCODING) != 0) cf_strcpy (iqp->encoding, iqp->encoding_len, undefined); if ((cf2 & IOPARM_INQUIRE_HAS_SIZE) != 0) *iqp->size = file_size (iqp->file, iqp->file_len); if ((cf2 & IOPARM_INQUIRE_HAS_IQSTREAM) != 0) cf_strcpy (iqp->iqstream, iqp->iqstream_len, "UNKNOWN"); } if ((cf & IOPARM_INQUIRE_HAS_POSITION) != 0) cf_strcpy (iqp->position, iqp->position_len, undefined); if ((cf & IOPARM_INQUIRE_HAS_ACCESS) != 0) cf_strcpy (iqp->access, iqp->access_len, undefined); if ((cf & IOPARM_INQUIRE_HAS_READ) != 0) { p = inquire_read (iqp->file, iqp->file_len); cf_strcpy (iqp->read, iqp->read_len, p); } if ((cf & IOPARM_INQUIRE_HAS_WRITE) != 0) { p = inquire_write (iqp->file, iqp->file_len); cf_strcpy (iqp->write, iqp->write_len, p); } if ((cf & IOPARM_INQUIRE_HAS_READWRITE) != 0) { p = inquire_read (iqp->file, iqp->file_len); cf_strcpy (iqp->readwrite, iqp->readwrite_len, p); } }
static GuiWidget *create_widget_list(GuiWidget *parent_widget, xmlNodePtr root) { GuiWidget *widget = NULL, *first_widget = NULL; xmlNodePtr cur = XML_GET_CHILD(root); while(cur != NULL) { if ( xmlStrcmp(cur->name, WIDGET_STR) == 0 ) { xmlChar *widget_name = xmlGetProp(cur, NAME_STR ); xmlChar *classid = xmlGetProp(cur, CLASS_STR); xmlChar *widget_style = xmlGetProp(cur, STYLE_STR); // printf("XmlParser: widget_name=%s\n",(char *)widget_name); widget = widget_new_child(parent_widget, (char *)widget_name, (char *)classid, (char *)widget_style); if (widget_name) xmlFree(widget_name); if (classid) xmlFree(classid); if (widget_style) xmlFree(widget_style); if (widget == NULL) goto next; if (first_widget == NULL) first_widget = widget; xmlNodePtr node = XML_GET_CHILD(cur); while (node != NULL) { if ( xmlStrcmp(node->name, PROPERTY_STR) == 0 ) { xmlChar *key = xmlGetProp(node, NAME_STR); xmlChar *value = xmlGetProp(node, VALUE_STR);//xmlNodeGetContent(node); if (xmlStrcmp(key, (xmlChar*)"tabstop") == 0) widget->tabstop= atoidef((char *)value, 1); else widget_set_property(widget, (char *)key, (char *)value); if (key) xmlFree(key); if (value) xmlFree(value); } else if (xmlStrcmp(node->name, SIGNAL_STR) == 0 ) { xmlChar *name = xmlGetProp(node, NAME_STR); xmlChar *handler = xmlGetProp(node, HANDLER_STR); signal_new(widget, (char *)name, (char *)handler); if (name) xmlFree(name); if (handler) xmlFree(handler); } else if (xmlStrcmp(node->name, CHILDREN_STR) == 0 ) create_widget_list(widget, node); node = node->next; } } else if ( xmlStrcmp(cur->name, FILES_STR) == 0 ) { int i=0; gui->search_num = 0; xmlNodePtr node = XML_GET_CHILD(cur); while (node != NULL) { if (xmlStrcmp(node->name, SEARCH_STR) == 0) gui->search_num++; node = node->next; } gui->search_path = (char **)malloc(sizeof(char*) *gui->search_num + 1); node = XML_GET_CHILD(cur); while (node != NULL) { if (xmlStrcmp(node->name, SEARCH_STR) == 0) gui->search_path[i++] = strdup( (char *)xmlGetProp(node, PATH_STR) ); node = node->next; } gui->search_path[i] = NULL; node = XML_GET_CHILD(cur); while (node != NULL) { if (xmlStrcmp(node->name, FONT_STR) == 0) { xmlChar *font_name = xmlGetProp(node, NAME_STR); xmlChar *file_name = xmlGetProp(node, FILE_STR); if (file_name && font_name) create_fontdesc((char *)font_name, (char *)file_name); if (file_name) xmlFree(file_name); if (font_name) xmlFree(font_name); } else if (xmlStrcmp(node->name, IMAGE_STR) == 0) { xmlChar *image_name = xmlGetProp(node, NAME_STR); xmlChar* file_name = xmlGetProp(node, FILE_STR); if (file_name && image_name) create_imagedesc((char *)image_name, (char *)file_name); if (file_name) xmlFree(file_name); if (image_name) xmlFree(image_name); } node = node->next; } } else if ( xmlStrcmp(cur->name, I18N_STR) == 0 ) { xmlNodePtr node = XML_GET_CHILD(cur); while (node != NULL) { GuiI18n *i18n; if (xmlStrcmp(node->name, LANGUAGE_STR) == 0) { xmlChar *language = xmlGetProp(node, NAME_STR); if (language) { i18n = i18n_add_language((char *)language); xmlFree(language); if (i18n) { xmlNodePtr text_node = XML_GET_CHILD(node); while (text_node != NULL) { if (xmlStrcmp(text_node->name, TRAN_STR) == 0) { xmlChar *key = xmlGetProp(text_node, ID_STR); xmlChar *value = xmlNodeGetContent(text_node); i18n_add_tran(i18n, (char *)key, (char *)value); if (key) xmlFree(key); if (value) xmlFree(value); } text_node = text_node->next; } } } } node = node->next; } } else if ( xmlStrcmp(cur->name, THEMES_STR) == 0) { xmlNodePtr node = XML_GET_CHILD(cur); while (node != NULL) { if (xmlStrcmp(node->name, THEME_STR) == 0) { Theme *theme = (Theme *)malloc(sizeof(Theme)); if (theme == NULL) { printf("memory out\n"); node = node->next; continue; } char *filename = (char *)xmlGetProp(node, FILE_STR); if (file_exists(filename) == -1) { char *oldfile = filename; filename = gui_search_file(filename); free(oldfile); } if (filename) { xmlChar *theme_name = xmlGetProp(node, NAME_STR); if (theme_load(theme, filename) == 0) { if (gui->current_theme == NULL) gui->current_theme = theme; hash_add(gui->theme_hash, (char *)theme_name, theme); } xmlFree(theme_name); free(filename); } } node = node->next; } } next: cur = cur->next; } return first_widget; }
void button::load_images() { std::string size_postfix; switch (location().h) { case 25: size_postfix = "_25"; break; case 30: size_postfix = "_30"; break; case 60: size_postfix = "_60"; break; default: break; } surface button_image(image::get_image(button_image_name_ + ".png")); surface pressed_image(image::get_image(button_image_name_ + "-pressed.png")); surface active_image(image::get_image(button_image_name_ + "-active.png")); surface disabled_image; if (file_exists(game_config::path + "/images/" + button_image_name_ + "-disabled.png")) disabled_image.assign((image::get_image(button_image_name_ + "-disabled.png"))); surface pressed_disabled_image, pressed_active_image, touched_image; static const Uint32 disabled_btn_color = 0xAAAAAA; static const double disabled_btn_adjust = 0.18; if (!button_overlay_image_name_.empty()) { overlayImage_.assign(image::get_image(button_overlay_image_name_ + size_postfix + ".png")); overlayPressedImage_.assign(image::get_image(button_overlay_image_name_ + size_postfix + "-pressed.png")); if (file_exists(game_config::path + "/images/" + button_overlay_image_name_ + size_postfix + "-active.png")) overlayActiveImage_.assign(image::get_image(button_overlay_image_name_ + size_postfix + "-active.png")); if (file_exists(game_config::path + "/images/" + button_overlay_image_name_ + size_postfix + "-pressed-disabled.png")) overlayPressedDisabledImage_.assign(image::get_image(button_overlay_image_name_ + size_postfix + "-pressed-disabled.png")); if (file_exists(game_config::path + "/images/" + button_overlay_image_name_ + "_30-disabled.png")) overlayDisabledImage_.assign(image::get_image(button_overlay_image_name_ + "_30-disabled.png")); if (overlayDisabledImage_.null()) overlayDisabledImage_ = blend_surface(greyscale_image(overlayImage_), disabled_btn_adjust, disabled_btn_color); if (overlayPressedDisabledImage_.null()) overlayPressedDisabledImage_ = blend_surface(greyscale_image(overlayPressedImage_), disabled_btn_adjust, disabled_btn_color); } else { overlayImage_.assign(NULL); } if (disabled_image == NULL) { disabled_image = blend_surface(greyscale_image(button_image), disabled_btn_adjust, disabled_btn_color); } if (pressed_image.null()) pressed_image.assign(button_image); if (active_image.null()) active_image.assign(button_image); if (type_ == TYPE_CHECK || type_ == TYPE_RADIO) { touched_image.assign(image::get_image(button_image_name_ + "-touched.png")); if (touched_image.null()) touched_image.assign(pressed_image); pressed_active_image.assign(image::get_image(button_image_name_ + "-active-pressed.png")); if (pressed_active_image.null()) pressed_active_image.assign(pressed_image); pressed_disabled_image.assign(image::get_image(button_image_name_ + "-disabled-pressed.png")); if (pressed_disabled_image.null()) pressed_disabled_image = blend_surface(greyscale_image(pressed_image), disabled_btn_adjust, disabled_btn_color); } if (button_image.null()) { ERR_DP << "error initializing button!\n"; throw error(); } base_height_ = button_image->h; base_width_ = button_image->w; if (type_ != TYPE_IMAGE) { set_label(label_); } if(type_ == TYPE_PRESS || type_ == TYPE_TURBO) { image_.assign(scale_surface(button_image,location().w,location().h)); pressedImage_.assign(scale_surface(pressed_image,location().w,location().h)); activeImage_.assign(scale_surface(active_image,location().w,location().h)); disabledImage_.assign(scale_surface(disabled_image,location().w,location().h)); } else { image_.assign(scale_surface(button_image,button_image->w,button_image->h)); activeImage_.assign(scale_surface(active_image,button_image->w,button_image->h)); disabledImage_.assign(scale_surface(disabled_image,button_image->w,button_image->h)); pressedImage_.assign(scale_surface(pressed_image,button_image->w,button_image->h)); if (type_ == TYPE_CHECK || type_ == TYPE_RADIO) { pressedDisabledImage_.assign(scale_surface(pressed_disabled_image,button_image->w,button_image->h)); pressedActiveImage_.assign(scale_surface(pressed_active_image, button_image->w, button_image->h)); touchedImage_.assign(scale_surface(touched_image, button_image->w, button_image->h)); } } if (type_ == TYPE_IMAGE){ calculate_size(); } }
gboolean main_include_task(gpointer _options) { GtkRecentManager *grm = gtk_recent_manager_get_default(); GtkRecentData *data; GSList* iterator = NULL; recent_file_options_t* options = _options; unsigned added = 0; /* Total files added */ static gchar* groups[] = { NULL }; for (iterator = options->fileNames; iterator; iterator = iterator->next) { char* _fileName = (char*)iterator->data; if (!file_exists(_fileName)) { if (!options->quiet) fprintf (stderr, "Error '%s' does not exist!\n", _fileName); continue; } char* fileName = realpath(_fileName, NULL); if (fileName==NULL) { if (!options->quiet) fprintf (stderr, "Error getting '%s' path!\n", _fileName); continue; } data = g_slice_new(GtkRecentData); data->display_name=g_strdup(fileName); data->description = NULL; data->mime_type=get_mime(fileName); data->app_name = (gchar*) g_get_application_name(); data->app_exec = g_strdup("recents"); data->groups = groups; data->is_private = FALSE; gchar *uri = g_filename_to_uri(fileName, NULL, NULL); if (gtk_recent_manager_add_full(grm, uri, data)) { if (!options->quiet) printf("File '%s' added successfully\n", fileName); ++added; } if (options->touchFile) { struct utimbuf utb; time_t now = time(NULL); utb.actime = now; utb.modtime = now; if ( (utime (fileName, &utb)<0) && (!options->quiet) ) { fprintf (stderr, "Could not touch '%s' (errno: %d, %s)\n", fileName, errno, strerror(errno)); } } free(fileName); } options->result = (added == g_slist_length(options->fileNames))?0:100; gtk_main_quit(); }
//* //* ONHOLD //* //* //* MAKE NEW FOLDER //* byte auia_hold_rename(AUI_VARSP v, char *oldname) { byte redoing = 0; char new_folder_name[256]; snprintf(new_folder_name, 256, oldname); byte dispatch_ret = 1; do { redoing = 0; dispatch_ret = 1; char *ret = aw_ime(v->hWin, new_folder_name, alang_get("rename")); if (ret != NULL) { if (strlen(ret) == 0) { redoing = aw_confirm(v->hWin, alang_get("rename"), alang_get ("rename.insertname"), aui_icons(37), alang_get("tryagain"), alang_get("cancel")); } else if (strcmp(ret, oldname) == 0) { redoing = 0; } else { char *path_newfolder = NULL; aui_setpath(&path_newfolder, v->path, ret, 0); if (path_newfolder != NULL) { if (file_exists(path_newfolder)) { redoing = aw_confirm(v->hWin, alang_get ("rename"), alang_get ("rename.exist"), aui_icons (39), alang_get ("tryagain"), alang_get ("cancel")); } else { char *path_oldfolder = NULL; aui_setpath(&path_oldfolder, v->path, oldname, 0); if (path_oldfolder) { int retval = rename (path_oldfolder, path_newfolder); if (retval != -1) { dispatch_ret = 0; v->reshow = 1; snprintf(v-> selfile, 256, "%s", ret); } else { redoing = aw_confirm (v->hWin, alang_get ("rename"), alang_get ("rename.error"), aui_icons (37), alang_get ("tryagain"), alang_get ("cancel")); } free(path_oldfolder); } } free(path_newfolder); } } snprintf(new_folder_name, 256, ret); free(ret); } } while (redoing); return dispatch_ret; }
ngx_int_t passenger_content_handler(ngx_http_request_t *r) { ngx_int_t rc; ngx_http_upstream_t *u; passenger_loc_conf_t *slcf; ngx_str_t path, base_uri; u_char *path_last, *end; u_char root_path_str[NGX_MAX_PATH + 1]; ngx_str_t root_path; size_t root_len, len; u_char page_cache_file_str[NGX_MAX_PATH + 1]; ngx_str_t page_cache_file; passenger_context_t *context; PP_Error error; if (passenger_main_conf.root_dir.len == 0) { return NGX_DECLINED; } slcf = ngx_http_get_module_loc_conf(r, ngx_http_passenger_module); /* Let the next content handler take care of this request if Phusion * Passenger is disabled for this URL. */ if (!slcf->enabled) { return NGX_DECLINED; } /* Let the next content handler take care of this request if this URL * maps to an existing file. */ path_last = ngx_http_map_uri_to_path(r, &path, &root_len, 0); if (path_last != NULL && file_exists(path.data, 0)) { return NGX_DECLINED; } /* Create a string containing the root path. This path already * contains a trailing slash. */ end = ngx_copy(root_path_str, path.data, root_len); *end = '\0'; root_path.data = root_path_str; root_path.len = root_len; context = ngx_pcalloc(r->pool, sizeof(passenger_context_t)); if (context == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } ngx_http_set_ctx(r, context, ngx_http_passenger_module); /* Find the base URI for this web application, if any. */ if (find_base_uri(r, slcf, &base_uri)) { /* Store the found base URI into context->public_dir. We infer that * the 'public' directory of the web app equals document root + base URI. */ if (slcf->document_root.data != NULL) { len = slcf->document_root.len + 1; context->public_dir.data = ngx_palloc(r->pool, sizeof(u_char) * len); end = ngx_copy(context->public_dir.data, slcf->document_root.data, slcf->document_root.len); } else { len = root_path.len + base_uri.len + 1; context->public_dir.data = ngx_palloc(r->pool, sizeof(u_char) * len); end = ngx_copy(context->public_dir.data, root_path.data, root_path.len); end = ngx_copy(end, base_uri.data, base_uri.len); } *end = '\0'; context->public_dir.len = len - 1; context->base_uri = base_uri; } else { /* No base URI directives are applicable for this request. So assume that * the web application's public directory is the document root. * context->base_uri is now a NULL string. */ len = sizeof(u_char *) * (root_path.len + 1); context->public_dir.data = ngx_palloc(r->pool, len); end = ngx_copy(context->public_dir.data, root_path.data, root_path.len); *end = '\0'; context->public_dir.len = root_path.len; } /* If there's a corresponding page cache file for this URL, then serve that * file instead. */ page_cache_file.data = page_cache_file_str; page_cache_file.len = sizeof(page_cache_file_str); if (map_uri_to_page_cache_file(r, &context->public_dir, path.data, path_last - path.data, &page_cache_file)) { return passenger_static_content_handler(r, &page_cache_file); } if (slcf->app_type.data == NULL) { pp_error_init(&error); if (slcf->app_root.data == NULL) { context->app_type = pp_app_type_detector_check_document_root( pp_app_type_detector, (const char *) context->public_dir.data, context->public_dir.len, context->base_uri.len != 0, &error); } else { context->app_type = pp_app_type_detector_check_app_root( pp_app_type_detector, (const char *) slcf->app_root.data, slcf->app_root.len, &error); } if (context->app_type == PAT_NONE) { return NGX_DECLINED; } else if (context->app_type == PAT_ERROR) { if (error.errnoCode == EACCES) { ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0, "%s; This error means that the Nginx worker process (PID %d, " "running as UID %d) does not have permission to access this file. " "Please read this page to learn how to fix this problem: " "https://www.phusionpassenger.com/library/admin/nginx/troubleshooting/?a=upon-accessing-the-web-app-nginx-reports-a-permission-denied-error; Extra info", error.message, (int) getpid(), (int) getuid()); } else { ngx_log_error(NGX_LOG_ALERT, r->connection->log, (error.errnoCode == PP_NO_ERRNO) ? 0 : error.errnoCode, "%s", error.message); } pp_error_destroy(&error); return NGX_HTTP_INTERNAL_SERVER_ERROR; } } else { context->app_type = pp_get_app_type2((const char *) slcf->app_type.data, slcf->app_type.len); if (context->app_type == PAT_NONE) { return NGX_DECLINED; } } /* Setup upstream stuff and prepare sending the request to the Passenger core. */ if (ngx_http_upstream_create(r) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } u = r->upstream; u->schema = pp_schema_string; u->output.tag = (ngx_buf_tag_t) &ngx_http_passenger_module; set_upstream_server_address(u, &slcf->upstream_config); u->conf = &slcf->upstream_config; #if (NGX_HTTP_CACHE) u->create_key = create_key; #endif u->create_request = create_request; u->reinit_request = reinit_request; u->process_header = process_status_line; u->abort_request = abort_request; u->finalize_request = finalize_request; r->state = 0; u->buffering = slcf->upstream_config.buffering; u->pipe = ngx_pcalloc(r->pool, sizeof(ngx_event_pipe_t)); if (u->pipe == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } u->pipe->input_filter = ngx_event_pipe_copy_input_filter; u->pipe->input_ctx = r; rc = ngx_http_read_client_request_body(r, ngx_http_upstream_init); fix_peer_address(r); if (rc >= NGX_HTTP_SPECIAL_RESPONSE) { return rc; } return NGX_DONE; }
int main(int argc, char **argv) { const char *name; int sock = -1; char fin[512], fout[512]; char cmd[512], reply[512]; int params = -1; say ("\n%s (%s): started\n", TITLE, VERSION); if( argc == 1){ say ("No service name passed, using default: %s\nYou can also pass --quick to execute a couple of default commands for quick testing. Requires s.txt to exist. \n", NAME); sock = initializeClient(NAME); usage(); } else if (argc == 2){ if( strcmp(argv[1], "--quick") == 0){ quick = true; name=NAME; } else{ name = argv[1]; usage(); } say ("Connecting to: %s\n", name); sock = initializeClient(name); } else if (argc == 3){ if( strcmp(argv[1], "--quick") == 0 ){ quick = true; name = argv[2]; say ("Connecting to: %s\n", name); sock = initializeClient(name); usage(); } else{ die(-1, "xftp [--quick] [SID]"); } } else{ die(-1, "xftp [--quick] [SID]"); } int i = 0; // This is for quick testing with a couple of commands while(i < NUM_PROMPTS){ say(">>"); cmd[0] = '\n'; fin[0] = '\n'; fout[0] = '\n'; params = -1; if(quick){ if( i==0 ) strcpy(cmd, "put s.txt r.txt"); else if( i==1 ) strcpy(cmd, "get r.txt sr.txt\n"); i++; }else{ fgets(cmd, 511, stdin); } // enable this if you want to limit how many times this is done // i++; if (strncmp(cmd, "get", 3) == 0){ params = sscanf(cmd,"get %s %s", fin, fout); if(params !=2 ){ sprintf(reply, "FAIL: invalid command (%s)\n", cmd); warn(reply); usage(); continue; } if( strcmp(fin, fout) == 0){ warn("Since both applications write to the same folder (local case) the names should be different.\n"); continue; } getFile(sock, s_ad, s_hid, fin, fout); } else if (strncmp(cmd, "put", 3) == 0){ params = sscanf(cmd,"put %s %s", fin, fout); if(params !=2 ){ sprintf(reply, "FAIL: invalid command (%s)\n", cmd); warn(reply); usage(); continue; } if(strcmp(fin, fout) == 0){ warn("Since both applications write to the same folder (local case) the names should be different.\n"); continue; } if(!file_exists(fin)){ warn("Source file: %s doesn't exist\n", fin); continue; } putFile(sock, my_ad, my_hid, fin, fout); } else{ sprintf(reply, "FAIL: invalid command (%s)\n", cmd); warn(reply); usage(); } } return 1; }
int cmd_add(int argc, const char **argv, const char *prefix) { int exit_status = 0; int newfd; struct pathspec pathspec; struct dir_struct dir; int flags; int add_new_files; int require_pathspec; char *seen = NULL; git_config(add_config, NULL); argc = parse_options(argc, argv, prefix, builtin_add_options, builtin_add_usage, PARSE_OPT_KEEP_ARGV0); if (patch_interactive) add_interactive = 1; if (add_interactive) exit(interactive_add(argc - 1, argv + 1, prefix, patch_interactive)); if (edit_interactive) return(edit_patch(argc, argv, prefix)); argc--; argv++; if (0 <= addremove_explicit) addremove = addremove_explicit; else if (take_worktree_changes && ADDREMOVE_DEFAULT) addremove = 0; /* "-u" was given but not "-A" */ if (addremove && take_worktree_changes) die(_("-A and -u are mutually incompatible")); if (!take_worktree_changes && addremove_explicit < 0 && argc) /* Turn "git add pathspec..." to "git add -A pathspec..." */ addremove = 1; if (!show_only && ignore_missing) die(_("Option --ignore-missing can only be used together with --dry-run")); if ((0 < addremove_explicit || take_worktree_changes) && !argc) { static const char *whole[2] = { ":/", NULL }; argc = 1; argv = whole; } add_new_files = !take_worktree_changes && !refresh_only; require_pathspec = !take_worktree_changes; newfd = hold_locked_index(&lock_file, 1); flags = ((verbose ? ADD_CACHE_VERBOSE : 0) | (show_only ? ADD_CACHE_PRETEND : 0) | (intent_to_add ? ADD_CACHE_INTENT : 0) | (ignore_add_errors ? ADD_CACHE_IGNORE_ERRORS : 0) | (!(addremove || take_worktree_changes) ? ADD_CACHE_IGNORE_REMOVAL : 0)); if (require_pathspec && argc == 0) { fprintf(stderr, _("Nothing specified, nothing added.\n")); fprintf(stderr, _("Maybe you wanted to say 'git add .'?\n")); return 0; } if (read_cache() < 0) die(_("index file corrupt")); /* * Check the "pathspec '%s' did not match any files" block * below before enabling new magic. */ parse_pathspec(&pathspec, 0, PATHSPEC_PREFER_FULL | PATHSPEC_SYMLINK_LEADING_PATH | PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE, prefix, argv); if (add_new_files) { int baselen; struct pathspec empty_pathspec; /* Set up the default git porcelain excludes */ memset(&dir, 0, sizeof(dir)); if (!ignored_too) { dir.flags |= DIR_COLLECT_IGNORED; setup_standard_excludes(&dir); } memset(&empty_pathspec, 0, sizeof(empty_pathspec)); /* This picks up the paths that are not tracked */ baselen = fill_directory(&dir, &pathspec); if (pathspec.nr) seen = prune_directory(&dir, &pathspec, baselen); } if (refresh_only) { refresh(verbose, &pathspec); goto finish; } if (pathspec.nr) { int i; if (!seen) seen = find_pathspecs_matching_against_index(&pathspec); /* * file_exists() assumes exact match */ GUARD_PATHSPEC(&pathspec, PATHSPEC_FROMTOP | PATHSPEC_LITERAL | PATHSPEC_GLOB | PATHSPEC_ICASE | PATHSPEC_EXCLUDE); for (i = 0; i < pathspec.nr; i++) { const char *path = pathspec.items[i].match; if (pathspec.items[i].magic & PATHSPEC_EXCLUDE) continue; if (!seen[i] && path[0] && ((pathspec.items[i].magic & (PATHSPEC_GLOB | PATHSPEC_ICASE)) || !file_exists(path))) { if (ignore_missing) { int dtype = DT_UNKNOWN; if (is_excluded(&dir, path, &dtype)) dir_add_ignored(&dir, path, pathspec.items[i].len); } else die(_("pathspec '%s' did not match any files"), pathspec.items[i].original); } } free(seen); } plug_bulk_checkin(); exit_status |= add_files_to_cache(prefix, &pathspec, flags); if (add_new_files) exit_status |= add_files(&dir, flags); unplug_bulk_checkin(); finish: if (active_cache_changed) { if (write_cache(newfd, active_cache, active_nr) || commit_locked_index(&lock_file)) die(_("Unable to write new index file")); } return exit_status; }
/** * Maps the URI for the given request to a page cache file, if possible. * * @return Whether the URI has been successfully mapped to a page cache file. * @param r The corresponding request. * @param public_dir The web application's 'public' directory. * @param filename The filename that the URI normally maps to. * @param filename_len The length of the <tt>filename</tt> string. * @param root The size of the root path in <tt>filename</tt>. * @param page_cache_file If mapping was successful, then the page cache * file's filename will be stored in here. * <tt>page_cache_file.data</tt> must already point to * a buffer, and <tt>page_cache_file.len</tt> must be set * to the size of this buffer, including terminating NUL. */ static int map_uri_to_page_cache_file(ngx_http_request_t *r, ngx_str_t *public_dir, const u_char *filename, size_t filename_len, ngx_str_t *page_cache_file) { u_char *end; if ((r->method != NGX_HTTP_GET && r->method != NGX_HTTP_HEAD) || filename_len == 0) { return 0; } /* From this point on we know that filename is not an empty string. */ /* Check whether `filename` is equal to public_dir. * `filename` may also be equal to public_dir + "/" so check for that as well. */ if (mapped_filename_equals(filename, filename_len, public_dir)) { /* If the URI maps to the 'public' or the alias directory (i.e. the request is the * base URI) then index.html is the page cache file. */ if (filename_len + sizeof("/index.html") > page_cache_file->len) { /* Page cache filename doesn't fit in the buffer. */ return 0; } end = ngx_copy(page_cache_file->data, filename, filename_len); if (filename[filename_len - 1] != '/') { end = ngx_copy(end, "/", 1); } end = ngx_copy(end, "index.html", sizeof("index.html")); } else if (filename[filename_len - 1] == '/') { /* if the filename ends with '/' check for filename + "index.html". */ if (filename_len + sizeof("index.html") > page_cache_file->len) { /* Page cache filename doesn't fit in the buffer. */ return 0; } end = ngx_copy(page_cache_file->data, filename, filename_len); end = ngx_copy(end, "index.html", sizeof("index.html")); } else { /* Otherwise, the page cache file is just filename + ".html". */ if (filename_len + sizeof(".html") > page_cache_file->len) { /* Page cache filename doesn't fit in the buffer. */ return 0; } end = ngx_copy(page_cache_file->data, filename, filename_len); end = ngx_copy(end, ".html", sizeof(".html")); } if (file_exists(page_cache_file->data, 0)) { page_cache_file->len = end - page_cache_file->data - 1; return 1; } else { return 0; } }
main(int argc, char *argv[]) { FILE *output; int numerate,i,j,k,l,nsperdmp,nsamps,indexing,plot,indexnow; int ifchan[16],frchan[4096],ifnum,chnum,ns,sample,ntotal; float time_of_pulse, width_of_pulse, time, time_start, time_end; float series_amp[100000],series_time[100000],ampmin,ampmax; char message[80],outfile[80],filename[80],timestring[80],pgdev[80]; unsigned char c; unsigned short s; float f[8]; if (argc<2) { puts(""); puts("getpulse - make and/or plot a time series from dedispersed file\n"); puts("usage: getpulse {filename} -{options}\n"); puts("filename is the dedispersed data file\n"); puts("options:\n"); puts("-t time - time (in seconds) on which to center time series (REQUIRED)\n"); puts("-w width - width (in seconds) of time series to plot (def=1)\n"); puts("-c fchan - to only output frequency channel fchan (def=all)\n"); puts("-i ifchan - to only output IF channel ifchan (def=all)\n"); puts("-p pgdev - pgplot device (def=/xs)\n"); puts("-numerate - to precede each dump with sample number (def=time)\n"); puts("-noindex - do not precede each dump with time/number\n"); puts("-plot - PGPLOT the results\n"); puts(""); exit(0); } /* zero IF and frequency channel arrays */ for (i=0;i<16;i++) ifchan[i]=0; for (i=0;i<4096;i++) frchan[i]=0; /* default case is to read from standard input */ input=stdin; numerate=0; ampmin = 1.e6; ampmax = -1.e6; plot=0; indexnow=0; indexing=1; strcpy(pgdev,"/xs"); /* parse command line if arguments were given */ if (argc>1) { i=1; while (i<argc) { if (strings_equal(argv[i],"-i")) { i++; ifchan[atoi(argv[i])-1]=1; } else if (strings_equal(argv[i],"-c")) { i++; frchan[atoi(argv[i])-1]=1; } else if (strings_equal(argv[i],"-t")) { i++; time_of_pulse = atof(argv[i]); strcpy(timestring,argv[i]); fprintf(stderr,"centering on time %f s\n",time_of_pulse); } else if (strings_equal(argv[i],"-w")) { i++; width_of_pulse = atof(argv[i]); fprintf(stderr,"with width %f s\n",width_of_pulse); } else if (strings_equal(argv[i],"-p")) { i++; strcpy(pgdev,argv[i]); } else if (strings_equal(argv[i],"-numerate")) { numerate=1; } else if (strings_equal(argv[i],"-noindex")) { indexing=0; } else if (strings_equal(argv[i],"-plot")) { plot=1; } else if (file_exists(argv[i])) { input=open_file(argv[i],"rb"); strcpy(filename,argv[i]); } else { sprintf(message,"unknown argument (%s) passed to getpulse",argv[i]); error_message(message); } i++; } } strcat(filename,".pulse."); strcat(filename,timestring); strcpy(outfile,filename); output=fopen(outfile,"w"); time_start = time_of_pulse - width_of_pulse/2.; time_end = time_of_pulse + width_of_pulse/2.; sample = 0; /* try to read the header */ if (!read_header(input)) error_message("error reading header\n"); /* check what IF and frequency channels (if any the user has selected) */ j=0; for (i=0; i<nifs; i++) if (ifchan[i]) j++; if (j==0) for (i=0; i<nifs; i++) ifchan[i]=1; j=0; for (i=0; i<nchans; i++) if (frchan[i]) j++; if (j==0) for (i=0; i<nchans; i++) frchan[i]=1; /* number of samples to read per dump */ nsperdmp=nifs*nchans; /* initialize loop counters and flags */ ifnum=chnum=nsamps=l=0; while (!feof(input)) { /* unpack the sample(s) if necessary */ switch (nbits) { case 1: fread(&c,1,1,input); for (i=0;i<8;i++) { f[i]=c&1; c>>=1; } ns=8; break; case 4: fread(&c,1,1,input); char2ints(c,&j,&k); f[0]=(float) j; f[1]=(float) k; ns=2; break; case 8: fread(&c,nbits/8,1,input); f[0]=(float) c; ns=1; break; case 16: fread(&s,nbits/8,1,input); f[0]=(float) s; ns=1; break; case 32: fread(&f[0],nbits/8,1,input); ns=1; break; default: sprintf(message,"cannot read %d bits per sample...\n",nbits); error_message(message); break; } if (plot) { ntotal = (time_end-time_start)/tsamp; if (ntotal > 100000) { fprintf(stderr,"Too many samples to plot!\n"); plot=0; } } for (i=0; i<ns; i++) { /* time stamp or index the data */ time = (double) tsamp * (double) l; if (time > time_end) { if (plot) { indexnow=indexnow-1; cpgbeg(0,pgdev,1,1); cpgsvp(0.1,0.9,0.1,0.9); cpgswin(series_time[0],series_time[indexnow],ampmin-0.1*ampmax,ampmax+0.1*ampmax); cpgbox("bcnst",0.0,0,"bcnst",0,0.0); cpgline(indexnow,series_time,series_amp); cpgscf(2); cpgmtxt("B",2.5,0.5,0.5,"Time (s)"); cpgmtxt("L",1.8,0.5,0.5,"Amplitude"); cpgend();} exit(0); } /* print sample if it is one of the ones selected */ if (ifchan[ifnum] && frchan[chnum] && time >= time_start && time <= time_end) { if (indexing) { if (numerate) fprintf(output,"%d %f\n",l,f[i]); else fprintf(output,"%f %f\n",time,f[i]); } else { fprintf(output,"%f\n",f[i]); } if (plot) { series_amp[indexnow]=f[i]; series_time[indexnow]=time; if (f[i] < ampmin) ampmin = f[i]; if (f[i] > ampmax) ampmax = f[i]; indexnow++; } } nsamps++; chnum++; if (chnum==nchans) { chnum=0; ifnum++; if (ifnum==nifs) ifnum=0; } if ((nsamps%nsperdmp)==0) { nsamps=0; l++; } } } fclose(output); }
uint64_t file_size(const std::string& filename) { if (!file_exists(filename)) return 0; return fs::file_size(filename); }
main(int argc, char *argv[]) { int numerate,i,j,k,l,stream,nsperdmp,nsamps,indexing,indexnow; int ifchan[16],frchan[4096],ifnum,chnum,ns,charout,sample; float time_of_pulse, width_of_pulse, time, time_start, time_end; char message[80],byte; unsigned char c; unsigned short s; float f[8]; /* zero IF and frequency channel arrays */ for (i=0;i<16;i++) ifchan[i]=0; for (i=0;i<4096;i++) frchan[i]=0; /* default case is to read from standard input */ input=stdin; charout=numerate=stream=0; indexing=1; /* parse command line if arguments were given */ if (argc>1) { i=1; while (i<argc) { if (strings_equal(argv[i],"help")) { reader_help(); exit(0); } else if (strings_equal(argv[1],"version")) { printf("PROGRAM: %s SIGPROC version: %.1f\n",argv[0],SIGPROC_VERSION); exit(0); } else if (strings_equal(argv[i],"-i")) { i++; ifchan[atoi(argv[i])-1]=1; } else if (strings_equal(argv[i],"-c")) { i++; frchan[atoi(argv[i])-1]=1; } else if (strings_equal(argv[i],"-t")) { i++; time_of_pulse = atof(argv[i]); fprintf(stderr,"centering on time %f s\n",time_of_pulse); } else if (strings_equal(argv[i],"-w")) { i++; width_of_pulse = atof(argv[i]); fprintf(stderr,"with width %f s\n",width_of_pulse); } else if (strings_equal(argv[i],"-numerate")) { numerate=1; } else if (strings_equal(argv[i],"-noindex")) { indexing=0; } else if (strings_equal(argv[i],"-stream")) { stream=1; } else if (strings_equal(argv[i],"-byte")) { charout=1; } else if (file_exists(argv[i])) { input=open_file(argv[i],"rb"); } else { reader_help(); sprintf(message,"unknown argument (%s) passed to reader",argv[i]); error_message(message); } i++; } } time_start = time_of_pulse - width_of_pulse/2.; time_end = time_of_pulse + width_of_pulse/2.; sample = 0; /* try to read the header */ if (!read_header(input)) error_message("error reading header\n"); /* check what IF and frequency channels (if any the user has selected) */ j=0; for (i=0; i<nifs; i++) if (ifchan[i]) j++; if (j==0) for (i=0; i<nifs; i++) ifchan[i]=1; j=0; for (i=0; i<nchans; i++) if (frchan[i]) j++; if (j==0) for (i=0; i<nchans; i++) frchan[i]=1; /* number of samples to read per dump */ nsperdmp=nifs*nchans; /* initialize loop counters and flags */ ifnum=chnum=nsamps=l=0; indexnow=1; if (stream && indexing) numerate=1; while (!feof(input)) { /* unpack the sample(s) if necessary */ switch (nbits) { case 1: fread(&c,1,1,input); for (i=0;i<8;i++) { f[i]=c&1; c>>=1; } ns=8; break; case 4: fread(&c,1,1,input); char2ints(c,&j,&k); f[0]=(float) j; f[1]=(float) k; ns=2; break; case 8: fread(&c,nbits/8,1,input); f[0]=(float) c; ns=1; break; case 16: fread(&s,nbits/8,1,input); f[0]=(float) s; ns=1; break; case 32: fread(&f[0],nbits/8,1,input); ns=1; break; default: sprintf(message,"cannot read %d bits per sample...\n",nbits); error_message(message); break; } for (i=0; i<ns; i++) { if (charout) { byte=(char) f[i]; putchar(byte); } else { /* time stamp or index the data if needed */ time = (double) tsamp * (double) l; if (time > time_end) exit(0); if (indexnow && stream) { puts("#START"); } else if (indexnow && indexing && time >= time_start && time <= time_end) { /* if (numerate) printf("%d ",l); else printf("# %f\n",time); */ } indexnow=0; /* print sample if it is one of the ones selected */ if (ifchan[ifnum] && frchan[chnum] && time >= time_start && time <= time_end) { if (stream && numerate) printf("%d ",nsamps); printf("%d %d %f \n",l,chnum,f[i]); } nsamps++; chnum++; if (chnum==nchans) { chnum=0; ifnum++; if (ifnum==nifs) ifnum=0; } /* put newline and terminator if in streaming mode */ if (stream) { if ((nsamps%nchans)==0) puts("#STOP"); } /* put newline if this is the last sample of the dump */ if ((nsamps%nsperdmp)==0) { nsamps=0; indexnow=1; l++; } } } } }
/* * Attempt to save the player in a savefile */ bool savefile_save(const char *path) { ang_file *file; int count = 0; char new_savefile[1024]; char old_savefile[1024]; /* New savefile */ strnfmt(old_savefile, sizeof(old_savefile), "%s%u.old", path,Rand_simple(1000000)); while (file_exists(old_savefile) && (count++ < 100)) { strnfmt(old_savefile, sizeof(old_savefile), "%s%u%u.old", path,Rand_simple(1000000),count); } count = 0; /* Make sure that the savefile doesn't already exist */ /*safe_setuid_grab(); file_delete(new_savefile); file_delete(old_savefile); safe_setuid_drop();*/ /* Open the savefile */ safe_setuid_grab(); strnfmt(new_savefile, sizeof(new_savefile), "%s%u.new", path,Rand_simple(1000000)); while (file_exists(new_savefile) && (count++ < 100)) { strnfmt(new_savefile, sizeof(new_savefile), "%s%u%u.new", path,Rand_simple(1000000),count); } file = file_open(new_savefile, MODE_WRITE, FTYPE_SAVE); safe_setuid_drop(); if (file) { file_write(file, (char *) &savefile_magic, 4); file_write(file, (char *) &savefile_name, 4); character_saved = try_save(file); file_close(file); } if (character_saved) { bool err = FALSE; safe_setuid_grab(); if (file_exists(savefile) && !file_move(savefile, old_savefile)) err = TRUE; if (!err) { if (!file_move(new_savefile, savefile)) err = TRUE; if (err) file_move(old_savefile, savefile); else file_delete(old_savefile); } safe_setuid_drop(); return err ? FALSE : TRUE; } /* Delete temp file if the save failed */ if (file) { /* file is no longer valid, but it still points to a non zero * value if the file was created above */ safe_setuid_grab(); file_delete(new_savefile); safe_setuid_drop(); } return FALSE; }
/* * Use the default gdb #defines unless there's a .gdb file. */ struct supported_gdb_version * setup_gdb_defaults(void) { FILE *fp; char inbuf[512]; char buf[512]; struct supported_gdb_version *sp; /* * Use the default, allowing for an override in .gdb */ if (!file_exists(".gdb")) return store_gdb_defaults(NULL); if ((fp = fopen(".gdb", "r")) == NULL) { perror(".gdb"); return store_gdb_defaults(NULL); } while (fgets(inbuf, 512, fp)) { strip_linefeeds(inbuf); strip_beginning_whitespace(inbuf); strcpy(buf, inbuf); /* * Simple override. */ if (strcmp(buf, "5.3") == 0) { fclose(fp); sp = &supported_gdb_versions[GDB_5_3]; fprintf(stderr, ".gdb configuration: %s\n\n", sp->GDB_VERSION_IN); return store_gdb_defaults(sp); } if (strcmp(buf, "6.0") == 0) { fclose(fp); sp = &supported_gdb_versions[GDB_6_0]; fprintf(stderr, ".gdb configuration: %s\n\n", sp->GDB_VERSION_IN); return store_gdb_defaults(sp); } if (strcmp(buf, "6.1") == 0) { fclose(fp); sp = &supported_gdb_versions[GDB_6_1]; fprintf(stderr, ".gdb configuration: %s\n", sp->GDB_VERSION_IN); return store_gdb_defaults(sp); } if (strcmp(buf, "7.0") == 0) { fclose(fp); sp = &supported_gdb_versions[GDB_7_0]; fprintf(stderr, ".gdb configuration: %s\n", sp->GDB_VERSION_IN); return store_gdb_defaults(sp); } if (strcmp(buf, "7.3.1") == 0) { fclose(fp); sp = &supported_gdb_versions[GDB_7_3_1]; fprintf(stderr, ".gdb configuration: %s\n", sp->GDB_VERSION_IN); return store_gdb_defaults(sp); } if (strcmp(buf, "7.6") == 0) { fclose(fp); sp = &supported_gdb_versions[GDB_7_6]; fprintf(stderr, ".gdb configuration: %s\n", sp->GDB_VERSION_IN); return store_gdb_defaults(sp); } } fclose(fp); fprintf(stderr, ".gdb: rejected -- using default gdb\n\n"); return store_gdb_defaults(NULL); }
/****************************************************************************** *** Labels_loadSYMfile ******************************************************************************/ void Labels_loadSYMfile (int taskid, int allobjects, unsigned ptask, unsigned task, char *name, int report) { #ifndef HAVE_BFD static int shown_BFD_missing = FALSE; #endif static int Labels_loadSYMfile_init = FALSE; FILE *FD; char LINE[1024], Type; unsigned function_count = 0, hwc_count = 0, other_count = 0; if (!Labels_loadSYMfile_init) { Extrae_Vector_Init (&defined_user_event_types); Extrae_Vector_Init (&defined_basic_block_labels); Labels_loadSYMfile_init = TRUE; } event_type_t * last_event_type_used = NULL; if (!name) return; if (strlen(name) == 0) return; if (!file_exists(name)) return; FD = (FILE *) fopen (name, "r"); if (FD == NULL) { fprintf (stderr, "mpi2prv: WARNING: Task %d Can\'t open symbols file %s\n", taskid, name); return; } while (!feof (FD)) { int args_assigned; if (fgets (LINE, 1024, FD) == NULL) break; args_assigned = sscanf (LINE, "%c %[^\n]", &Type, LINE); if (args_assigned == 2) { switch (Type) { case 'B': { unsigned long start, end, offset; char module[1024]; int res = sscanf (LINE, "0 \"%lx-%lx %lx %[^\n\"]\"", &start, &end, &offset, module); if (res == 4) { #ifdef HAVE_BFD ObjectTable_AddBinaryObject (allobjects, ptask, task, start, end, offset, module); #else if (!shown_BFD_missing) fprintf (stdout, "mpi2prv: Ignoring symbols from the application execution because mpi2prv does not support BFD\n"); shown_BFD_missing = TRUE; UNREFERENCED_PARAMETER(allobjects); UNREFERENCED_PARAMETER(ptask); UNREFERENCED_PARAMETER(task); #endif } else fprintf (stderr, PACKAGE_NAME": Error! Invalid line ('%s') in %s\n", LINE, name); } break; case 'O': case 'U': case 'P': { #ifdef HAVE_BFD /* Example of line: U 0x100016d4 fA mpi_test.c 0 */ char fname[1024], modname[1024]; int line; int type; int res; UINT64 address; res = sscanf (LINE, "%lx \"%[^\"]\" \"%[^\"]\" %d", &address, fname, modname, &line); if (res != 4) fprintf (stderr, PACKAGE_NAME": Error! Invalid line ('%s') in %s\n", LINE, name); if (!get_option_merge_UniqueCallerID()) { if (Type == 'O') type = OTHER_FUNCTION_TYPE; else if (Type == 'U') type = USER_FUNCTION_TYPE; else /* if (Type == 'P') */ type = OUTLINED_OPENMP_TYPE; } else type = UNIQUE_TYPE; Address2Info_AddSymbol (address, type, fname, modname, line); function_count++; #endif /* HAVE_BFD */ } break; case 'H': { int res, eventcode; char hwc_description[1024]; res = sscanf (LINE, "%d \"%[^\"]\"", &eventcode, hwc_description); if (res != 2) fprintf (stderr, PACKAGE_NAME": Error! Invalid line ('%s') in %s\n", LINE, name); Labels_AddHWCounter_Code_Description (eventcode, hwc_description); hwc_count++; } break; case 'c': case 'C': { int res, eventcode; char code_description[1024]; res = sscanf (LINE, "%d \"%[^\"]\"", &eventcode, code_description); if (res != 2) fprintf (stderr, PACKAGE_NAME": Error! Invalid line ('%s') in %s\n", LINE, name); Labels_Add_CodeLocation_Label (eventcode, Type=='C'?CODELOCATION_FUNCTION:CODELOCATION_FILELINE, code_description); other_count++; } break; case 'd': { int res, eventvalue; char value_description[1024]; value_t * evt_value = NULL; unsigned i, max = Extrae_Vector_Count (&last_event_type_used->event_values); res = sscanf (LINE, "%d \"%[^\"]\"", &eventvalue, value_description); if (res != 2) fprintf (stderr, PACKAGE_NAME": Error! Invalid line ('%s') in %s\n", LINE, name); for (i = 0; i < max; i++) { value_t * evt = Extrae_Vector_Get (&last_event_type_used->event_values, i); if(evt->value == eventvalue) { if(strcmp(evt->label, value_description)) { fprintf(stderr, PACKAGE_NAME"(%s,%d): Warning! Ignoring duplicate definition \"%s\" for value type %d,%d!\n",__FILE__, __LINE__, value_description,last_event_type_used->event_type.type, eventvalue); } evt_value = evt; break; } } if (!evt_value) { evt_value = (value_t*) malloc (sizeof (value_t)); if (evt_value == NULL) { fprintf (stderr, PACKAGE_NAME"(%s,%d): Fatal error! Cannot allocate memory to store the 'd' symbol in TRACE.sym file\n", __FILE__, __LINE__); exit(-1); } evt_value->value = eventvalue; strcpy(evt_value->label, value_description); Extrae_Vector_Append (&last_event_type_used->event_values, evt_value); other_count++; } } break; case 'D': { int res, eventcode; char code_description[1024]; unsigned i, max = Extrae_Vector_Count (&defined_user_event_types); event_type_t * evt_type = NULL; res = sscanf (LINE, "%d \"%[^\"]\"", &eventcode, code_description); if (res != 2) fprintf (stderr, PACKAGE_NAME": Error! Invalid line ('%s') in %s\n", LINE, name); for (i = 0; i < max; i++) { event_type_t * evt = Extrae_Vector_Get (&defined_user_event_types, i); if (evt->event_type.type == eventcode) { if(strcmp(evt->event_type.label, code_description)) { fprintf(stderr, PACKAGE_NAME"(%s,%d): Warning! Ignoring duplicate definition \"%s\" for type %d!\n", __FILE__, __LINE__, code_description, eventcode); } evt_type = evt; break; } } if (!evt_type) { evt_type = (event_type_t*) malloc (sizeof (event_type_t)); if (evt_type == NULL) { fprintf (stderr, "Extrae (%s,%d): Fatal error! Cannot allocate memory to store the 'D' symbol in TRACE.sym file\n", __FILE__, __LINE__); exit(-1); } evt_type->event_type.type = eventcode; strcpy(evt_type->event_type.label, code_description); Extrae_Vector_Init(&evt_type->event_values); Extrae_Vector_Append(&defined_user_event_types, evt_type); other_count++; } last_event_type_used = evt_type; } break; case 'b': // BasicBlocks symbol { int res, eventvalue; char bb_description[1024]; unsigned i, max = Extrae_Vector_Count (&defined_basic_block_labels); event_type_t * evt_type = NULL; value_t * evt_value = NULL; res = sscanf (LINE, "%d \"%[^\"]\"", &eventvalue, bb_description); if (res != 2) fprintf (stderr, PACKAGE_NAME": Error! Invalid line ('%s') in %s\n", LINE, name); if (max==0){ evt_type = (event_type_t*) malloc (sizeof (event_type_t)); if (evt_type == NULL) { fprintf (stderr, "Extrae (%s,%d): Fatal error! Cannot allocate memory to store the 'B' symbol in TRACE.sym file\n", __FILE__, __LINE__); exit(-1); } evt_type->event_type.type = USRFUNC_EV_BB; strcpy(evt_type->event_type.label, "BASIC_BLOCKS"); Extrae_Vector_Init(&evt_type->event_values); Extrae_Vector_Append(&defined_basic_block_labels, evt_type); } else { evt_type = Extrae_Vector_Get (&defined_basic_block_labels, 0); // There is only one event type in the vector } max = Extrae_Vector_Count (&evt_type->event_values); for(i = 0; i < max; i++) { value_t * evt = Extrae_Vector_Get (&evt_type->event_values, i); if(evt->value == eventvalue) { if(strcmp(evt->label, bb_description)) { fprintf(stderr, "Extrae (%s,%d): Warning! Ignoring duplicate definition \"%s\" for value type %d,%d!\n",__FILE__, __LINE__, bb_description,evt_type->event_type.type, eventvalue); } evt_value = evt; break; } } if (!evt_value) { evt_value = (value_t*) malloc (sizeof (value_t)); if (evt_value == NULL) { fprintf (stderr, "Extrae (%s,%d): Fatal error! Cannot allocate memory to store the 'B' symbol in TRACE.sym file\n", __FILE__, __LINE__); exit(-1); } evt_value->value = eventvalue; strcpy(evt_value->label, bb_description); Extrae_Vector_Append (&evt_type->event_values, evt_value); other_count++; } } break; default: fprintf (stderr, PACKAGE_NAME" mpi2prv: Error! Task %d found unexpected line in symbol file '%s'\n", taskid, LINE); break; } } } if (taskid == 0 && report) { fprintf (stdout, "mpi2prv: A total of %u symbols were imported from %s file\n", function_count+hwc_count+other_count, name); fprintf (stdout, "mpi2prv: %u function symbols imported\n", function_count); fprintf (stdout, "mpi2prv: %u HWC counter descriptions imported\n", hwc_count); } fclose (FD); }
/* * Add extra compression libraries. If not already there, create * a CFLAGS.extra file and an LDFLAGS.extra file. * For lzo: * - enter -DSNAPPY in the CFLAGS.extra file * - enter -lsnappy in the LDFLAGS.extra file * * For snappy: * - enter -DLZO in the CFLAGS.extra file * - enter -llzo2 in the LDFLAGS.extra file. */ void add_extra_lib(char *option) { int lzo, add_DLZO, add_llzo2; int snappy, add_DSNAPPY, add_lsnappy; char *cflags, *ldflags; FILE *fp_cflags, *fp_ldflags; char *mode; char inbuf[512]; lzo = add_DLZO = add_llzo2 = 0; snappy = add_DSNAPPY = add_lsnappy = 0; ldflags = get_extra_flags("LDFLAGS.extra", NULL); cflags = get_extra_flags("CFLAGS.extra", NULL); if (strcmp(option, "lzo") == 0) { lzo++; if (!cflags || !strstr(cflags, "-DLZO")) add_DLZO++; if (!ldflags || !strstr(ldflags, "-llzo2")) add_llzo2++; } if (strcmp(option, "snappy") == 0) { snappy++; if (!cflags || !strstr(cflags, "-DSNAPPY")) add_DSNAPPY++; if (!ldflags || !strstr(ldflags, "-lsnappy")) add_lsnappy++; } if ((lzo || snappy) && file_exists("diskdump.o") && (unlink("diskdump.o") < 0)) { perror("diskdump.o"); return; } mode = file_exists("CFLAGS.extra") ? "r+" : "w+"; if ((fp_cflags = fopen("CFLAGS.extra", mode)) == NULL) { perror("CFLAGS.extra"); return; } mode = file_exists("LDFLAGS.extra") ? "r+" : "w+"; if ((fp_ldflags = fopen("LDFLAGS.extra", mode)) == NULL) { perror("LDFLAGS.extra"); fclose(fp_cflags); return; } if (add_DLZO || add_DSNAPPY) { while (fgets(inbuf, 512, fp_cflags)) ; if (add_DLZO) fputs("-DLZO\n", fp_cflags); if (add_DSNAPPY) fputs("-DSNAPPY\n", fp_cflags); } if (add_llzo2 || add_lsnappy) { while (fgets(inbuf, 512, fp_ldflags)) ; if (add_llzo2) fputs("-llzo2\n", fp_ldflags); if (add_lsnappy) fputs("-lsnappy\n", fp_ldflags); } fclose(fp_cflags); fclose(fp_ldflags); }
ColoringRulesDialog::ColoringRulesDialog(QWidget *parent, QString add_filter) : GeometryStateDialog(parent), ui(new Ui::ColoringRulesDialog), copy_from_menu_(NULL), colorRuleModel_(palette().color(QPalette::Text), palette().color(QPalette::Base), this), colorRuleDelegate_(this) { ui->setupUi(this); if (parent) loadGeometry(parent->width() * 2 / 3, parent->height() * 4 / 5); setWindowTitle(wsApp->windowTitleString(tr("Coloring Rules %1").arg(get_profile_name()))); ui->coloringRulesTreeView->setModel(&colorRuleModel_); ui->coloringRulesTreeView->setItemDelegate(&colorRuleDelegate_); ui->coloringRulesTreeView->viewport()->setAcceptDrops(true); for (int i = 0; i < colorRuleModel_.columnCount(); i++) { ui->coloringRulesTreeView->resizeColumnToContents(i); } #ifdef Q_OS_MAC ui->newToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->deleteToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->copyToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->clearToolButton->setAttribute(Qt::WA_MacSmallSize, true); ui->pathLabel->setAttribute(Qt::WA_MacSmallSize, true); #endif connect(ui->coloringRulesTreeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(colorRuleSelectionChanged(const QItemSelection &, const QItemSelection &))); connect(&colorRuleDelegate_, SIGNAL(invalidField(const QModelIndex&, const QString&)), this, SLOT(invalidField(const QModelIndex&, const QString&))); connect(&colorRuleDelegate_, SIGNAL(validField(const QModelIndex&)), this, SLOT(validField(const QModelIndex&))); connect(&colorRuleModel_, SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(rowCountChanged())); connect(&colorRuleModel_, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), this, SLOT(rowCountChanged())); rowCountChanged(); import_button_ = ui->buttonBox->addButton(tr("Import" UTF8_HORIZONTAL_ELLIPSIS), QDialogButtonBox::ApplyRole); import_button_->setToolTip(tr("Select a file and add its filters to the end of the list.")); export_button_ = ui->buttonBox->addButton(tr("Export" UTF8_HORIZONTAL_ELLIPSIS), QDialogButtonBox::ApplyRole); export_button_->setToolTip(tr("Save filters in a file.")); QPushButton *copy_button = ui->buttonBox->addButton(tr("Copy from"), QDialogButtonBox::ActionRole); copy_from_menu_ = new CopyFromProfileMenu(COLORFILTERS_FILE_NAME); copy_button->setMenu(copy_from_menu_); copy_button->setToolTip(tr("Copy coloring rules from another profile.")); copy_button->setEnabled(copy_from_menu_->haveProfiles()); connect(copy_from_menu_, SIGNAL(triggered(QAction *)), this, SLOT(copyFromProfile(QAction *))); QString abs_path = gchar_free_to_qstring(get_persconffile_path(COLORFILTERS_FILE_NAME, TRUE)); if (file_exists(abs_path.toUtf8().constData())) { ui->pathLabel->setText(abs_path); ui->pathLabel->setUrl(QUrl::fromLocalFile(abs_path).toString()); ui->pathLabel->setToolTip(tr("Open ") + COLORFILTERS_FILE_NAME); ui->pathLabel->setEnabled(true); } if (!add_filter.isEmpty()) { colorRuleModel_.addColor(false, add_filter, palette().color(QPalette::Text), palette().color(QPalette::Base)); //setup the buttons appropriately ui->coloringRulesTreeView->setCurrentIndex(colorRuleModel_.index(0, 0)); //set edit on display filter ui->coloringRulesTreeView->edit(colorRuleModel_.index(0, 1)); }else { ui->coloringRulesTreeView->setCurrentIndex(QModelIndex()); } checkUnknownColorfilters(); updateHint(); }
void get_current_configuration(struct supported_gdb_version *sp) { FILE *fp; static char buf[512]; char *p; #ifdef __alpha__ target_data.target = ALPHA; #endif #ifdef __i386__ target_data.target = X86; #endif #ifdef __powerpc__ target_data.target = PPC; #endif #ifdef __ia64__ target_data.target = IA64; #endif #ifdef __s390__ target_data.target = S390; #endif #ifdef __s390x__ target_data.target = S390X; #endif #ifdef __powerpc64__ target_data.target = PPC64; #endif #ifdef __x86_64__ target_data.target = X86_64; #endif #ifdef __arm__ target_data.target = ARM; #endif #ifdef __aarch64__ target_data.target = ARM64; #endif #ifdef __mips__ target_data.target = MIPS; #endif set_initial_target(sp); /* * Override target if specified on command line. */ target_data.host = target_data.target; if (target_data.target_as_param) { if ((target_data.target == X86 || target_data.target == X86_64) && (name_to_target((char *)target_data.target_as_param) == ARM)) { /* * Debugging of ARM core files supported on X86, and on * X86_64 when built as a 32-bit executable. */ target_data.target = ARM; } else if ((target_data.target == X86 || target_data.target == X86_64) && (name_to_target((char *)target_data.target_as_param) == MIPS)) { /* * Debugging of MIPS little-endian core files * supported on X86, and on X86_64 when built as a * 32-bit executable. */ target_data.target = MIPS; } else if ((target_data.target == X86_64) && (name_to_target((char *)target_data.target_as_param) == X86)) { /* * Build an X86 crash binary on an X86_64 host. */ target_data.target = X86; } else if ((target_data.target == X86_64) && (name_to_target((char *)target_data.target_as_param) == ARM64)) { /* * Build an ARM64 crash binary on an X86_64 host. */ target_data.target = ARM64; } else if ((target_data.target == X86_64) && (name_to_target((char *)target_data.target_as_param) == PPC64)) { /* * Build a PPC64 little-endian crash binary on an X86_64 host. */ target_data.target = PPC64; } else if ((target_data.target == PPC64) && (name_to_target((char *)target_data.target_as_param) == PPC)) { /* * Build an PPC crash binary on an PPC64 host. */ target_data.target = PPC; } else if (name_to_target((char *)target_data.target_as_param) == target_data.host) { if ((target_data.initial_gdb_target != UNKNOWN) && (target_data.host != target_data.initial_gdb_target)) arch_mismatch(sp); } else { fprintf(stderr, "\ntarget=%s is not supported on the %s host architecture\n\n", target_data.target_as_param, target_to_name(target_data.host)); exit(1); } } /* * Impose implied (sticky) target if an initial build has been * done in the source tree. */ if (target_data.initial_gdb_target && (target_data.target != target_data.initial_gdb_target)) { if ((target_data.initial_gdb_target == ARM) && (target_data.target != ARM)) { if ((target_data.target == X86) || (target_data.target == X86_64)) target_data.target = ARM; else arch_mismatch(sp); } if ((target_data.target == ARM) && (target_data.initial_gdb_target != ARM)) arch_mismatch(sp); if ((target_data.initial_gdb_target == MIPS) && (target_data.target != MIPS)) { if ((target_data.target == X86) || (target_data.target == X86_64)) target_data.target = MIPS; else arch_mismatch(sp); } if ((target_data.initial_gdb_target == X86) && (target_data.target != X86)) { if (target_data.target == X86_64) target_data.target = X86; else arch_mismatch(sp); } if ((target_data.target == X86) && (target_data.initial_gdb_target != X86)) arch_mismatch(sp); if ((target_data.initial_gdb_target == ARM64) && (target_data.target != ARM64)) { if (target_data.target == X86_64) target_data.target = ARM64; else arch_mismatch(sp); } if ((target_data.target == ARM64) && (target_data.initial_gdb_target != ARM64)) arch_mismatch(sp); if ((target_data.initial_gdb_target == PPC64) && (target_data.target != PPC64)) { if (target_data.target == X86_64) target_data.target = PPC64; else arch_mismatch(sp); } if ((target_data.target == PPC64) && (target_data.initial_gdb_target != PPC64)) arch_mismatch(sp); if ((target_data.initial_gdb_target == PPC) && (target_data.target != PPC)) { if (target_data.target == PPC64) target_data.target = PPC; else arch_mismatch(sp); } if ((target_data.target == PPC) && (target_data.initial_gdb_target != PPC)) arch_mismatch(sp); } if ((fp = fopen("Makefile", "r")) == NULL) { perror("Makefile"); goto get_release; } while (fgets(buf, 512, fp)) { if (strncmp(buf, "PROGRAM=", strlen("PROGRAM=")) == 0) { p = strstr(buf, "=") + 1; strip_linefeeds(p); upper_case(p, target_data.program); if (target_data.flags & DAEMON) strcat(target_data.program, "D"); continue; } } fclose(fp); get_release: target_data.release[0] = '\0'; if (file_exists(".rh_rpm_package")) { if ((fp = fopen(".rh_rpm_package", "r")) == NULL) { perror(".rh_rpm_package"); } else { if (fgets(buf, 512, fp)) { strip_linefeeds(buf); if (strlen(buf)) { buf[MAXSTRLEN-1] = '\0'; strcpy(target_data.release, buf); } else fprintf(stderr, "WARNING: .rh_rpm_package file is empty!\n"); } else fprintf(stderr, "WARNING: .rh_rpm_package file is empty!\n"); fclose(fp); if (strlen(target_data.release)) return; } } else fprintf(stderr, "WARNING: .rh_rpm_package file does not exist!\n"); if ((fp = fopen("defs.h", "r")) == NULL) { perror("defs.h"); return; } while (fgets(buf, 512, fp)) { if (strncmp(buf, "#define BASELEVEL_REVISION", strlen("#define BASELEVEL_REVISION")) == 0) { p = strstr(buf, "\"") + 1; strip_linefeeds(p); p[strlen(p)-1] = '\0'; strcpy(target_data.release, p); break; } } fclose(fp); }
int cmd_merge(int argc, const char **argv, const char *prefix) { unsigned char result_tree[20]; unsigned char stash[20]; unsigned char head_sha1[20]; struct commit *head_commit; struct strbuf buf = STRBUF_INIT; const char *head_arg; int flag, i, ret = 0; int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0; struct commit_list *common = NULL; const char *best_strategy = NULL, *wt_strategy = NULL; struct commit_list **remotes = &remoteheads; void *branch_to_free; if (argc == 2 && !strcmp(argv[1], "-h")) usage_with_options(builtin_merge_usage, builtin_merge_options); /* * Check if we are _not_ on a detached HEAD, i.e. if there is a * current branch. */ branch = branch_to_free = resolve_refdup("HEAD", head_sha1, 0, &flag); if (branch && !prefixcmp(branch, "refs/heads/")) branch += 11; if (!branch || is_null_sha1(head_sha1)) head_commit = NULL; else head_commit = lookup_commit_or_die(head_sha1, "HEAD"); git_config(git_merge_config, NULL); if (branch_mergeoptions) parse_branch_merge_options(branch_mergeoptions); argc = parse_options(argc, argv, prefix, builtin_merge_options, builtin_merge_usage, 0); if (shortlog_len < 0) shortlog_len = (merge_log_config > 0) ? merge_log_config : 0; if (verbosity < 0 && show_progress == -1) show_progress = 0; if (abort_current_merge) { int nargc = 2; const char *nargv[] = {"reset", "--merge", NULL}; if (!file_exists(git_path("MERGE_HEAD"))) die(_("There is no merge to abort (MERGE_HEAD missing).")); /* Invoke 'git reset --merge' */ ret = cmd_reset(nargc, nargv, prefix); goto done; } if (read_cache_unmerged()) die_resolve_conflict("merge"); if (file_exists(git_path("MERGE_HEAD"))) { /* * There is no unmerged entry, don't advise 'git * add/rm <file>', just 'git commit'. */ if (advice_resolve_conflict) die(_("You have not concluded your merge (MERGE_HEAD exists).\n" "Please, commit your changes before you can merge.")); else die(_("You have not concluded your merge (MERGE_HEAD exists).")); } if (file_exists(git_path("CHERRY_PICK_HEAD"))) { if (advice_resolve_conflict) die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n" "Please, commit your changes before you can merge.")); else die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).")); } resolve_undo_clear(); if (verbosity < 0) show_diffstat = 0; if (squash) { if (!allow_fast_forward) die(_("You cannot combine --squash with --no-ff.")); option_commit = 0; } if (!allow_fast_forward && fast_forward_only) die(_("You cannot combine --no-ff with --ff-only.")); if (!abort_current_merge) { if (!argc) { if (default_to_upstream) argc = setup_with_upstream(&argv); else die(_("No commit specified and merge.defaultToUpstream not set.")); } else if (argc == 1 && !strcmp(argv[0], "-")) argv[0] = "@{-1}"; } if (!argc) usage_with_options(builtin_merge_usage, builtin_merge_options); /* * This could be traditional "merge <msg> HEAD <commit>..." and * the way we can tell it is to see if the second token is HEAD, * but some people might have misused the interface and used a * committish that is the same as HEAD there instead. * Traditional format never would have "-m" so it is an * additional safety measure to check for it. */ if (!have_message && head_commit && is_old_style_invocation(argc, argv, head_commit->object.sha1)) { strbuf_addstr(&merge_msg, argv[0]); head_arg = argv[1]; argv += 2; argc -= 2; } else if (!head_commit) { struct commit *remote_head; /* * If the merged head is a valid one there is no reason * to forbid "git merge" into a branch yet to be born. * We do the same for "git pull". */ if (argc != 1) die(_("Can merge only exactly one commit into " "empty head")); if (squash) die(_("Squash commit into empty head not supported yet")); if (!allow_fast_forward) die(_("Non-fast-forward commit does not make sense into " "an empty head")); remote_head = get_merge_parent(argv[0]); if (!remote_head) die(_("%s - not something we can merge"), argv[0]); read_empty(remote_head->object.sha1, 0); update_ref("initial pull", "HEAD", remote_head->object.sha1, NULL, 0, DIE_ON_ERR); goto done; } else { struct strbuf merge_names = STRBUF_INIT; /* We are invoked directly as the first-class UI. */ head_arg = "HEAD"; /* * All the rest are the commits being merged; prepare * the standard merge summary message to be appended * to the given message. */ for (i = 0; i < argc; i++) merge_name(argv[i], &merge_names); if (!have_message || shortlog_len) { struct fmt_merge_msg_opts opts; memset(&opts, 0, sizeof(opts)); opts.add_title = !have_message; opts.shortlog_len = shortlog_len; fmt_merge_msg(&merge_names, &merge_msg, &opts); if (merge_msg.len) strbuf_setlen(&merge_msg, merge_msg.len - 1); } } if (!head_commit || !argc) usage_with_options(builtin_merge_usage, builtin_merge_options); strbuf_addstr(&buf, "merge"); for (i = 0; i < argc; i++) strbuf_addf(&buf, " %s", argv[i]); setenv("GIT_REFLOG_ACTION", buf.buf, 0); strbuf_reset(&buf); for (i = 0; i < argc; i++) { struct commit *commit = get_merge_parent(argv[i]); if (!commit) die(_("%s - not something we can merge"), argv[i]); remotes = &commit_list_insert(commit, remotes)->next; strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(commit->object.sha1)); setenv(buf.buf, argv[i], 1); strbuf_reset(&buf); if (!fast_forward_only && merge_remote_util(commit) && merge_remote_util(commit)->obj && merge_remote_util(commit)->obj->type == OBJ_TAG) { if (option_edit < 0) option_edit = 1; allow_fast_forward = 0; } } if (option_edit < 0) option_edit = 0; if (!use_strategies) { if (!remoteheads->next) add_strategies(pull_twohead, DEFAULT_TWOHEAD); else add_strategies(pull_octopus, DEFAULT_OCTOPUS); } for (i = 0; i < use_strategies_nr; i++) { if (use_strategies[i]->attr & NO_FAST_FORWARD) allow_fast_forward = 0; if (use_strategies[i]->attr & NO_TRIVIAL) allow_trivial = 0; } if (!remoteheads->next) common = get_merge_bases(head_commit, remoteheads->item, 1); else { struct commit_list *list = remoteheads; commit_list_insert(head_commit, &list); common = get_octopus_merge_bases(list); free(list); } update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.sha1, NULL, 0, DIE_ON_ERR); if (!common) ; /* No common ancestors found. We need a real merge. */ else if (!remoteheads->next && !common->next && common->item == remoteheads->item) { /* * If head can reach all the merge then we are up to date. * but first the most common case of merging one remote. */ finish_up_to_date("Already up-to-date."); goto done; } else if (allow_fast_forward && !remoteheads->next && !common->next && !hashcmp(common->item->object.sha1, head_commit->object.sha1)) { /* Again the most common case of merging one remote. */ struct strbuf msg = STRBUF_INIT; struct commit *commit; char hex[41]; strcpy(hex, find_unique_abbrev(head_commit->object.sha1, DEFAULT_ABBREV)); if (verbosity >= 0) printf(_("Updating %s..%s\n"), hex, find_unique_abbrev(remoteheads->item->object.sha1, DEFAULT_ABBREV)); strbuf_addstr(&msg, "Fast-forward"); if (have_message) strbuf_addstr(&msg, " (no commit created; -m option ignored)"); commit = remoteheads->item; if (!commit) { ret = 1; goto done; } if (checkout_fast_forward(head_commit->object.sha1, commit->object.sha1)) { ret = 1; goto done; } finish(head_commit, commit->object.sha1, msg.buf); drop_save(); goto done; } else if (!remoteheads->next && common->next) ; /* * We are not doing octopus and not fast-forward. Need * a real merge. */ else if (!remoteheads->next && !common->next && option_commit) { /* * We are not doing octopus, not fast-forward, and have * only one common. */ refresh_cache(REFRESH_QUIET); if (allow_trivial && !fast_forward_only) { /* See if it is really trivial. */ git_committer_info(IDENT_ERROR_ON_NO_NAME); printf(_("Trying really trivial in-index merge...\n")); if (!read_tree_trivial(common->item->object.sha1, head_commit->object.sha1, remoteheads->item->object.sha1)) { ret = merge_trivial(head_commit); goto done; } printf(_("Nope.\n")); } } else { /* * An octopus. If we can reach all the remote we are up * to date. */ int up_to_date = 1; struct commit_list *j; for (j = remoteheads; j; j = j->next) { struct commit_list *common_one; /* * Here we *have* to calculate the individual * merge_bases again, otherwise "git merge HEAD^ * HEAD^^" would be missed. */ common_one = get_merge_bases(head_commit, j->item, 1); if (hashcmp(common_one->item->object.sha1, j->item->object.sha1)) { up_to_date = 0; break; } } if (up_to_date) { finish_up_to_date("Already up-to-date. Yeeah!"); goto done; } } if (fast_forward_only) die(_("Not possible to fast-forward, aborting.")); /* We are going to make a new commit. */ git_committer_info(IDENT_ERROR_ON_NO_NAME); /* * At this point, we need a real merge. No matter what strategy * we use, it would operate on the index, possibly affecting the * working tree, and when resolved cleanly, have the desired * tree in the index -- this means that the index must be in * sync with the head commit. The strategies are responsible * to ensure this. */ if (use_strategies_nr == 1 || /* * Stash away the local changes so that we can try more than one. */ save_state(stash)) hashcpy(stash, null_sha1); for (i = 0; i < use_strategies_nr; i++) { int ret; if (i) { printf(_("Rewinding the tree to pristine...\n")); restore_state(head_commit->object.sha1, stash); } if (use_strategies_nr != 1) printf(_("Trying merge strategy %s...\n"), use_strategies[i]->name); /* * Remember which strategy left the state in the working * tree. */ wt_strategy = use_strategies[i]->name; ret = try_merge_strategy(use_strategies[i]->name, common, head_commit, head_arg); if (!option_commit && !ret) { merge_was_ok = 1; /* * This is necessary here just to avoid writing * the tree, but later we will *not* exit with * status code 1 because merge_was_ok is set. */ ret = 1; } if (ret) { /* * The backend exits with 1 when conflicts are * left to be resolved, with 2 when it does not * handle the given merge at all. */ if (ret == 1) { int cnt = evaluate_result(); if (best_cnt <= 0 || cnt <= best_cnt) { best_strategy = use_strategies[i]->name; best_cnt = cnt; } } if (merge_was_ok) break; else continue; } /* Automerge succeeded. */ write_tree_trivial(result_tree); automerge_was_ok = 1; break; } /* * If we have a resulting tree, that means the strategy module * auto resolved the merge cleanly. */ if (automerge_was_ok) { ret = finish_automerge(head_commit, common, result_tree, wt_strategy); goto done; } /* * Pick the result from the best strategy and have the user fix * it up. */ if (!best_strategy) { restore_state(head_commit->object.sha1, stash); if (use_strategies_nr > 1) fprintf(stderr, _("No merge strategy handled the merge.\n")); else fprintf(stderr, _("Merge with strategy %s failed.\n"), use_strategies[0]->name); ret = 2; goto done; } else if (best_strategy == wt_strategy) ; /* We already have its result in the working tree. */ else { printf(_("Rewinding the tree to pristine...\n")); restore_state(head_commit->object.sha1, stash); printf(_("Using the %s to prepare resolving by hand.\n"), best_strategy); try_merge_strategy(best_strategy, common, head_commit, head_arg); } if (squash) finish(head_commit, NULL, NULL); else write_merge_state(); if (merge_was_ok) fprintf(stderr, _("Automatic merge went well; " "stopped before committing as requested\n")); else ret = suggest_conflicts(option_renormalize); done: free(branch_to_free); return ret; }
/* * Create an .rh_rpm_package file if the passed-in variable is set. */ void make_rh_rpm_package(char *package, int release) { char *p, *cur; FILE *fp; char buf[256]; if ((strcmp(package, "remove") == 0)) { if (file_exists(".rh_rpm_package")) { if (unlink(".rh_rpm_package")) { perror("unlink"); fprintf(stderr, "cannot remove .rh_rpm_package\n"); exit(1); } } return; } if (!(p = strstr(package, "="))) return; if (!strlen(++p)) return; if (release) { if (!(fp = popen("./crash -v", "r"))) { fprintf(stderr, "cannot execute \"crash -v\"\n"); exit(1); } cur = NULL; while (fgets(buf, 256, fp)) { if (strncmp(buf, "crash ", 6) == 0) { cur = &buf[6]; break; } } pclose(fp); if (!cur) { fprintf(stderr, "cannot get version from \"crash -v\"\n"); exit(1); } strip_linefeeds(cur); if (strcmp(cur, p) != 0) { fprintf(stderr, "./crash version: %s\n", cur); fprintf(stderr, "release version: %s\n", p); exit(1); } } if ((fp = fopen(".rh_rpm_package", "w")) == NULL) { perror("fopen"); fprintf(stderr, "cannot open .rh_rpm_package\n"); exit(1); } fprintf(fp, "%s\n", strip_linefeeds(p)); fclose(fp); }
void file_write (File *file, const char* directory) { char *path = NULL; assert (file); if (!file) return; if (file->name == NULL) { file->name = strdup( TNEF_DEFAULT_FILENAME ); debug_print ("No file name specified, using default %s.\n", TNEF_DEFAULT_FILENAME); } if ( file->path == NULL ) { file->path = munge_fname( file->name ); if (file->path == NULL) { file->path = strdup( TNEF_DEFAULT_FILENAME ); debug_print ("No path name available, using default %s.\n", TNEF_DEFAULT_FILENAME); } } path = concat_fname( directory, file->path ); if (path == NULL) { path = strdup( TNEF_DEFAULT_FILENAME ); debug_print ("No path generated, using default %s.\n", TNEF_DEFAULT_FILENAME); } debug_print ("%sWRITING\t|\t%s\t|\t%s\n", ((LIST_ONLY==0)?"":"NOT "), file->name, path); if (!LIST_ONLY) { FILE *fp = NULL; if (!confirm_action ("extract %s?", file->name)) return; if (!OVERWRITE_FILES) { if (file_exists (path)) { if (!NUMBER_FILES) { fprintf (stderr, "tnef: %s: Could not create file: File exists\n", path); return; } else { char *tmp = find_free_number (path); debug_print ("Renaming %s to %s\n", path, tmp); XFREE (path); path = tmp; } } } fp = fopen (path, "wb"); if (fp == NULL) { perror (path); exit (1); } if (fwrite (file->data, 1, file->len, fp) != file->len) { perror (path); exit (1); } fclose (fp); } if (LIST_ONLY || VERBOSE_ON) { if (LIST_ONLY && VERBOSE_ON) { /* FIXME: print out date and stuff */ const char *date_str = date_to_str(&file->dt); fprintf (stdout, "%11lu\t|\t%s\t|\t%s\t|\t%s", (unsigned long)file->len, date_str+4, /* skip the day of week */ file->name, path); } else { fprintf (stdout, "%s\t|\t%s", file->name, path); } if ( SHOW_MIME ) { fprintf (stdout, "\t|\t%s", file->mime_type ? file->mime_type : "unknown"); fprintf (stdout, "\t|\t%s", file->content_id ? file->content_id : ""); } fprintf (stdout, "\n"); } XFREE(path); }
Var* ff_write(vfuncptr func, Var* arg) { Var* ob = NULL; char* filename = NULL; char* title = NULL; char* type = NULL; char* separator = NULL; /* for csv */ int header = 0; /* for csv */ int force = 0; /* Force file overwrite */ int hdf_old = 0; // write hdf file backward like davinci used to unsigned short iom_type_idx, iom_type_found; Alist alist[9]; alist[0] = make_alist("object", ID_UNK, NULL, &ob); alist[1] = make_alist("filename", ID_STRING, NULL, &filename); alist[2] = make_alist("type", ID_ENUM, NULL, &type); alist[3] = make_alist("title", ID_STRING, NULL, &title); alist[4] = make_alist("force", DV_INT32, NULL, &force); alist[5] = make_alist("separator", ID_STRING, NULL, &separator); alist[6] = make_alist("header", DV_INT32, NULL, &header); alist[7] = make_alist("hdf_old", DV_INT32, NULL, &hdf_old); alist[8].name = NULL; if (parse_args(func, arg, alist) == 0) return (NULL); /** ** Make sure user specified an object **/ if (ob == NULL) { parse_error("%s: No object specified.", func->name); return (NULL); } /** ** get filename. Verify type **/ if (filename == NULL) { parse_error("No filename specified."); return (NULL); } filename = dv_locate_file(filename); if (type == NULL) { parse_error("No type specified."); return (NULL); } /* ** Get title string */ if (title == NULL) { title = (char*)"DV data product"; } /* Check type against list of types supported by iomedley. */ iom_type_idx = iom_type_found = 0; while (iom_filetypes[iom_type_idx]) { if (!strcasecmp(type, iom_filetypes[iom_type_idx])) { iom_type_found = 1; break; } iom_type_idx++; } if (iom_type_found) dv_WriteIOM(ob, filename, type, force); else if (!strcasecmp(type, "raw")) dv_WriteRaw(ob, filename, force); else if (!strcasecmp(type, "vicar")) dv_WriteVicar(ob, filename, force); else if (!strcasecmp(type, "grd")) dv_WriteGRD(ob, filename, force, title, (char*)"davinci"); /* else if (!strcasecmp(type, "pnm")) dv_WritePNM(ob, filename, force); */ else if (!strcasecmp(type, "pgm")) dv_WritePGM(ob, filename, force); else if (!strcasecmp(type, "ppm")) dv_WritePPM(ob, filename, force); else if (!strcasecmp(type, "ascii")) WriteAscii(ob, filename, force); else if (!strcasecmp(type, "csv")) dv_WriteCSV(ob, filename, separator, header, force); else if (!strcasecmp(type, "ers")) dv_WriteERS(ob, filename, force); else if (!strcasecmp(type, "imath")) dv_WriteIMath(ob, filename, force); else if (!strcasecmp(type, "isis")) dv_WriteISIS(ob, filename, force, title); else if (!strcasecmp(type, "envi")) dv_WriteENVI(ob, filename, force); else if (!strcasecmp(type, "specpr")) { if (!force && file_exists(filename)) { parse_error("File %s already exists.\n", filename); return NULL; } WriteSpecpr(ob, filename, title); } /* ** Below here are optional packages */ #ifdef HAVE_LIBHDF5 else if (!strcasecmp(type, "hdf")) { struct stat statbuf; if (!force && !stat(filename, &statbuf)) { parse_error("File %s already exists.\n", filename); return NULL; } /* force ? */ WriteHDF5(-1, filename, ob, hdf_old); } #endif #ifdef BUILD_MODULE_SUPPORT else if (iomod_handler_for_type(type)) write_to_io_module(ob, filename, type, force); #endif #if 0 #ifdef HAVE_LIBMAGICK // else if (dvio_ValidGfx(type, GFX_type)) dv_WriteGFX_Image(ob, filename, force, GFX_type); else if (1) paramdvWriteImage(ob, filename, type, force); #endif #endif else { sprintf(error_buf, "Unrecognized type: %s", type); parse_error(NULL); return (NULL); } free(filename); return (NULL); }
virtual int init( int argc, const char *argv[] ) { txID = 0; blkID = 0; inputID = 0; outputID = 0; static uint64_t sz = 32 * 1000 * 1000; outputMap.setEmptyKey(empty); outputMap.resize(sz); optparse::Values &values = parser.parse_args(argc, argv); if (!file_exists("../blockchain/blockchain.sqlite")) { cutoffBlock = values.get("atBlock"); } else { sqlite3pp::database db("../blockchain/blockchain.sqlite"); sqlite3pp::query qry(db, "SELECT MAX(block_id) FROM blocks"); sqlite3pp::query::iterator i = qry.begin(); cutoffBlock = (uint64_t) atoi((*i).get<char const *>(0)) + 1; info("Resuming from block %" PRIu64 ".\n", cutoffBlock); } info("Dumping the blockchain..."); txFile = fopen("tx.txt", "w"); if (!txFile) sysErrFatal("Couldn't open file tx.txt for writing\n"); blockFile = fopen("blocks.txt", "w"); if (!blockFile) sysErrFatal("Couldn't open file blocks.txt for writing\n"); inputFile = fopen("txin.txt", "w"); if (!inputFile) sysErrFatal("Couldn't open file txin.txt for writing\n"); outputFile = fopen("txout.txt", "w"); if (!outputFile) sysErrFatal("Couldn't open file txout.txt for writing\n"); FILE *sqlFile = fopen("blockchain.sql", "w"); if (!sqlFile) sysErrFatal("Couldn't open file blockchain.sql for writing\n"); fprintf( sqlFile, "PRAGMA journal_mode=MEMORY;\n" "PRAGMA synchronous=0;\n" "CREATE TABLE IF NOT EXISTS blocks(\n" " block_id BIGINT NOT NULL PRIMARY KEY,\n" " block_hash TEXT NOT NULL,\n" " time BIGINT NOT NULL\n" ");\n" "\n" "CREATE TABLE IF NOT EXISTS tx(\n" " tx_id BIGINT NOT NULL PRIMARY KEY,\n" " tx_hash TEXT NOT NULL,\n" " block_id BIGINT NOT NULL,\n" " FOREIGN KEY (block_id) REFERENCES blocks (block_id)\n" ");\n" "\n" "CREATE TABLE IF NOT EXISTS txout(\n" " txout_id BIGINT NOT NULL PRIMARY KEY,\n" " address CHAR(40),\n" " txout_value BIGINT NOT NULL,\n" " tx_id BIGINT NOT NULL,\n" " txout_pos INT NOT NULL,\n" " FOREIGN KEY (tx_id) REFERENCES tx (tx_id)\n" ");\n" "\n" "CREATE TABLE IF NOT EXISTS txin(\n" " txin_id BIGINT NOT NULL PRIMARY KEY,\n" " txout_id BIGINT NOT NULL,\n" " tx_id BIGINT NOT NULL,\n" " txin_pos INT NOT NULL,\n" " FOREIGN KEY (tx_id) REFERENCES tx (tx_id)\n" ");\n" "CREATE INDEX IF NOT EXISTS x_txin_txout ON txin (txout_id);\n" "CREATE INDEX IF NOT EXISTS x_txout_address ON txout (address);\n" "CREATE INDEX IF NOT EXISTS x_txin_txid ON txin (tx_id);\n" "CREATE INDEX IF NOT EXISTS x_txout_txid ON txout (tx_id);\n" "CREATE INDEX IF NOT EXISTS x_txout_value ON txout (txout_value);\n" "CREATE VIEW IF NOT EXISTS tx_full AS SELECT blocks.time, tx.tx_hash, tx.tx_id, txout.address, txout.txout_value FROM txout LEFT JOIN tx ON (tx.tx_id = txout.tx_id) LEFT JOIN blocks ON (tx.block_id = blocks.block_id);\n" "\n" ); fclose(sqlFile); bashFile = fopen("blockchain.sh", "w"); if (!bashFile) sysErrFatal("Couldn't open file blockchain.sh for writing!\n"); // EDIT here: using /run/shm/ for performance on a server - modify to local path! fprintf( bashFile, "\n" "#!/bin/bash\n" "\n" "echo 'Recreating DB blockchain...'\n" "rm -f /run/shm/blockchain.sqlite\n" "mkdir ../blockchain\n" "cp -f ../blockchain/blockchain.sqlite /run/shm/\n" "sqlite3 /run/shm/blockchain.sqlite < blockchain.sql\n" "echo done\n" "echo\n" "rm -f blockchain.sql\n" "\n" "for i in blocks tx txin txout\n" "do\n" " echo Importing table $i ...\n" " echo \".import $i.txt $i\" | sqlite3 /run/shm/blockchain.sqlite\n" " echo done\n" " rm -f $i.txt\n" " echo\n" "done\n" "mv -f /run/shm/blockchain.sqlite ../blockchain/blockchain.sqlite\n" "rm -f blockchain.sh\n" "\n" ); fclose(bashFile); return 0; }
int main(int argc, char *argv[]) { int ret; int id; int op; struct sender_t *sender; char cfg[PATH_MAX]; const char * const config_path[2] = { CONFIG_CUSTOMIZE, CONFIG_INSTALL }; const struct option opts[] = { { "config", required_argument, NULL, 'c' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { NULL, 0, NULL, 0 } }; cfg[0] = 0; while ((op = getopt_long(argc, argv, "c:hV", opts, NULL)) != -1) { switch (op) { case 'c': strncpy(cfg, optarg, PATH_MAX); break; case 'h': usage(); return 0; case 'V': printf("version is %d.%d-%s, build by %s@%s\n", AP_MAJOR_VERSION, AP_MINOR_VERSION, AP_BUILD_VERSION, AP_BUILD_USER, AP_BUILD_TIME); return 0; case '?': usage(); return -1; } } if (!cfg[0]) { if (file_exists(config_path[0])) strncpy(cfg, config_path[0], PATH_MAX); else strncpy(cfg, config_path[1], PATH_MAX); } cfg[PATH_MAX - 1] = 0; ret = load_conf(cfg); if (ret) return -1; init_crash_reclassify(); ret = init_sender(); if (ret) return -1; init_event_queue(); ret = init_event_handler(); if (ret) return -1; ret = init_channels(); if (ret) return -1; while (1) { for_each_sender(id, sender, conf) { if (!sender) continue; uptime(sender); } } return 0; }
static int modfile_exists( INSTANCE * my, int * params ) { int r = file_exists( string_get( params[0] ) ) ; string_discard( params[0] ) ; return r ; }
int encode_file(char *filepath) { #ifdef DEBUG printf("processing %s\n", filepath); #endif // DEBUG if (!file_exists(filepath)) { fprintf(stderr, "Failed to decode file %s\n, file doesn't exitsts", filepath); return -1; } /** * Check if the file to be encoded is empty, if so, we don't need * to process it. */ struct stat filestat; if (-1 == stat(filepath, &filestat)) { perror(NULL); return -1; } if (0 == filestat.st_size) return 0; /** * If the file is not empty, we encode it and add a newline sign * when finish encoding the file */ char *input_path = clone_file(filepath); char *output_path = filepath; if (!file_exists(input_path) || !file_exists(output_path)) { fprintf(stderr, "Failed to make a clone of file %s\n", filepath); return -1; } int input_fd = open(input_path, O_RDONLY); int output_fd = open(output_path, O_WRONLY | O_TRUNC); if (-1 == input_fd || -1 == output_fd) { perror(NULL); return -1; } uint8_t read_buf[kNumRead], write_buf[kNumWrite]; int num_read, num_write; while (1) { memset(read_buf, 0, kNumRead); memset(write_buf, 0, kNumWrite); num_read = read(input_fd, read_buf, kNumRead); if (0 == num_read) break; // finish reading the file if (-1 == num_read) { fprintf(stderr, "Failed to read bytes from %s\n", input_path); return -1; } num_write = encode_block(read_buf, write_buf, num_read); if (num_write != write(output_fd, write_buf, num_write)) { fprintf(stderr, "Failed to write %d bytes into %s\n", num_write, output_path); return -1; } } /** * write a newline sign to the output_fd */ write_buf[0] = 0x0a; if (1 != write(output_fd, write_buf, 1)) { fprintf(stderr, "Failed to write the newline sign to %s\n", output_path); return -1; } /** * close everything, remove the file_clone */ close(input_fd); close(output_fd); if (-1 == unlink(input_path)) { fprintf(stderr, "Failed to remove file %s\n", input_path); return -1; } return 0; }
int main(int argc, const char * argv[]) { if ( (argc < 2) || (argc > 3) || ((argc == 3) && (strcmp("--config", argv[1]) != 0)) || (strcmp("-h", argv[1]) == 0) || (strcmp("--help", argv[1]) == 0) ) { fprintf(stderr, "Usage: %s config_path\n", argv[0]); fprintf(stderr, " %s --config js_device_path\n", argv[0]); exit(-1); } Display * display = open_display("xjoy2key"); if (display == NULL) return -1; struct config cfg; if (strcmp("--config", argv[1]) == 0) { probe_config(&cfg, argv[2]); fill_config(&cfg, display); write_config(&cfg, display, stdout); exit(0); } if (file_exists(argv[1])) read_config(&cfg, display, argv[1]); else { fprintf(stderr, "File doesn't exist: %s\n", argv[1]); exit(-1); } int fd = open(cfg.device, O_RDONLY); if (fd == -1) { fprintf(stderr, "Unable to open joystick '%s': %s\n", cfg.device, strerror(errno)); exit(-1); } struct sigaction new_action, old_action; new_action.sa_handler = sigint; sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; sigaction(SIGINT, NULL, &old_action); if (old_action.sa_handler != SIG_IGN) sigaction(SIGINT, &new_action, NULL); while (!done) { struct js_event event; if (read_timeout_usec(fd, &event, sizeof(struct js_event), 100) == sizeof(struct js_event)) { handle_event(&event, display, &cfg); } } XCloseDisplay(display); free_config(&cfg); return close(fd); }
/* main: * Guess what this function does. */ int main(int argc, char *argv[]) { PACKFILE *f; CFURLRef cf_url_ref; FSRef fs_ref; FSSpec fs_spec; IconFamilyHandle icon_family; Handle raw_data; char datafile[MAX_STRING_SIZE]; char bundle[MAX_STRING_SIZE]; char bundle_dir[MAX_STRING_SIZE]; char bundle_contents_dir[MAX_STRING_SIZE]; char bundle_contents_resources_dir[MAX_STRING_SIZE]; char bundle_contents_macos_dir[MAX_STRING_SIZE]; char bundle_contents_frameworks_dir[MAX_STRING_SIZE]; char *bundle_exe = NULL; char bundle_plist[MAX_STRING_SIZE]; char bundle_pkginfo[MAX_STRING_SIZE]; char bundle_icns[MAX_STRING_SIZE]; char bundle_version[MAX_STRING_SIZE]; char bundle_long_version[MAX_STRING_SIZE]; char *buffer = NULL; int arg, type = 0, result = 0; int i, size, x, y, mask_bit, mask_byte; unsigned char *data; install_allegro(SYSTEM_NONE, &errno, &atexit); set_color_depth(32); set_color_conversion(COLORCONV_TOTAL | COLORCONV_KEEP_TRANS); if (argc < 2) usage(); datafile[0] = '\0'; bundle[0] = '\0'; select_palette(black_palette); /* Parse command line and load any given resource */ for (arg = 2; arg < argc; arg++) { if (!strcmp(argv[arg], "-m")) flags |= F_MOVE; else if (!strcmp(argv[arg], "-e")) flags |= F_EMBED_FRAMEWORK; else if (!strcmp(argv[arg], "-o")) { if ((argc < arg + 2) || (bundle[0] != '\0')) usage(); strcpy(bundle, argv[++arg]); } else if (!strcmp(argv[arg], "-v")) { if (argc < arg + 2) usage(); flags |= F_GOT_VERSION; strcpy(bundle_version, argv[++arg]); } else if (!strcmp(argv[arg], "-V")) { if (argc < arg + 2) usage(); flags |= F_GOT_LONG_VERSION; strcpy(bundle_long_version, argv[++arg]); } else if (!strcmp(argv[arg], "-d")) { if (argc < arg + 2) usage(); strcpy(datafile, argv[++arg]); } else if ((!strcmp(argv[arg], "-16")) || (!strcmp(argv[arg], "-32")) || (!strcmp(argv[arg], "-48")) || (!strcmp(argv[arg], "-128"))) { if (argc < arg + 2) usage(); switch (atoi(&argv[arg][1])) { case 16: type = 0; break; case 32: type = 1; break; case 48: type = 2; break; case 128: type = 3; break; } if (load_resource(datafile, argv[++arg], &icon_data[type])) { result = -1; goto exit_error; } } else { if (load_resource(datafile, argv[arg], NULL)) { result = -1; goto exit_error; } } } buffer = malloc(4096); if (!buffer) { result = -1; goto exit_error_bundle; } bundle_exe = argv[1]; if (!exists(bundle_exe)) { fprintf(stderr, "Cannot locate executable file '%s'\n", bundle_exe); result = -1; goto exit_error; } if (bundle[0] == '\0') strcpy(bundle, bundle_exe); replace_extension(bundle_dir, bundle, "app", MAX_STRING_SIZE); strcpy(bundle_contents_dir, bundle_dir); strcat(bundle_contents_dir, "/Contents"); strcpy(bundle_contents_resources_dir, bundle_contents_dir); strcat(bundle_contents_resources_dir, "/Resources"); strcpy(bundle_contents_macos_dir, bundle_contents_dir); strcat(bundle_contents_macos_dir, "/MacOS"); strcpy(bundle_contents_frameworks_dir, bundle_contents_dir); strcat(bundle_contents_frameworks_dir, "/Frameworks"); bundle_icns[0] = '\0'; bundle_plist[0] = '\0'; bundle_pkginfo[0] = '\0'; /* Create bundle structure */ if ((mkdir(bundle_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_resources_dir, 0777) && (errno != EEXIST)) || (mkdir(bundle_contents_macos_dir, 0777) && (errno != EEXIST))) { fprintf(stderr, "Cannot create %s\n", bundle_dir); result = -1; goto exit_error_bundle; } /* Copy/move executable into the bundle */ if (copy_file(bundle_exe, bundle_contents_macos_dir)) { fprintf(stderr, "Cannot create %s\n", bundle_contents_macos_dir); result = -1; goto exit_error_bundle; } strcat(bundle_contents_macos_dir, "/"); strcat(bundle_contents_macos_dir, get_filename(bundle_exe)); chmod(bundle_contents_macos_dir, 0755); if (flags & F_MOVE) unlink(bundle_exe); /* Embed Allegro framework if requested */ if (flags & F_EMBED_FRAMEWORK) { if (!file_exists("/Library/Frameworks/Allegro.framework", FA_RDONLY | FA_DIREC, NULL)) { fprintf(stderr, "Cannot find Allegro framework\n"); result = -1; goto exit_error_bundle; } if (!exists("/Library/Frameworks/Allegro.framework/Resources/Embeddable")) { fprintf(stderr, "Cannot embed system wide Allegro framework; install embeddable version first!\n"); result = -1; goto exit_error_bundle; } sprintf(buffer, "/Developer/Tools/pbxcp -exclude .DS_Store -exclude CVS -resolve-src-symlinks /Library/Frameworks/Allegro.framework %s", bundle_contents_frameworks_dir); if ((mkdir(bundle_contents_frameworks_dir, 0777) && (errno != EEXIST)) || (system(buffer))) { fprintf(stderr, "Cannot create %s\n", bundle_contents_frameworks_dir); result = -1; goto exit_error_bundle; } } /* Setup the .icns resource */ if (flags & F_ICONS_DEFINED) { strcat(bundle_contents_resources_dir, "/"); strcat(bundle_contents_resources_dir, get_filename(bundle)); replace_extension(bundle_icns, bundle_contents_resources_dir, "icns", MAX_STRING_SIZE); icon_family = (IconFamilyHandle)NewHandle(0); for (i = 0; i < 4; i++) { if (flags & icon_data[i].defined) { /* Set 32bit RGBA data */ raw_data = NewHandle(icon_data[i].size * icon_data[i].size * 4); data = *(unsigned char **)raw_data; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { *data++ = geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getr32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getg32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); *data++ = getb32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); } } if (SetIconFamilyData(icon_family, icon_data[i].data, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource RGBA data\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); /* Set 8bit mask */ raw_data = NewHandle(icon_data[i].size * icon_data[i].size); data = *(unsigned char **)raw_data; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { *data++ = geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]); } } if (SetIconFamilyData(icon_family, icon_data[i].mask8, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource 8bit mask\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); /* Set 1bit mask */ if (icon_data[i].mask1) { size = ((icon_data[i].size * icon_data[i].size) + 7) / 8; raw_data = NewHandle(size * 2); data = *(unsigned char **)raw_data; mask_byte = 0; mask_bit = 7; for (y = 0; y < icon_data[i].size; y++) { for (x = 0; x < icon_data[i].size; x++) { if (geta32(((unsigned int *)(icon_data[i].scaled->line[y]))[x]) >= 0xfd) mask_byte |= (1 << mask_bit); mask_bit--; if (mask_bit < 0) { *data++ = mask_byte; mask_byte = 0; mask_bit = 7; } } } memcpy(*raw_data + size, *raw_data, size); if (SetIconFamilyData(icon_family, icon_data[i].mask1, raw_data) != noErr) { DisposeHandle(raw_data); fprintf(stderr, "Error setting %dx%d icon resource 1bit mask\n", icon_data[i].size, icon_data[i].size); result = -1; goto exit_error_bundle; } DisposeHandle(raw_data); } } } f = pack_fopen(bundle_icns, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } pack_fclose(f); cf_url_ref = CFURLCreateWithBytes(kCFAllocatorDefault, (unsigned char *)bundle_icns, strlen(bundle_icns), 0, NULL); if (!cf_url_ref) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } CFURLGetFSRef(cf_url_ref, &fs_ref); CFRelease(cf_url_ref); if ((FSGetCatalogInfo(&fs_ref, kFSCatInfoNone, NULL, NULL, &fs_spec, NULL)) || (WriteIconFile(icon_family, &fs_spec) != noErr)) { fprintf(stderr, "Cannot create %s\n", bundle_icns); result = -1; goto exit_error_bundle; } DisposeHandle((Handle)icon_family); } /* Setup Info.plist */ sprintf(bundle_plist, "%s/Info.plist", bundle_contents_dir); f = pack_fopen(bundle_plist, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_plist); result = -1; goto exit_error_bundle; } sprintf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" "<plist version=\"1.0\">\n" "<dict>\n" "\t<key>CFBundleExecutable</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleInfoDictionaryVersion</key>\n" "\t<string>6.0</string>\n" "\t<key>CFBundlePackageType</key>\n" "\t<string>APPL</string>\n" "\t<key>CFBundleSignature</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleVersion</key>\n" "\t<string>%s</string>\n" "\t<key>CFBundleDocumentTypes</key>\n" "\t<array>\n" "\t\t<dict>\n" "\t\t\t<key>CFBundleTypeExtensions</key>\n" "\t\t\t<array>\n" "\t\t\t\t<string>*</string>\n" "\t\t\t</array>\n" "\t\t\t<key>CFBundleTypeName</key>\n" "\t\t\t<string>NSStringPboardType</string>\n" "\t\t\t<key>CFBundleTypeOSTypes</key>\n" "\t\t\t<array>\n" "\t\t\t\t<string>****</string>\n" "\t\t\t</array>\n" "\t\t\t<key>CFBundleTypeRole</key>\n" "\t\t\t<string>Viewer</string>\n" "\t\t</dict>\n" "\t</array>\n", get_filename(bundle_exe), "????", (flags & F_GOT_VERSION) ? bundle_version : "1.0"); pack_fputs(buffer, f); if (flags & F_GOT_LONG_VERSION) { sprintf(buffer, "\t<key>CFBundleGetInfoString</key>\n" "\t<string>%s</string>\n", bundle_long_version); pack_fputs(buffer, f); } if (flags & F_ICONS_DEFINED) { sprintf(buffer, "\t<key>CFBundleIconFile</key>\n" "\t<string>%s</string>\n", get_filename(bundle_icns)); pack_fputs(buffer, f); } pack_fputs("</dict>\n</plist>\n", f); pack_fclose(f); /* Setup PkgInfo */ sprintf(bundle_pkginfo, "%s/PkgInfo", bundle_contents_dir); f = pack_fopen(bundle_pkginfo, F_WRITE); if (!f) { fprintf(stderr, "Cannot create %s\n", bundle_pkginfo); result = -1; goto exit_error_bundle; } pack_fputs("APPL????", f); pack_fclose(f); exit_error: if (buffer) free(buffer); for (i = 0; i < 4; i++) { if (icon_data[i].original) destroy_bitmap(icon_data[i].original); if (icon_data[i].workspace) destroy_bitmap(icon_data[i].workspace); if (icon_data[i].scaled) destroy_bitmap(icon_data[i].scaled); } return result; exit_error_bundle: sprintf(buffer, "%s/%s", bundle_contents_macos_dir, get_filename(bundle_exe)); unlink(buffer); unlink(bundle_plist); unlink(bundle_pkginfo); unlink(bundle_icns); rmdir(bundle_dir); rmdir(bundle_contents_dir); rmdir(bundle_contents_resources_dir); rmdir(bundle_contents_macos_dir); goto exit_error; }