GF_EXPORT const char *gf_esd_get_textual_description(GF_ESD *esd) { if (!esd || !esd->decoderConfig) return "Bad parameter"; switch (esd->decoderConfig->streamType) { case GF_STREAM_OD: return "MPEG-4 Object Descriptor"; case GF_STREAM_OCR: return "MPEG-4 Object Clock Reference"; case GF_STREAM_SCENE: switch (esd->decoderConfig->objectTypeIndication) { case 0x0: case 0x1: case 0x2: case 0x3: case 0xFF: return "MPEG-4 BIFS Scene Description"; case GPAC_OTI_SCENE_BIFS_EXTENDED: return "MPEG-4 Extended BIFS Scene Description"; case GPAC_OTI_SCENE_AFX: if (!esd->decoderConfig->decoderSpecificInfo || !esd->decoderConfig->decoderSpecificInfo->data) return "AFX Unknown"; return gf_afx_get_type_description(esd->decoderConfig->decoderSpecificInfo->data[0]); case GPAC_OTI_SCENE_LASER: { GF_LASERConfig l_cfg; gf_odf_get_laser_config(esd->decoderConfig->decoderSpecificInfo, &l_cfg); if (! l_cfg.newSceneIndicator ) return "LASeR Scene Segment Description"; } return "LASeR Scene Description"; case GPAC_OTI_SCENE_SYNTHESIZED_TEXTURE: return "MPEG-4 Synthesized Texture"; case GPAC_OTI_SCENE_SAF: return "MPEG-4 SAF"; case GPAC_OTI_3GPP2_CMF: return "3GPP2 CMF"; default: return "Unknown Scene Type"; } break; case GF_STREAM_VISUAL: switch (esd->decoderConfig->objectTypeIndication) { case GPAC_OTI_VIDEO_MPEG2_SIMPLE: return "MPEG-2 Visual Simple Profile"; case GPAC_OTI_VIDEO_MPEG2_MAIN: return "MPEG-2 Visual Main Profile"; case GPAC_OTI_VIDEO_MPEG2_SNR: return "MPEG-2 Visual SNR Profile"; case GPAC_OTI_VIDEO_MPEG2_SPATIAL: return "MPEG-2 Visual SNR Profile"; case GPAC_OTI_VIDEO_MPEG2_HIGH: return "MPEG-2 Visual SNR Profile"; case GPAC_OTI_VIDEO_MPEG2_422: return "MPEG-2 Visual SNR Profile"; case GPAC_OTI_VIDEO_MPEG1: return "MPEG-1 Video"; case GPAC_OTI_IMAGE_JPEG: return "JPEG Image"; case GPAC_OTI_IMAGE_PNG: return "PNG Image"; case GPAC_OTI_IMAGE_JPEG_2000: return "JPEG2000 Image"; case GPAC_OTI_VIDEO_MPEG4_PART2: return "MPEG-4 Part 2 Video"; case GPAC_OTI_VIDEO_AVC: return "MPEG-4 AVC|H264 Video"; case GPAC_OTI_VIDEO_SVC: return "MPEG-4 SVC Video"; case GPAC_OTI_VIDEO_AVC_PS: return "MPEG-4 AVC|H264 Parameter Set"; case GPAC_OTI_VIDEO_HEVC: return "MPEG-H HEVC Video"; case GPAC_OTI_VIDEO_SHVC: return "MPEG-H SHVC Video"; case GPAC_OTI_MEDIA_FFMPEG: return "GPAC FFMPEG Private Video"; case GPAC_OTI_VIDEO_SMPTE_VC1: return "SMPTE VC-1 Video"; case GPAC_OTI_VIDEO_DIRAC: return "Dirac Video"; default: return "Unknown Video type"; } break; case GF_STREAM_AUDIO: switch (esd->decoderConfig->objectTypeIndication) { case GPAC_OTI_AUDIO_AAC_MPEG2_MP: return "MPEG-2 AAC Main Profile"; case GPAC_OTI_AUDIO_AAC_MPEG2_LCP: return "MPEG-2 AAC Low Complexity Profile"; case GPAC_OTI_AUDIO_AAC_MPEG2_SSRP: return "MPEG-2 AAC Scaleable Sampling Rate Profile"; case GPAC_OTI_AUDIO_MPEG2_PART3: return "MPEG-2 Audio Part 3"; case GPAC_OTI_AUDIO_MPEG1: return "MPEG-1 Audio"; case GPAC_OTI_AUDIO_AAC_MPEG4: { #ifdef GPAC_DISABLE_AV_PARSERS return "MPEG-4 AAC"; #else GF_M4ADecSpecInfo a_cfg; if (!esd->decoderConfig->decoderSpecificInfo) return "MPEG-4 AAC"; gf_m4a_get_config(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, &a_cfg); return gf_m4a_object_type_name(a_cfg.base_object_type); #endif } break; case GPAC_OTI_MEDIA_FFMPEG: return "GPAC FFMPEG Private Audio"; case GPAC_OTI_AUDIO_EVRC_VOICE: return "EVRC Voice"; case GPAC_OTI_AUDIO_SMV_VOICE: return "SMV Voice"; case GPAC_OTI_AUDIO_AC3: return "AC-3 audio"; case GPAC_OTI_AUDIO_EAC3: return "Enhanced AC-3 Audio"; case GPAC_OTI_AUDIO_DRA: return "DRA Audio"; case GPAC_OTI_AUDIO_ITU_G719: return "ITU G719 Audio"; case GPAC_OTI_AUDIO_DTS_CA: return "DTS Coherent Acoustics audio"; case GPAC_OTI_AUDIO_DTS_HD_HR: return "DTS-HD High Resolution audio"; case GPAC_OTI_AUDIO_DTS_HD_MASTER: return "DTS-HD Master audios"; default: return "Unknown Audio Type"; } break; case GF_STREAM_MPEG7: return "MPEG-7 Description"; case GF_STREAM_IPMP: return "MPEG-4 IPMP"; case GF_STREAM_OCI: return "MPEG-4 OCI"; case GF_STREAM_MPEGJ: return "MPEG-4 MPEG-J"; case GF_STREAM_INTERACT: return "MPEG-4 User Interaction"; case GF_STREAM_IPMP_TOOL: return "MPEG-4 IPMP Tool"; case GF_STREAM_FONT: return "MPEG-4 Font Data"; case GF_STREAM_TEXT: return "MPEG-4 Streaming Text"; case GF_STREAM_ND_SUBPIC: return "Nero Digital Subpicture"; case GF_STREAM_PRIVATE_SCENE: switch (esd->decoderConfig->objectTypeIndication) { case GPAC_OTI_PRIVATE_SCENE_GENERIC: { char *ext = strchr(esd->decoderConfig->decoderSpecificInfo->data + 4, '.'); if (!ext) return "GPAC Internal Scene Description"; ext += 1; if (!strnicmp(ext, "bt", 2)) return "BT Scene Description"; if (!strnicmp(ext, "xmt", 2)) return "XMT Scene Description"; if (!strnicmp(ext, "wrl", 3)) return "VRML Scene Description"; if (!strnicmp(ext, "x3d", 3)) return "W3D Scene Description"; if (!strnicmp(ext, "x3dv", 4)) return "X3D Scene Description"; if (!strnicmp(ext, "swf", 3)) return "Flash (SWF) Scene Description"; if (!strnicmp(ext, "xsr", 3)) return "LASeR-ML Scene Description"; if (!strnicmp(ext, "wgt", 3)) return "W3C Widget Package"; if (!strnicmp(ext, "mgt", 3)) return "MPEG-U Widget Package"; } return "GPAC Internal Scene Description"; case GPAC_OTI_PRIVATE_SCENE_SVG: return "SVG"; case GPAC_OTI_PRIVATE_SCENE_LASER: return "LASeR (XML)"; case GPAC_OTI_PRIVATE_SCENE_XBL: return "XBL"; case GPAC_OTI_PRIVATE_SCENE_EPG: return "DVB Event Information"; case GPAC_OTI_PRIVATE_SCENE_WGT: return "W3C/MPEG-U Widget"; case GPAC_OTI_SCENE_SVG: return "SVG over RTP"; case GPAC_OTI_SCENE_SVG_GZ: return "SVG+gz over RTP"; case GPAC_OTI_SCENE_DIMS: return "3GPP DIMS"; default: return "Unknown Scene Description"; } break; case GF_STREAM_PRIVATE_MEDIA: return "Opaque Decoder"; case GF_STREAM_4CC: return gf_4cc_to_str(esd->decoderConfig->objectTypeIndication); default: return "Unknown Media Type"; } }
/*! */ xbShort xbDbf::PutField(const xbShort FieldNo, const char *buf) { xbShort len, i; char * startpos; char * tp; /* target pointer */ const char * sp; /* source pointer */ if( FieldNo < 0 || FieldNo >= NoOfFields ) return XB_INVALID_FIELDNO; if( DbfStatus != XB_UPDATED ){ DbfStatus = XB_UPDATED; memcpy( RecBuf2, RecBuf, RecordLen ); } if( SchemaPtr[FieldNo].Type == 'L' && !ValidLogicalData( buf )) return XB_INVALID_DATA; else if(( SchemaPtr[FieldNo].Type == 'F' || SchemaPtr[FieldNo].Type == 'N' ) && !ValidNumericData( buf )) return XB_INVALID_DATA; else if( SchemaPtr[FieldNo].Type == 'D' ){ xbDate d; if( !d.DateIsValid( buf )) return XB_INVALID_DATA; } if( SchemaPtr[FieldNo].Type == 'C' && SchemaPtr[FieldNo].NoOfDecs > 0 ) memset( SchemaPtr[FieldNo].Address, 0x20, SchemaPtr[FieldNo].LongFieldLen ); else memset( SchemaPtr[FieldNo].Address, 0x20, SchemaPtr[FieldNo].FieldLen ); len = strlen( buf ); if(( SchemaPtr[FieldNo].Type == 'N' || SchemaPtr[FieldNo].Type == 'F') && len > SchemaPtr[FieldNo].FieldLen ) return XB_INVALID_DATA; else if( len > SchemaPtr[FieldNo].FieldLen ) len = SchemaPtr[FieldNo].FieldLen; if( SchemaPtr[FieldNo].Type == 'F' || SchemaPtr[FieldNo].Type == 'N' || SchemaPtr[FieldNo].Type == 'M') { const char *sdp = strchr( buf, '.' ); /* source decimal point */ len = 0; sp =buf; while( *sp && *sp != '.' ) { len++; sp++; } if( SchemaPtr[FieldNo].NoOfDecs > 0 ){ /* do the right of decimal area */ tp = SchemaPtr[FieldNo].Address; tp += SchemaPtr[FieldNo].FieldLen - SchemaPtr[FieldNo].NoOfDecs - 1; *tp++ = '.'; sp = sdp; if( sp ) sp++; for( i = 0; i < SchemaPtr[FieldNo].NoOfDecs; i++ ) if( sp && *sp ) *tp++ = *sp++; else *tp++ = '0'; startpos= SchemaPtr[FieldNo].Address + SchemaPtr[FieldNo].FieldLen - SchemaPtr[FieldNo].NoOfDecs - len - 1; } else { startpos=SchemaPtr[FieldNo].Address+SchemaPtr[FieldNo].FieldLen-len; } } else startpos = SchemaPtr[FieldNo].Address; memcpy( startpos, buf, len ); return 0; }
void set_global_values(const char *configuration_file) { if (!configuration_file) return; pmesg(LOG_INFO, __FILE__, __LINE__, "Loading configuration from '%s'\n", configuration_file); oph_server_params = hashtbl_create(HASHTBL_KEY_NUMBER, NULL); if (!oph_server_params) return; char tmp[OPH_MAX_STRING_SIZE]; char *value; FILE *file = fopen(configuration_file, "r"); if (file) { char key[OPH_MAX_STRING_SIZE], value2[OPH_MAX_STRING_SIZE]; while (fgets(tmp, OPH_MAX_STRING_SIZE, file)) { if (strlen(tmp)) { tmp[strlen(tmp) - 1] = '\0'; if (tmp[0] == OPH_COMMENT_MARK) continue; // Skip possible commented lines value = strchr(tmp, OPH_SEPARATOR_KV[0]); if (value) { value++; snprintf(key, value - tmp, "%s", tmp); if (value[0]) { if (value[0] == OPH_SUBSTITUTION_MARK && !strncasecmp(value + 1, OPH_SERVER_LOCATION_STR, strlen(OPH_SERVER_LOCATION_STR))) { snprintf(value2, OPH_MAX_STRING_SIZE, "%s%s", oph_server_location, value + strlen(OPH_SERVER_LOCATION_STR) + 1); value = value2; } hashtbl_insert(oph_server_params, key, value); } else hashtbl_insert(oph_server_params, key, ""); pmesg(LOG_DEBUG, __FILE__, __LINE__, "Read %s=%s\n", key, value); } } } fclose(file); } // Pre-process if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_TIMEOUT))) oph_server_timeout = strtol(value, NULL, 10); if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_INACTIVITY_TIMEOUT))) oph_server_inactivity_timeout = strtol(value, NULL, 10); if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_WORKFLOW_TIMEOUT))) oph_server_workflow_timeout = strtol(value, NULL, 10); if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_SERVER_FARM_SIZE))) oph_server_farm_size = (unsigned int) strtol(value, NULL, 10); if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_QUEUE_SIZE))) oph_server_queue_size = (unsigned int) strtol(value, NULL, 10); if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_AUTO_RETRY))) oph_auto_retry = (unsigned int) strtol(value, NULL, 10); if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_POLL_TIME))) oph_server_poll_time = (unsigned int) strtol(value, NULL, 10); if ((value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_BASE_BACKOFF))) oph_base_backoff = (unsigned int) strtol(value, NULL, 10); if (!logfile && (value = hashtbl_get(oph_server_params, OPH_SERVER_CONF_LOGFILE))) { pmesg(LOG_INFO, __FILE__, __LINE__, "Selected log file '%s'\n", value); logfile = fopen(value, "a"); if (logfile) set_log_file(logfile); // Redirect stdout and stderr to logfile if (!freopen(value, "a", stdout)) pmesg(LOG_ERROR, __FILE__, __LINE__, "Error in redirect stdout to logfile\n"); if (!freopen(value, "a", stderr)) pmesg(LOG_ERROR, __FILE__, __LINE__, "Error in redirect stderr to logfile\n"); } // Default values if (!oph_server_protocol && !(oph_server_protocol = hashtbl_get(oph_server_params, OPH_SERVER_CONF_PROTOCOL))) { hashtbl_insert(oph_server_params, OPH_SERVER_CONF_PROTOCOL, OPH_DEFAULT_PROTOCOL); oph_server_protocol = hashtbl_get(oph_server_params, OPH_SERVER_CONF_PROTOCOL); } if (!oph_server_host && !(oph_server_host = hashtbl_get(oph_server_params, OPH_SERVER_CONF_HOST))) { if (!gethostname(tmp, OPH_MAX_STRING_SIZE)) hashtbl_insert(oph_server_params, OPH_SERVER_CONF_HOST, tmp); else hashtbl_insert(oph_server_params, OPH_SERVER_CONF_HOST, OPH_DEFAULT_HOST); oph_server_host = hashtbl_get(oph_server_params, OPH_SERVER_CONF_HOST); } if (!oph_server_port && !(oph_server_port = hashtbl_get(oph_server_params, OPH_SERVER_CONF_PORT))) { hashtbl_insert(oph_server_params, OPH_SERVER_CONF_PORT, OPH_DEFAULT_PORT); oph_server_port = hashtbl_get(oph_server_params, OPH_SERVER_CONF_PORT); } if (!(oph_server_cert = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CERT))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SERVER_CERT, oph_server_location); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_CERT, tmp); oph_server_cert = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CERT); } if (!(oph_server_ca = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CA))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SERVER_CA, oph_server_location); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_CA, tmp); oph_server_ca = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CA); } if (!(oph_server_password = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CERT_PASSWORD))) { hashtbl_insert(oph_server_params, OPH_SERVER_CONF_CERT_PASSWORD, OPH_SERVER_PASSWORD); oph_server_password = hashtbl_get(oph_server_params, OPH_SERVER_CONF_CERT_PASSWORD); } if (!(oph_rmanager_conf_file = hashtbl_get(oph_server_params, OPH_SERVER_CONF_RMANAGER_CONF_FILE))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_RMANAGER_CONF_FILE, oph_server_location); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_RMANAGER_CONF_FILE, tmp); oph_rmanager_conf_file = hashtbl_get(oph_server_params, OPH_SERVER_CONF_RMANAGER_CONF_FILE); } if (!(oph_auth_location = hashtbl_get(oph_server_params, OPH_SERVER_CONF_AUTHZ_DIR))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SERVER_AUTHZ, oph_server_location); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_AUTHZ_DIR, tmp); oph_auth_location = hashtbl_get(oph_server_params, OPH_SERVER_CONF_AUTHZ_DIR); } if (!(oph_txt_location = hashtbl_get(oph_server_params, OPH_SERVER_CONF_TXT_DIR))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_TXT_LOCATION, oph_server_location); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_TXT_DIR, tmp); oph_txt_location = hashtbl_get(oph_server_params, OPH_SERVER_CONF_TXT_DIR); } if (!(oph_web_server = hashtbl_get(oph_server_params, OPH_SERVER_CONF_WEB_SERVER))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_WEB_SERVER); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_WEB_SERVER, tmp); oph_web_server = hashtbl_get(oph_server_params, OPH_SERVER_CONF_WEB_SERVER); } if (!(oph_web_server_location = hashtbl_get(oph_server_params, OPH_SERVER_CONF_WEB_SERVER_LOCATION))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_WEB_SERVER_LOCATION); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_WEB_SERVER_LOCATION, tmp); oph_web_server_location = hashtbl_get(oph_server_params, OPH_SERVER_CONF_WEB_SERVER_LOCATION); } if (!(oph_operator_client = hashtbl_get(oph_server_params, OPH_SERVER_CONF_OPERATOR_CLIENT))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_OPERATOR_CLIENT); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_OPERATOR_CLIENT, tmp); oph_operator_client = hashtbl_get(oph_server_params, OPH_SERVER_CONF_OPERATOR_CLIENT); } if (!(oph_ip_target_host = hashtbl_get(oph_server_params, OPH_SERVER_CONF_IP_TARGET_HOST))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_IP_TARGET_HOST); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_IP_TARGET_HOST, tmp); oph_ip_target_host = hashtbl_get(oph_server_params, OPH_SERVER_CONF_IP_TARGET_HOST); } if (!(oph_subm_user = hashtbl_get(oph_server_params, OPH_SERVER_CONF_SUBM_USER))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SUBM_USER); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_SUBM_USER, tmp); oph_subm_user = hashtbl_get(oph_server_params, OPH_SERVER_CONF_SUBM_USER); } if (!(oph_subm_user_publk = hashtbl_get(oph_server_params, OPH_SERVER_CONF_SUBM_USER_PUBLK))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SUBM_USER_PUBLK); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_SUBM_USER_PUBLK, tmp); oph_subm_user_publk = hashtbl_get(oph_server_params, OPH_SERVER_CONF_SUBM_USER_PUBLK); } if (!(oph_subm_user_privk = hashtbl_get(oph_server_params, OPH_SERVER_CONF_SUBM_USER_PRIVK))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SUBM_USER_PRIVK); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_SUBM_USER_PRIVK, tmp); oph_subm_user_privk = hashtbl_get(oph_server_params, OPH_SERVER_CONF_SUBM_USER_PRIVK); } if (!(oph_xml_operators = hashtbl_get(oph_server_params, OPH_SERVER_CONF_XML_URL))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_CLIENT_XML_URL); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_XML_URL, tmp); oph_xml_operators = hashtbl_get(oph_server_params, OPH_SERVER_CONF_XML_URL); } if (!(oph_xml_operator_dir = hashtbl_get(oph_server_params, OPH_SERVER_CONF_XML_DIR))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_SERVER_XML_EXT_PATH); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_XML_DIR, tmp); oph_xml_operator_dir = hashtbl_get(oph_server_params, OPH_SERVER_CONF_XML_DIR); } if (!(oph_user_notifier = hashtbl_get(oph_server_params, OPH_SERVER_CONF_NOTIFIER))) { snprintf(tmp, OPH_MAX_STRING_SIZE, OPH_USER_NOTIFIER); hashtbl_insert(oph_server_params, OPH_SERVER_CONF_NOTIFIER, tmp); oph_user_notifier = hashtbl_get(oph_server_params, OPH_SERVER_CONF_NOTIFIER); } if (!(oph_base_src_path = hashtbl_get(oph_server_params, OPH_SERVER_CONF_BASE_SRC_PATH))) { hashtbl_insert(oph_server_params, OPH_SERVER_CONF_BASE_SRC_PATH, OPH_BASE_SRC_PATH); oph_base_src_path = hashtbl_get(oph_server_params, OPH_SERVER_CONF_BASE_SRC_PATH); } oph_json_location = oph_web_server_location; // Position of JSON Response will be the same of web server }
static int tcl_mv_cp(Tcl_Interp *irp, int argc, char **argv, int copy) { char *p, *fn = NULL, *oldpath = NULL, *s = NULL, *s1 = NULL; char *newfn = NULL, *newpath = NULL; int ok = 0, only_first, skip_this; FILE *fdb_old, *fdb_new; filedb_entry *fdbe_old, *fdbe_new; long where; BADARGS(3, 3, " oldfilepath newfilepath"); malloc_strcpy(fn, argv[1]); p = strrchr(fn, '/'); if (p != NULL) { *p = 0; malloc_strcpy(s, fn); strcpy(fn, p + 1); if (!resolve_dir("/", s, &oldpath, -1)) { /* Tcl can do * anything */ Tcl_AppendResult(irp, "-1", NULL); /* Invalid source */ my_free(fn); my_free(oldpath); return TCL_OK; } my_free(s); } else malloc_strcpy(oldpath, "/"); malloc_strcpy(s, argv[2]); if (!resolve_dir("/", s, &newpath, -1)) { /* Destination is not just a directory */ p = strrchr(s, '/'); if (!p) { malloc_strcpy(newfn, s); s[0] = 0; } else { *p = 0; malloc_strcpy(newfn, p + 1); } my_free(newpath); if (!resolve_dir("/", s, &newpath, -1)) { Tcl_AppendResult(irp, "-2", NULL); /* Invalid desto */ my_free(newpath); my_free(s); my_free(newfn); return TCL_OK; } } else malloc_strcpy(newfn, ""); my_free(s); /* Stupidness checks */ if ((!strcmp(oldpath, newpath)) && (!newfn[0] || !strcmp(newfn, fn))) { my_free(newfn); my_free(fn); my_free(oldpath); my_free(newpath); Tcl_AppendResult(irp, "-3", NULL); /* Stupid copy to self */ return TCL_OK; } /* Be aware of 'cp * this.file' possibility: ONLY COPY FIRST ONE */ if ((strchr(fn, '?') || strchr(fn, '*')) && newfn[0]) only_first = 1; else only_first = 0; fdb_old = filedb_open(oldpath, 0); if (!strcmp(oldpath, newpath)) fdb_new = fdb_old; else fdb_new = filedb_open(newpath, 0); if (!fdb_old || !fdb_new) { my_free(newfn); my_free(fn); my_free(oldpath); my_free(newpath); if (fdb_old) filedb_close(fdb_old); else if (fdb_new) filedb_close(fdb_new); Tcl_AppendResult(irp, "-5", NULL); /* DB access failed */ return -1; } filedb_readtop(fdb_old, NULL); fdbe_old = filedb_matchfile(fdb_old, ftell(fdb_old), fn); if (!fdbe_old) { my_free(newfn); my_free(fn); my_free(oldpath); my_free(newpath); if (fdb_new != fdb_old) filedb_close(fdb_new); filedb_close(fdb_old); Tcl_AppendResult(irp, "-4", NULL); /* No match */ return -2; } while (fdbe_old) { where = ftell(fdb_old); skip_this = 0; if (!(fdbe_old->stat & (FILE_HIDDEN | FILE_DIR))) { s = nmalloc(strlen(dccdir) + strlen(oldpath) + strlen(fdbe_old->filename) + 2); s1 = nmalloc(strlen(dccdir) + strlen(newpath) + strlen(newfn[0] ? newfn : fdbe_old->filename) + 2); sprintf(s, "%s%s%s%s", dccdir, oldpath, oldpath[0] ? "/" : "", fdbe_old->filename); sprintf(s1, "%s%s%s%s", dccdir, newpath, newpath[0] ? "/" : "", newfn[0] ? newfn : fdbe_old->filename); if (!strcmp(s, s1)) { Tcl_AppendResult(irp, "-3", NULL); /* Stupid copy to self */ skip_this = 1; } /* Check for existence of file with same name in new dir */ filedb_readtop(fdb_new, NULL); fdbe_new = filedb_matchfile(fdb_new, ftell(fdb_new), newfn[0] ? newfn : fdbe_old->filename); if (fdbe_new) { /* It's ok if the entry in the new dir is a normal file (we'll * just scrap the old entry and overwrite the file) -- but if * it's a directory, this file has to be skipped. */ if (fdbe_new->stat & FILE_DIR) skip_this = 1; else filedb_delfile(fdb_new, fdbe_new->pos); free_fdbe(&fdbe_new); } if (!skip_this) { if ((fdbe_old->sharelink) || ((copy ? copyfile(s, s1) : movefile(s, s1)) == 0)) { /* Raw file moved okay: create new entry for it */ ok++; fdbe_new = malloc_fdbe(); fdbe_new->stat = fdbe_old->stat; /* We don't have to worry about any entries to be * NULL, because malloc_strcpy takes care of that. */ malloc_strcpy(fdbe_new->flags_req, fdbe_old->flags_req); malloc_strcpy(fdbe_new->chan, fdbe_old->chan); malloc_strcpy(fdbe_new->filename, fdbe_old->filename); malloc_strcpy(fdbe_new->desc, fdbe_old->desc); if (newfn[0]) malloc_strcpy(fdbe_new->filename, newfn); malloc_strcpy(fdbe_new->uploader, fdbe_old->uploader); fdbe_new->uploaded = fdbe_old->uploaded; fdbe_new->size = fdbe_old->size; fdbe_new->gots = fdbe_old->gots; malloc_strcpy(fdbe_new->sharelink, fdbe_old->sharelink); filedb_addfile(fdb_new, fdbe_new); if (!copy) filedb_delfile(fdb_old, fdbe_old->pos); free_fdbe(&fdbe_new); } } my_free(s); my_free(s1); } free_fdbe(&fdbe_old); fdbe_old = filedb_matchfile(fdb_old, where, fn); if (ok && only_first) { free_fdbe(&fdbe_old); } } if (fdb_old != fdb_new) filedb_close(fdb_new); filedb_close(fdb_old); if (!ok) Tcl_AppendResult(irp, "-4", NULL); /* No match */ else { char x[30]; sprintf(x, "%d", ok); Tcl_AppendResult(irp, x, NULL); } my_free(newfn); my_free(fn); my_free(oldpath); my_free(newpath); return TCL_OK; }
/* HBB 20010121: added code that attempts to fix rounding-induced * off-by-one errors in 10^%T and similar output formats */ static void mant_exp( double log10_base, double x, TBOOLEAN scientific, /* round to power of 3 */ double *m, /* results */ int *p, const char *format) /* format string for fixup */ { int sign = 1; double l10; int power; double mantissa; /*{{{ check 0 */ if (x == 0) { if (m) *m = 0; if (p) *p = 0; return; } /*}}} */ /*{{{ check -ve */ if (x < 0) { sign = (-1); x = (-x); } /*}}} */ l10 = log10(x) / log10_base; power = floor(l10); mantissa = pow(10.0, log10_base * (l10 - power)); /* round power to an integer multiple of 3, to get what's * sometimes called 'scientific' or 'engineering' notation. Also * useful for handling metric unit prefixes like 'kilo' or 'micro' * */ if (scientific) { /* Scientific mode makes no sense whatsoever if the base of * the logarithmic axis is anything but 10.0 */ assert(log10_base == 1.0); /* HBB FIXED 20040701: negative modulo positive may yield * negative result. But we always want an effectively * positive modulus --> adjust input by one step */ switch (power % 3) { case -1: power -= 3; case 2: mantissa *= 100; break; case -2: power -= 3; case 1: mantissa *= 10; break; case 0: break; default: int_error (NO_CARET, "Internal error in scientific number formatting"); } power -= (power % 3); } /* HBB 20010121: new code for decimal mantissa fixups. Looks at * format string to see how many decimals will be put there. Iff * the number is so close to an exact power of 10 that it will be * rounded up to 10.0e??? by an sprintf() with that many digits of * precision, increase the power by 1 to get a mantissa in the * region of 1.0. If this handling is not wanted, pass NULL as * the format string */ /* HBB 20040521: extended to also work for bases other than 10.0 */ if (format) { double actual_base = (scientific ? 1000 : pow(10.0, log10_base)); int precision = 0; double tolerance; format = strchr (format, '.'); if (format != NULL) /* a decimal point was found in the format, so use that * precision. */ precision = strtol(format + 1, NULL, 10); /* See if mantissa would be right on the border. The * condition to watch out for is that the mantissa is within * one printing precision of the next power of the logarithm * base. So add the 0.5*10^-precision to the mantissa, and * see if it's now larger than the base of the scale */ tolerance = pow(10.0, -precision) / 2; if (mantissa + tolerance >= actual_base) { mantissa /= actual_base; power += (scientific ? 3 : 1); } } if (m) *m = sign * mantissa; if (p) *p = power; }
int32_t TestFontClusters(void) { #ifdef _USE_LEO_ int32_t name; int i,j; int nClust; int porog=50; // test !!! int numInvalid; LeoFieldSetup fs={0}; RecRaster rec; RecObject ro={0}; LeoPageSetup ps={0}; ClustInfo cluInfo; uchar addLet,resLet; #ifdef _SAVE_INVALID_CLU_ FILE *fp; #endif curNumFile++; nClust=FONGetClustCount(); set_alphabet(alphabet1, alpha_str); #ifdef _SAVE_INVALID_CLU_ fp=fopen("clust.tst","at"); fprintf(fp,"file %d\n",curNumFile); #endif LEOSetPlatform(LEOGetCPU()); fs.nStyle = LS_PRINT; memcpy(fs.AlphaTable,alphabet1,256); LEOSetupField(&fs); for(i=0,numInvalid=0;i<nClust;i++) { cluInfo.let = 0; j=FONGetClustInfo(&cluInfo,i+1); if(j<=0) continue; if(cluInfo.attr & CTB_PRINT_ITALIC) continue; if(cluInfo.attr & CTB_PRINT_BOLD) continue; // now - test only russian ASCII letters if(cluInfo.let < 128 || cluInfo.let >= 176 && cluInfo.let < 224 || cluInfo.let > 240 ) continue; addLet=(cluInfo.let < 144 ? cluInfo.let +32 : cluInfo.let < 160 ? cluInfo.let +80 : cluInfo.let < 176 ? cluInfo.let -32 : cluInfo.let - 80 ); name=0; FONGetClusterAsBW(&name,i,porog,&rec); memset(&ro,0,sizeof(RecObject)); memcpy(&ro.recData.recRaster,&rec,sizeof(RecRaster)); ps.nIdPage=-1; ro.recData.lwStatus=0; LEOSetupPage(&ps); LEORecogPrintChar(&ro); // ничего хорошего по LEO ? if( ro.recResults.lnAltCnt <= 0 || ro.recResults.Alt[0].Prob < 150 ) continue; for(j=0;j<ro.recResults.lnAltCnt;j++) { resLet = stdAnsiToAscii(ro.recResults.Alt[j].Code); if( resLet == cluInfo.let || resLet == addLet ) break; } if(j==0) continue; { char *qq; resLet = stdAnsiToAscii(ro.recResults.Alt[0].Code); if( !is_lower(resLet) ) resLet = to_lower(resLet); if( (qq=strchr(hasNearSame,cluInfo.let)) && NearSame[qq-(char*)hasNearSame] == resLet ) continue; } // узналось как что-то иное ? // если совсем не распозналось - бывает ('»' в sten91) if( j >= ro.recResults.lnAltCnt || ro.recResults.Alt[j].Prob < 180 || ro.recResults.Alt[j].Prob < 220 && ro.recResults.Alt[j].Prob + 25 < ro.recResults.Alt[0].Prob ) { FonTestInfo testInfo[MAXCHECKALT]; // проверим resLet = stdAnsiToAscii(ro.recResults.Alt[0].Code); j=FONTestChar(&rec,resLet,testInfo,0); if( j <=0 || testInfo[0].prob <= 215 ) { resLet=(resLet < 144 ? resLet +32 : resLet < 160 ? resLet +80 : resLet < 176 ? resLet -32 : resLet - 80 ); j=FONTestChar(&rec,resLet,testInfo,0); } if( j > 0 && testInfo[0].prob > 215 ) { numInvalid++; FONSetClusterInvalid(i+1); #ifdef _SAVE_INVALID_CLU_ fprintf(fp," invalid %d (%c -> %c(%d))\n",i+1,cluInfo.let, stdAnsiToAscii(ro.recResults.Alt[0].Code), ro.recResults.Alt[0].Prob); #endif } } // end if j } // end clusters #ifdef _SAVE_INVALID_CLU_ fclose(fp); #endif return numInvalid; #else return 0; #endif }
static int fw_parse_opt(struct filter_util *qu, char *handle, int argc, char **argv, struct nlmsghdr *n) { struct tc_police tp; struct tcmsg *t = NLMSG_DATA(n); struct rtattr *tail; __u32 mask = 0; int mask_set = 0; memset(&tp, 0, sizeof(tp)); if (handle) { char *slash; if ((slash = strchr(handle, '/')) != NULL) *slash = '\0'; if (get_u32(&t->tcm_handle, handle, 0)) { fprintf(stderr, "Illegal \"handle\"\n"); return -1; } if (slash) { if (get_u32(&mask, slash+1, 0)) { fprintf(stderr, "Illegal \"handle\" mask\n"); return -1; } mask_set = 1; } } if (argc == 0) return 0; tail = NLMSG_TAIL(n); addattr_l(n, 4096, TCA_OPTIONS, NULL, 0); if (mask_set) addattr32(n, MAX_MSG, TCA_FW_MASK, mask); while (argc > 0) { if (matches(*argv, "classid") == 0 || matches(*argv, "flowid") == 0) { unsigned handle; NEXT_ARG(); if (get_tc_classid(&handle, *argv)) { fprintf(stderr, "Illegal \"classid\"\n"); return -1; } addattr_l(n, 4096, TCA_FW_CLASSID, &handle, 4); } else if (matches(*argv, "police") == 0) { NEXT_ARG(); if (parse_police(&argc, &argv, TCA_FW_POLICE, n)) { fprintf(stderr, "Illegal \"police\"\n"); return -1; } continue; } else if (matches(*argv, "action") == 0) { NEXT_ARG(); if (parse_action(&argc, &argv, TCA_FW_ACT, n)) { fprintf(stderr, "Illegal fw \"action\"\n"); return -1; } continue; } else if (strcmp(*argv, "indev") == 0) { char d[IFNAMSIZ+1]; memset(d, 0, sizeof (d)); argc--; argv++; if (argc < 1) { fprintf(stderr, "Illegal indev\n"); return -1; } strncpy(d, *argv, sizeof (d) - 1); addattr_l(n, MAX_MSG, TCA_FW_INDEV, d, strlen(d) + 1); } else if (strcmp(*argv, "help") == 0) { explain(); return -1; } else { fprintf(stderr, "What is \"%s\"?\n", *argv); explain(); return -1; } argc--; argv++; } tail->rta_len = (void *) NLMSG_TAIL(n) - (void *) tail; return 0; }
/* * Recognized connection string either starts with a valid URI prefix or * contains a "=" in it. * * Must be consistent with parse_connection_string: anything for which this * returns true should at least look like it's parseable by that routine. * * XXX This is a duplicate of the eponymous libpq function. */ bool recognized_connection_string(const char *connstr) { return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL; }
static int virLXCProcessReadLogOutputData(virDomainObjPtr vm, int fd, char *buf, size_t buflen) { int retries = 10; int got = 0; int ret = -1; char *filter_next = buf; buf[0] = '\0'; while (retries) { ssize_t bytes; bool isdead = false; char *eol; if (vm->pid <= 0 || (kill(vm->pid, 0) == -1 && errno == ESRCH)) isdead = true; /* Any failures should be detected before we read the log, so we * always have something useful to report on failure. */ bytes = saferead(fd, buf+got, buflen-got-1); if (bytes < 0) { virReportSystemError(errno, "%s", _("Failure while reading log output")); goto cleanup; } got += bytes; buf[got] = '\0'; /* Filter out debug messages from intermediate libvirt process */ while ((eol = strchr(filter_next, '\n'))) { *eol = '\0'; if (virLXCProcessIgnorableLogLine(filter_next)) { memmove(filter_next, eol + 1, got - (eol - buf)); got -= eol + 1 - filter_next; } else { filter_next = eol + 1; *eol = '\n'; } } if (got == buflen-1) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Out of space while reading log output: %s"), buf); goto cleanup; } if (isdead) { ret = got; goto cleanup; } usleep(100*1000); retries--; } virReportError(VIR_ERR_INTERNAL_ERROR, _("Timed out while reading log output: %s"), buf); cleanup: return ret; }
static void parse_extended_opts(struct ext2_super_block *param, const char *opts) { char *buf, *token, *next, *p, *arg, *badopt = ""; int len; int r_usage = 0; len = strlen(opts); buf = malloc(len+1); if (!buf) { fprintf(stderr, _("Couldn't allocate memory to parse options!\n")); exit(1); } strcpy(buf, opts); for (token = buf; token && *token; token = next) { p = strchr(token, ','); next = 0; if (p) { *p = 0; next = p+1; } arg = strchr(token, '='); if (arg) { *arg = 0; arg++; } if (strcmp(token, "stride") == 0) { if (!arg) { r_usage++; badopt = token; continue; } param->s_raid_stride = strtoul(arg, &p, 0); if (*p || (param->s_raid_stride == 0)) { fprintf(stderr, _("Invalid stride parameter: %s\n"), arg); r_usage++; continue; } } else if (strcmp(token, "stripe-width") == 0 || strcmp(token, "stripe_width") == 0) { if (!arg) { r_usage++; badopt = token; continue; } param->s_raid_stripe_width = strtoul(arg, &p, 0); if (*p || (param->s_raid_stripe_width == 0)) { fprintf(stderr, _("Invalid stripe-width parameter: %s\n"), arg); r_usage++; continue; } } else if (!strcmp(token, "resize")) { unsigned long resize, bpg, rsv_groups; unsigned long group_desc_count, desc_blocks; unsigned int gdpb, blocksize; int rsv_gdb; if (!arg) { r_usage++; badopt = token; continue; } resize = parse_num_blocks(arg, param->s_log_block_size); if (resize == 0) { fprintf(stderr, _("Invalid resize parameter: %s\n"), arg); r_usage++; continue; } if (resize <= param->s_blocks_count) { fprintf(stderr, _("The resize maximum must be greater " "than the filesystem size.\n")); r_usage++; continue; } blocksize = EXT2_BLOCK_SIZE(param); bpg = param->s_blocks_per_group; if (!bpg) bpg = blocksize * 8; gdpb = blocksize / sizeof(struct ext2_group_desc); group_desc_count = ext2fs_div_ceil(param->s_blocks_count, bpg); desc_blocks = (group_desc_count + gdpb - 1) / gdpb; rsv_groups = ext2fs_div_ceil(resize, bpg); rsv_gdb = ext2fs_div_ceil(rsv_groups, gdpb) - desc_blocks; if (rsv_gdb > (int) EXT2_ADDR_PER_BLOCK(param)) rsv_gdb = EXT2_ADDR_PER_BLOCK(param); if (rsv_gdb > 0) { if (param->s_rev_level == EXT2_GOOD_OLD_REV) { fprintf(stderr, _("On-line resizing not supported with revision 0 filesystems\n")); free(buf); exit(1); } param->s_feature_compat |= EXT2_FEATURE_COMPAT_RESIZE_INODE; param->s_reserved_gdt_blocks = rsv_gdb; } } else if (!strcmp(token, "test_fs")) { param->s_flags |= EXT2_FLAGS_TEST_FILESYS; } else { r_usage++; badopt = token; } } if (r_usage) { fprintf(stderr, _("\nBad option(s) specified: %s\n\n" "Extended options are separated by commas, " "and may take an argument which\n" "\tis set off by an equals ('=') sign.\n\n" "Valid extended options are:\n" "\tstride=<RAID per-disk data chunk in blocks>\n" "\tstripe-width=<RAID stride * data disks in blocks>\n" "\tresize=<resize maximum size in blocks>\n\n" "\ttest_fs\n"), badopt); free(buf); exit(1); } if (param->s_raid_stride && (param->s_raid_stripe_width % param->s_raid_stride) != 0) fprintf(stderr, _("\nWarning: RAID stripe-width %u not an even " "multiple of stride %u.\n\n"), param->s_raid_stripe_width, param->s_raid_stride); free(buf); }
static int str_format (lua_State *L) { int arg = 1; size_t sfl; const char *strfrmt = luaL_checklstring(L, arg, &sfl); const char *strfrmt_end = strfrmt+sfl; luaL_Buffer b; luaL_buffinit(L, &b); while (strfrmt < strfrmt_end) { if (*strfrmt != L_ESC) luaL_addchar(&b, *strfrmt++); else if (*++strfrmt == L_ESC) luaL_addchar(&b, *strfrmt++); /* %% */ else { /* format item */ char form[MAX_FORMAT]; /* to store the format (`%...') */ char buff[MAX_ITEM]; /* to store the formatted item */ arg++; strfrmt = scanformat(L, strfrmt, form); switch (*strfrmt++) { case 'c': { sprintf(buff, form, (int)luaL_checknumber(L, arg)); break; } case 'd': case 'i': { addintlen(form); sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg)); break; } case 'o': case 'u': case 'x': case 'X': { addintlen(form); sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg)); break; } case 'e': case 'E': case 'f': case 'g': case 'G': { sprintf(buff, form, (double)luaL_checknumber(L, arg)); break; } case 'q': { addquoted(L, &b, arg); continue; /* skip the 'addsize' at the end */ } case 's': { size_t l; const char *s = luaL_checklstring(L, arg, &l); if (!strchr(form, '.') && l >= 100) { /* no precision and string is too long to be formatted; keep original string */ lua_pushvalue(L, arg); luaL_addvalue(&b); continue; /* skip the `addsize' at the end */ } else { sprintf(buff, form, s); break; } } default: { /* also treat cases `pnLlh' */ return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " LUA_QL("format"), *(strfrmt - 1)); } } luaL_addlstring(&b, buff, strlen(buff)); } } luaL_pushresult(&b); return 1; }
static int __read(RIO *io, RIODesc *fd, ut8 *buf, int count) { char fmt[4096], num[128]; int rv, rescount = -1; int bufi, numi; char *res, *r; if (!fd || !fd->data) { return -1; } if (count > 1024) { count = 1024; } snprintf (fmt, sizeof (fmt), "{\"op\":\"read\",\"address\":%"PFMT64d",\"count\":%d}", io->off, count); rv = r2p_write (R2P (fd), fmt); if (rv < 1) { eprintf ("r2p_write: error\n"); return -1; } res = r2p_read (R2P (fd)); /* TODO: parse json back */ r = strstr (res, "result"); if (r) { rescount = atoi (r + 6 + 2); } r = strstr (res, "data"); if (r) { char *arr = strchr (r, ':'); if (!arr || arr[1]!='[') { goto beach; } arr += 2; for (num[0] = numi = bufi = 0; bufi < count && *arr; arr++) { switch (*arr) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': num[numi++] = *arr; num[numi] = 0; break; case ' ': case ',': case ']': if (num[0]) { buf[bufi++] = atoi (num); num[numi = 0] = 0; } break; case 'n': case 'u': case 'l': break; default: goto beach; break; } } } beach: free (res); return rescount; }
/* * The runtime library's popen() on win32 does not work when being * called from a service when running on windows <= 2000, because * there is no stdin/stdout/stderr. * * Executing a command in a pipe and reading the first line from it * is all we need. */ static char * pipe_read_line(char *cmd, char *line, int maxsize) { #ifndef WIN32 FILE *pgver; /* flush output buffers in case popen does not... */ fflush(stdout); fflush(stderr); errno = 0; if ((pgver = popen(cmd, "r")) == NULL) { perror("popen failure"); return NULL; } errno = 0; if (fgets(line, maxsize, pgver) == NULL) { if (feof(pgver)) fprintf(stderr, "no data was returned by command \"%s\"\n", cmd); else perror("fgets failure"); pclose(pgver); /* no error checking */ return NULL; } if (pclose_check(pgver)) return NULL; return line; #else /* WIN32 */ SECURITY_ATTRIBUTES sattr; HANDLE childstdoutrd, childstdoutwr, childstdoutrddup; PROCESS_INFORMATION pi; STARTUPINFO si; char *retval = NULL; sattr.nLength = sizeof(SECURITY_ATTRIBUTES); sattr.bInheritHandle = TRUE; sattr.lpSecurityDescriptor = NULL; if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0)) return NULL; if (!DuplicateHandle(GetCurrentProcess(), childstdoutrd, GetCurrentProcess(), &childstdoutrddup, 0, FALSE, DUPLICATE_SAME_ACCESS)) { CloseHandle(childstdoutrd); CloseHandle(childstdoutwr); return NULL; } CloseHandle(childstdoutrd); ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdError = childstdoutwr; si.hStdOutput = childstdoutwr; si.hStdInput = INVALID_HANDLE_VALUE; if (CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { /* Successfully started the process */ char *lineptr; ZeroMemory(line, maxsize); /* Try to read at least one line from the pipe */ /* This may require more than one wait/read attempt */ for (lineptr = line; lineptr < line + maxsize - 1;) { DWORD bytesread = 0; /* Let's see if we can read */ if (WaitForSingleObject(childstdoutrddup, 10000) != WAIT_OBJECT_0) break; /* Timeout, but perhaps we got a line already */ if (!ReadFile(childstdoutrddup, lineptr, maxsize - (lineptr - line), &bytesread, NULL)) break; /* Error, but perhaps we got a line already */ lineptr += strlen(lineptr); if (!bytesread) break; /* EOF */ if (strchr(line, '\n')) break; /* One or more lines read */ } if (lineptr != line) { /* OK, we read some data */ int len; /* If we got more than one line, cut off after the first \n */ lineptr = strchr(line, '\n'); if (lineptr) *(lineptr + 1) = '\0'; len = strlen(line); /* * If EOL is \r\n, convert to just \n. Because stdout is a * text-mode stream, the \n output by the child process is * received as \r\n, so we convert it to \n. The server main.c * sets setvbuf(stdout, NULL, _IONBF, 0) which has the effect of * disabling \n to \r\n expansion for stdout. */ if (len >= 2 && line[len - 2] == '\r' && line[len - 1] == '\n') { line[len - 2] = '\n'; line[len - 1] = '\0'; len--; } /* * We emulate fgets() behaviour. So if there is no newline at the * end, we add one... */ if (len == 0 || line[len - 1] != '\n') strcat(line, "\n"); retval = line; } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } CloseHandle(childstdoutwr); CloseHandle(childstdoutrddup); return retval; #endif /* WIN32 */ }
QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } // Start searching from the middle qint64 left = 0; qint64 right = dictFile.size() - 4096; dictFile.seek((left + right) / 2); // 0 = find some matching expression // 1 = go forward for first matching expr // 2 = appending text inside matching entry // 3 = skipping text outside entry int phase = 0; QString exprString("<entry key=\"" + expr); char buf[4096]; QString result; int numResults = 0; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(phase == 2) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); numResults++; if(numResults > maxResults) { break; } phase = 3; continue; } char *keyStart = strstr(buf, "<entry key=\""); if(keyStart == 0) { continue; } keyStart += 12; char *keyEnd = strchr(keyStart, '"'); QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); int cmp = compareExprKey(expr, key); if(cmp == UNCOMPARABLE_CHARS) { continue; // skip uncomparable words } if(phase == 0) { bool changed = true; if(cmp > 0) // expression is bigger then key { left = dictFile.pos(); } else // expression is smaller or matches { changed = (right != dictFile.pos()); // comparing twice same word right = dictFile.pos(); } if(changed && (right - left > 4096)) { dictFile.seek((left + right) / 2); continue; } phase = 1; dictFile.seek(left); continue; } if(phase == 1) { if(cmp > 0) { continue; // first match still not found } else if(cmp < 0) { break; // all matching words passed } phase = 2; } if(phase == 2 || phase == 3) { QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { break; // first non matching entry was hit } result += str.right(entryStart - exprString.length()); phase = 2; } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; }
int closingpunct(int c) { return strchr(".,:;'\")]}>!?", c) != nil; }
void MP3_NetIO(void *cbk, GF_NETIO_Parameter *param) { GF_Err e; const char *szCache; u32 total_size, bytes_done; MP3Reader *read = (MP3Reader *) cbk; e = param->error; /*done*/ if (param->msg_type==GF_NETIO_DATA_TRANSFERED) { if (read->stream) { read->is_remote = 0; e = GF_EOS; } else { return; } } else if (param->msg_type==GF_NETIO_PARSE_HEADER) { if (!strcmp(param->name, "icy-name")) { if (read->icy_name) free(read->icy_name); read->icy_name = strdup(param->value); } if (!strcmp(param->name, "icy-genre")) { if (read->icy_genre) free(read->icy_genre); read->icy_genre = strdup(param->value); } if (!strcmp(param->name, "icy-meta")) { GF_NetworkCommand com; char *meta; if (read->icy_track_name) free(read->icy_track_name); read->icy_track_name = NULL; meta = param->value; while (meta && meta[0]) { char *sep = strchr(meta, ';'); if (sep) sep[0] = 0; if (!strnicmp(meta, "StreamTitle=", 12)) { read->icy_track_name = strdup(meta+12); } if (!sep) break; sep[0] = ';'; meta = sep+1; } com.base.command_type = GF_NET_SERVICE_INFO; gf_term_on_command(read->service, &com, GF_OK); } return; } else { /*handle service message*/ gf_term_download_update_stats(read->dnload); if (param->msg_type!=GF_NETIO_DATA_EXCHANGE) return; } if (e >= GF_OK) { if (read->needs_connection) { gf_dm_sess_get_stats(read->dnload, NULL, NULL, &total_size, NULL, NULL, NULL); if (!total_size) read->is_live = 1; } /*looks like a live stream*/ if (read->is_live) { if (!e) MP3_OnLiveData(read, param->data, param->size); return; } if (read->stream) return; /*open service*/ szCache = gf_dm_sess_get_cache_name(read->dnload); if (!szCache) e = GF_IO_ERR; else { read->stream = fopen((char *) szCache, "rb"); if (!read->stream) e = GF_SERVICE_ERROR; else { /*if full file at once (in cache) parse duration*/ if (e==GF_EOS) read->is_remote = 0; e = GF_OK; /*not enough data*/ if (!MP3_ConfigureFromFile(read)) { gf_dm_sess_get_stats(read->dnload, NULL, NULL, NULL, &bytes_done, NULL, NULL); /*bad data - there's likely some ID3 around...*/ if (bytes_done>10*1024) { e = GF_CORRUPTED_DATA; } else { fclose(read->stream); read->stream = NULL; return; } } } } } /*OK confirm*/ if (read->needs_connection) { read->needs_connection = 0; gf_term_on_connect(read->service, NULL, e); if (!e) mp3_setup_object(read); } }
ps_font_info_type ps_init (string font_name, tfm_global_info_type tfm_info) { string base_encoding, mapping; ps_font_info_type ret; libfile_start ("postscript", "map"); while ((mapping = libfile_line ()) != NULL && !STREQ (font_name, strtok (mapping, " \t"))) ; libfile_close (); if (mapping == NULL) { WARNING2 ("%s: No information for font `%s'; using defaults", "postscript.map", font_name); ret.font_name = xstrdup (font_name); base_encoding = "adobestd"; } else { /* We found it; dissect the rest of the line for what we need. The second word is the full PostScript font name, e.g., `Times-BoldItalic'. The third word is the base filename for the encoding vector. */ ret.font_name = strtok (NULL, " \t"); base_encoding = strtok (NULL, " \t"); } /* Read the encoding file. We don't store this in the structure we return, since we've never needed it. Perhaps we should anyway. */ encoding = read_encoding_file (base_encoding); /* The family name would be `Times' for the font `Times-BoldItalic', but it's `Helvetica' for `Helvetica'. (It should be `Lucida' for `LucidaBright-Italic', but we don't handle that case -- maybe optional arg in mapping file?) */ ret.family_name = strchr (ret.font_name, '-'); if (ret.family_name == NULL) ret.family_name = ret.font_name; /* E.g., `Helvetica'. */ else ret.family_name = substring (ret.font_name, 0, ret.family_name - 1- ret.font_name); /* If the font name contains `Bold', that's the weight. Otherwise, guess `Medium'. (I don't know of any programs that actually care about this. Again, perhaps it should be an optional arg in the mapping file.) */ ret.weight = strstr (ret.font_name, "Bold") ? "Bold" : "Medium"; /* We should be able to compute the italic angle by somehow looking at the characters. bdftops.ps rotates the `I' and takes the angle that minimizes the width, for example. xx */ ret.italic_angle = 0; /* Monospaced fonts have no stretch or shrink in their interword space (or shouldn't), but they do have a nonzero interword space (math fonts sometimes have all their interword space parameters set to zero). */ ret.monospace_p = TFM_FONT_PARAMETER (tfm_info, TFM_STRETCH_PARAMETER) == 0.0 && TFM_FONT_PARAMETER (tfm_info, TFM_SPACE_PARAMETER) != 0.0; /* What might be a good way to compute this one? xx */ ret.underline_position = -100; /* Here we can use the rule thickness from the TFM file, if it's set. Otherwise, just guess. (A better guess would be the dominant stem width in the font.) */ ret.underline_thickness = TFM_FONT_PARAMETER (tfm_info, TFM_DEFAULTRULETHICKNESS_PARAMETER) ? : 50; /* What to do about the UniqueID's? Actually, I'm not sure they should really be necessary. Adobe wants people to register their fonts to get a UniqueID from them, which is semi-reasonable, but a lot of trouble. We just omit them. */ ret.unique_id = 0; /* If there is no version number in the TFM file, then just say it's version 0. */ ret.version = TFM_FONT_PARAMETER (tfm_info, TFM_VERSION_PARAMETER) ? dtoa (TFM_FONT_PARAMETER (tfm_info, TFM_VERSION_PARAMETER)) : "0.0"; return ret; }
/* Look up the specified function or ordinal in the exportlist: * If it is a string: * - look up the name in the Name list. * - look up the ordinal with that index. * - use the ordinal as offset into the functionlist * If it is a ordinal: * - use ordinal-pe_export->Base as offset into the functionlist */ FARPROC PE_FindExportedFunction (WINE_MODREF * wm, LPCSTR funcName, WIN_BOOL snoop) { u_short *ordinals; u_long *function; u_char **name, *ename = NULL; int i, ordinal; PE_MODREF *pem = &(wm->binfmt.pe); IMAGE_EXPORT_DIRECTORY *exports = pem->pe_export; unsigned int load_addr = wm->module; u_long rva_start, rva_end, addr; if (HIWORD (funcName)) TRACE ("FindExportedFunction(%s)\n", funcName); else TRACE ("FindExportedFunction(%d)\n", (int) funcName); if (!exports) { /* Not a fatal problem, some apps do * GetProcAddress(0,"RegisterPenApp") which triggers this * case. */ WARN ("Module %08x(%s)/MODREF %p doesn't have a exports table.\n", wm->module, wm->modname, pem); return NULL; } ordinals = (u_short *) RVA (exports->AddressOfNameOrdinals); function = (u_long *) RVA (exports->AddressOfFunctions); name = (u_char **) RVA (exports->AddressOfNames); rva_start = PE_HEADER (wm->module)-> OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; rva_end = rva_start + PE_HEADER (wm->module)-> OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; //TRACE(".. search in %ld symbols\n",exports->NumberOfNames); if (HIWORD (funcName)) { int min = 0, max = exports->NumberOfNames - 1; while (min <= max) { int res, pos = (min + max) / 2; ename = RVA (name[pos]); if (!(res = strcmp ((char *) ename, funcName))) { ordinal = ordinals[pos]; goto found; } if (res > 0) max = pos - 1; else min = pos + 1; } for (i = 0; i < exports->NumberOfNames; i++) { ename = RVA (name[i]); if (!strcmp ((char *) ename, funcName)) { ERR ("%s.%s required a linear search\n", wm->modname, funcName); ordinal = ordinals[i]; goto found; } } return NULL; } else { ordinal = LOWORD (funcName) - exports->Base; if (snoop && name) { for (i = 0; i < exports->NumberOfNames; i++) if (ordinals[i] == ordinal) { ename = RVA (name[i]); break; } } } found: //TRACE("ordinal = %d (of %d)\n", ordinal, exports->NumberOfFunctions); if (ordinal >= exports->NumberOfFunctions) { TRACE (" ordinal %ld out of range!\n", ordinal + exports->Base); return NULL; } addr = function[ordinal]; if (!addr) { TRACE ("no address for function '%s'\n", funcName); return NULL; } if ((addr < rva_start) || (addr >= rva_end)) { FARPROC proc = RVA (addr); if (snoop) { if (!ename) ename = (u_char *) "@"; //proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc); //TRACE("SNOOP_GetProcAddress n/a\n"); } return proc; } else { WINE_MODREF *wm; char *forward = RVA (addr); char module[256]; char *end = strchr (forward, '.'); TRACE ("getting next module name from '%s'\n", forward); if (!end) return NULL; if (end - forward >= sizeof (module)) { WARN ("need to enlarge buffer from %d to %ld\n", sizeof (module), (long) (end - forward)); return NULL; } memcpy (module, forward, end - forward); module[end - forward] = 0; TRACE ("calling FindModule(%s)\n", module); if (!(wm = MODULE_FindModule (module))) { ERR ("module not found for forward '%s'\n", forward); return NULL; } return MODULE_GetProcAddress (wm->module, end + 1, snoop); } }
/* ----------------------------------------------------------------------- */ int miniopt(miniopt_t *t, char **argv) { int keylen; char *p, *eq, *valstr, *endptr = NULL; int err = 0; t->consumed = 0; t->positional = FALSE; memset(t->key, 0, MINIOPT_MAXKEY); t->opt = '\0'; t->valstr = NULL; t->good_int = FALSE; valstr = NULL; if (*argv == NULL) { err = -1; goto exit; } p = *argv++; t->consumed++; if (!t->opt_end && !strcmp(p, "--")) { t->opt_end = TRUE; if (*argv == NULL) { err = -1; goto exit; } p = *argv++; t->consumed++; } if (t->opt_end) { t->positional = TRUE; valstr = p; } else if (!strncmp(p, "--", 2)) { eq = strchr(p, '='); if (eq == NULL && !t->longflags) { fprintf(stderr, "%s: missing \" = \" in long param \"%s\"\n", t->name, p); err = 1; goto exit; } keylen = eq ? (eq - (p + 2)) : (int)strlen(p) - 2; if (keylen > 63) keylen = 63; memcpy(t->key, p + 2, keylen); if (eq) { valstr = eq + 1; if (*valstr == '\0') { fprintf(stderr, "%s: missing value after \" = \" in long param \"%s\"\n", t->name, p); err = 1; goto exit; } } } else if (!strncmp(p, "-", 1)) { t->opt = p[1]; if (strlen(p) > 2) { fprintf(stderr, "%s: only single char options, error on param \"%s\"\n", t->name, p); err = 1; goto exit; } if (strchr(t->flags, t->opt)) { /* this is a flag option, no value expected */ valstr = NULL; } else { if (*argv == NULL) { fprintf(stderr, "%s: missing value parameter after \"%s\"\n", t->name, p); err = 1; goto exit; } valstr = *argv; argv++; t->consumed++; } } else { t->positional = TRUE; valstr = p; } /* parse valstr as int just in case */ if (valstr) { t->uval = (uint)strtoul(valstr, &endptr, 0); t->val = (int)t->uval; t->good_int = (*endptr == '\0'); } t->valstr = valstr; exit: if (err == 1) t->opt = '?'; return err; }
static int compare_opcodes (const void * a, const void * b) { sparc_opcode *op0 = * (sparc_opcode **) a; sparc_opcode *op1 = * (sparc_opcode **) b; unsigned long int match0 = op0->match, match1 = op1->match; unsigned long int lose0 = op0->lose, lose1 = op1->lose; register unsigned int i; /* If one (and only one) insn isn't supported by the current architecture, prefer the one that is. If neither are supported, but they're both for the same architecture, continue processing. Otherwise (both unsupported and for different architectures), prefer lower numbered arch's (fudged by comparing the bitmasks). */ if (op0->architecture & current_arch_mask) { if (! (op1->architecture & current_arch_mask)) return -1; } else { if (op1->architecture & current_arch_mask) return 1; else if (op0->architecture != op1->architecture) return op0->architecture - op1->architecture; } /* If a bit is set in both match and lose, there is something wrong with the opcode table. */ if (match0 & lose0) { fprintf (stderr, /* xgettext:c-format */ _("Internal error: bad sparc-opcode.h: \"%s\", %#.8lx, %#.8lx\n"), op0->name, match0, lose0); op0->lose &= ~op0->match; lose0 = op0->lose; } if (match1 & lose1) { fprintf (stderr, /* xgettext:c-format */ _("Internal error: bad sparc-opcode.h: \"%s\", %#.8lx, %#.8lx\n"), op1->name, match1, lose1); op1->lose &= ~op1->match; lose1 = op1->lose; } /* Because the bits that are variable in one opcode are constant in another, it is important to order the opcodes in the right order. */ for (i = 0; i < 32; ++i) { unsigned long int x = 1 << i; int x0 = (match0 & x) != 0; int x1 = (match1 & x) != 0; if (x0 != x1) return x1 - x0; } for (i = 0; i < 32; ++i) { unsigned long int x = 1 << i; int x0 = (lose0 & x) != 0; int x1 = (lose1 & x) != 0; if (x0 != x1) return x1 - x0; } /* They are functionally equal. So as long as the opcode table is valid, we can put whichever one first we want, on aesthetic grounds. */ /* Our first aesthetic ground is that aliases defer to real insns. */ { int alias_diff = (op0->flags & F_ALIAS) - (op1->flags & F_ALIAS); if (alias_diff != 0) /* Put the one that isn't an alias first. */ return alias_diff; } /* Except for aliases, two "identical" instructions had better have the same opcode. This is a sanity check on the table. */ i = strcmp (op0->name, op1->name); if (i) { if (op0->flags & F_ALIAS) /* If they're both aliases, be arbitrary. */ return i; else fprintf (stderr, /* xgettext:c-format */ _("Internal error: bad sparc-opcode.h: \"%s\" == \"%s\"\n"), op0->name, op1->name); } /* Fewer arguments are preferred. */ { int length_diff = strlen (op0->args) - strlen (op1->args); if (length_diff != 0) /* Put the one with fewer arguments first. */ return length_diff; } /* Put 1+i before i+1. */ { char *p0 = (char *) strchr (op0->args, '+'); char *p1 = (char *) strchr (op1->args, '+'); if (p0 && p1) { /* There is a plus in both operands. Note that a plus sign cannot be the first character in args, so the following [-1]'s are valid. */ if (p0[-1] == 'i' && p1[1] == 'i') /* op0 is i+1 and op1 is 1+i, so op1 goes first. */ return 1; if (p0[1] == 'i' && p1[-1] == 'i') /* op0 is 1+i and op1 is i+1, so op0 goes first. */ return -1; } } /* Put 1,i before i,1. */ { int i0 = strncmp (op0->args, "i,1", 3) == 0; int i1 = strncmp (op1->args, "i,1", 3) == 0; if (i0 ^ i1) return i0 - i1; } /* They are, as far as we can tell, identical. Since qsort may have rearranged the table partially, there is no way to tell which one was first in the opcode table as written, so just say there are equal. */ /* ??? This is no longer true now that we sort a vector of pointers, not the table itself. */ return 0; }
static enum request run_prompt_command(struct view *view, char *cmd) { enum request request; if (!cmd) return REQ_NONE; if (string_isnumber(cmd)) { int lineno = view->pos.lineno + 1; if (parse_int(&lineno, cmd, 1, view->lines + 1) == SUCCESS) { select_view_line(view, lineno - 1); report_clear(); } else { report("Unable to parse '%s' as a line number", cmd); } } else if (iscommit(cmd)) { string_ncopy(view->env->search, cmd, strlen(cmd)); request = view_request(view, REQ_JUMP_COMMIT); if (request == REQ_JUMP_COMMIT) { report("Jumping to commits is not supported by the '%s' view", view->name); } } else if (strlen(cmd) == 1) { struct key_input input = { { cmd[0] } }; return get_keybinding(&view->ops->keymap, &input); } else if (cmd[0] == '/' || cmd[0] == '?') { const char *search = cmd + 1; if (!strcmp(search, view->env->search)) return cmd[0] == '/' ? REQ_FIND_NEXT : REQ_FIND_PREV; string_ncopy(view->env->search, search, strlen(search)); return cmd[0] == '/' ? REQ_SEARCH : REQ_SEARCH_BACK; } else if (cmd[0] == '!') { struct view *next = VIEW(REQ_VIEW_PAGER); const char *argv[SIZEOF_ARG]; int argc = 0; cmd++; /* When running random commands, initially show the * command in the title. However, it maybe later be * overwritten if a commit line is selected. */ string_ncopy(next->ref, cmd, strlen(cmd)); if (!argv_from_string(argv, &argc, cmd)) { report("Too many arguments"); } else if (!argv_format(view->env, &next->argv, argv, FALSE, TRUE)) { report("Argument formatting failed"); } else { next->dir = NULL; open_view(view, REQ_VIEW_PAGER, OPEN_PREPARED); } } else { request = get_request(cmd); if (request != REQ_UNKNOWN) return request; char *args = strchr(cmd, ' '); if (args) { *args++ = 0; if (set_option(cmd, args) == SUCCESS) { request = !view->unrefreshable ? REQ_REFRESH : REQ_SCREEN_REDRAW; if (!strcmp(cmd, "color")) init_colors(); resize_display(); redraw_display(TRUE); } } return request; } return REQ_NONE; }
int print_insn_sparc (bfd_vma memaddr, disassemble_info *info) { FILE *stream = info->stream; bfd_byte buffer[4]; unsigned long insn; sparc_opcode_hash *op; /* Nonzero of opcode table has been initialized. */ static int opcodes_initialized = 0; /* bfd mach number of last call. */ static unsigned long current_mach = 0; bfd_vma (*getword) (const void *); if (!opcodes_initialized || info->mach != current_mach) { int i; current_arch_mask = compute_arch_mask (info->mach); if (!opcodes_initialized) sorted_opcodes = xmalloc (sparc_num_opcodes * sizeof (sparc_opcode *)); /* Reset the sorted table so we can resort it. */ for (i = 0; i < sparc_num_opcodes; ++i) sorted_opcodes[i] = &sparc_opcodes[i]; qsort ((char *) sorted_opcodes, sparc_num_opcodes, sizeof (sorted_opcodes[0]), compare_opcodes); build_hash_table (sorted_opcodes, opcode_hash_table, sparc_num_opcodes); current_mach = info->mach; opcodes_initialized = 1; } { int status = (*info->read_memory_func) (memaddr, buffer, sizeof (buffer), info); if (status != 0) { (*info->memory_error_func) (status, memaddr, info); return -1; } } /* On SPARClite variants such as DANlite (sparc86x), instructions are always big-endian even when the machine is in little-endian mode. */ if (info->endian == BFD_ENDIAN_BIG || info->mach == bfd_mach_sparc_sparclite) getword = bfd_getb32; else getword = bfd_getl32; insn = getword (buffer); info->insn_info_valid = 1; /* We do return this info. */ info->insn_type = dis_nonbranch; /* Assume non branch insn. */ info->branch_delay_insns = 0; /* Assume no delay. */ info->target = 0; /* Assume no target known. */ for (op = opcode_hash_table[HASH_INSN (insn)]; op; op = op->next) { const sparc_opcode *opcode = op->opcode; /* If the insn isn't supported by the current architecture, skip it. */ if (! (opcode->architecture & current_arch_mask)) continue; if ((opcode->match & insn) == opcode->match && (opcode->lose & insn) == 0) { /* Nonzero means that we have found an instruction which has the effect of adding or or'ing the imm13 field to rs1. */ int imm_added_to_rs1 = 0; int imm_ored_to_rs1 = 0; /* Nonzero means that we have found a plus sign in the args field of the opcode table. */ int found_plus = 0; /* Nonzero means we have an annulled branch. */ int is_annulled = 0; /* Do we have an `add' or `or' instruction combining an immediate with rs1? */ if (opcode->match == 0x80102000) /* or */ imm_ored_to_rs1 = 1; if (opcode->match == 0x80002000) /* add */ imm_added_to_rs1 = 1; if (X_RS1 (insn) != X_RD (insn) && strchr (opcode->args, 'r') != 0) /* Can't do simple format if source and dest are different. */ continue; if (X_RS2 (insn) != X_RD (insn) && strchr (opcode->args, 'O') != 0) /* Can't do simple format if source and dest are different. */ continue; (*info->fprintf_func) (stream, opcode->name); { const char *s; if (opcode->args[0] != ',') (*info->fprintf_func) (stream, " "); for (s = opcode->args; *s != '\0'; ++s) { while (*s == ',') { (*info->fprintf_func) (stream, ","); ++s; switch (*s) { case 'a': (*info->fprintf_func) (stream, "a"); is_annulled = 1; ++s; continue; case 'N': (*info->fprintf_func) (stream, "pn"); ++s; continue; case 'T': (*info->fprintf_func) (stream, "pt"); ++s; continue; default: break; } } (*info->fprintf_func) (stream, " "); switch (*s) { case '+': found_plus = 1; /* Fall through. */ default: (*info->fprintf_func) (stream, "%c", *s); break; case '#': (*info->fprintf_func) (stream, "0"); break; #define reg(n) (*info->fprintf_func) (stream, "%%%s", reg_names[n]) case '1': case 'r': reg (X_RS1 (insn)); break; case '2': case 'O': reg (X_RS2 (insn)); break; case 'd': reg (X_RD (insn)); break; #undef reg #define freg(n) (*info->fprintf_func) (stream, "%%%s", freg_names[n]) #define fregx(n) (*info->fprintf_func) (stream, "%%%s", freg_names[((n) & ~1) | (((n) & 1) << 5)]) case 'e': freg (X_RS1 (insn)); break; case 'v': /* Double/even. */ case 'V': /* Quad/multiple of 4. */ fregx (X_RS1 (insn)); break; case 'f': freg (X_RS2 (insn)); break; case 'B': /* Double/even. */ case 'R': /* Quad/multiple of 4. */ fregx (X_RS2 (insn)); break; case 'g': freg (X_RD (insn)); break; case 'H': /* Double/even. */ case 'J': /* Quad/multiple of 4. */ fregx (X_RD (insn)); break; #undef freg #undef fregx #define creg(n) (*info->fprintf_func) (stream, "%%c%u", (unsigned int) (n)) case 'b': creg (X_RS1 (insn)); break; case 'c': creg (X_RS2 (insn)); break; case 'D': creg (X_RD (insn)); break; #undef creg case 'h': (*info->fprintf_func) (stream, "%%hi(%#x)", ((unsigned) 0xFFFFFFFF & ((int) X_IMM22 (insn) << 10))); break; case 'i': /* 13 bit immediate. */ case 'I': /* 11 bit immediate. */ case 'j': /* 10 bit immediate. */ { int imm; if (*s == 'i') imm = X_SIMM (insn, 13); else if (*s == 'I') imm = X_SIMM (insn, 11); else imm = X_SIMM (insn, 10); /* Check to see whether we have a 1+i, and take note of that fact. Note: because of the way we sort the table, we will be matching 1+i rather than i+1, so it is OK to assume that i is after +, not before it. */ if (found_plus) imm_added_to_rs1 = 1; if (imm <= 9) (*info->fprintf_func) (stream, "%d", imm); else (*info->fprintf_func) (stream, "%#x", imm); } break; case 'X': /* 5 bit unsigned immediate. */ case 'Y': /* 6 bit unsigned immediate. */ { int imm = X_IMM (insn, *s == 'X' ? 5 : 6); if (imm <= 9) (info->fprintf_func) (stream, "%d", imm); else (info->fprintf_func) (stream, "%#x", (unsigned) imm); } break; case '3': (info->fprintf_func) (stream, "%ld", X_IMM (insn, 3)); break; case 'K': { int mask = X_MEMBAR (insn); int bit = 0x40, printed_one = 0; const char *name; if (mask == 0) (info->fprintf_func) (stream, "0"); else while (bit) { if (mask & bit) { if (printed_one) (info->fprintf_func) (stream, "|"); name = sparc_decode_membar (bit); (info->fprintf_func) (stream, "%s", name); printed_one = 1; } bit >>= 1; } break; } case 'k': info->target = memaddr + SEX (X_DISP16 (insn), 16) * 4; (*info->print_address_func) (info->target, info); break; case 'G': info->target = memaddr + SEX (X_DISP19 (insn), 19) * 4; (*info->print_address_func) (info->target, info); break; case '6': case '7': case '8': case '9': (*info->fprintf_func) (stream, "%%fcc%c", *s - '6' + '0'); break; case 'z': (*info->fprintf_func) (stream, "%%icc"); break; case 'Z': (*info->fprintf_func) (stream, "%%xcc"); break; case 'E': (*info->fprintf_func) (stream, "%%ccr"); break; case 's': (*info->fprintf_func) (stream, "%%fprs"); break; case 'o': (*info->fprintf_func) (stream, "%%asi"); break; case 'W': (*info->fprintf_func) (stream, "%%tick"); break; case 'P': (*info->fprintf_func) (stream, "%%pc"); break; case '?': if (X_RS1 (insn) == 31) (*info->fprintf_func) (stream, "%%ver"); else if ((unsigned) X_RS1 (insn) < 17) (*info->fprintf_func) (stream, "%%%s", v9_priv_reg_names[X_RS1 (insn)]); else (*info->fprintf_func) (stream, "%%reserved"); break; case '!': if ((unsigned) X_RD (insn) < 17) (*info->fprintf_func) (stream, "%%%s", v9_priv_reg_names[X_RD (insn)]); else (*info->fprintf_func) (stream, "%%reserved"); break; case '$': if ((unsigned) X_RS1 (insn) < 32) (*info->fprintf_func) (stream, "%%%s", v9_hpriv_reg_names[X_RS1 (insn)]); else (*info->fprintf_func) (stream, "%%reserved"); break; case '%': if ((unsigned) X_RD (insn) < 32) (*info->fprintf_func) (stream, "%%%s", v9_hpriv_reg_names[X_RD (insn)]); else (*info->fprintf_func) (stream, "%%reserved"); break; case '/': if (X_RS1 (insn) < 16 || X_RS1 (insn) > 25) (*info->fprintf_func) (stream, "%%reserved"); else (*info->fprintf_func) (stream, "%%%s", v9a_asr_reg_names[X_RS1 (insn)-16]); break; case '_': if (X_RD (insn) < 16 || X_RD (insn) > 25) (*info->fprintf_func) (stream, "%%reserved"); else (*info->fprintf_func) (stream, "%%%s", v9a_asr_reg_names[X_RD (insn)-16]); break; case '*': { const char *name = sparc_decode_prefetch (X_RD (insn)); if (name) (*info->fprintf_func) (stream, "%s", name); else (*info->fprintf_func) (stream, "%ld", X_RD (insn)); break; } case 'M': (*info->fprintf_func) (stream, "%%asr%ld", X_RS1 (insn)); break; case 'm': (*info->fprintf_func) (stream, "%%asr%ld", X_RD (insn)); break; case 'L': info->target = memaddr + SEX (X_DISP30 (insn), 30) * 4; (*info->print_address_func) (info->target, info); break; case 'n': (*info->fprintf_func) (stream, "%#x", SEX (X_DISP22 (insn), 22)); break; case 'l': info->target = memaddr + SEX (X_DISP22 (insn), 22) * 4; (*info->print_address_func) (info->target, info); break; case 'A': { const char *name = sparc_decode_asi (X_ASI (insn)); if (name) (*info->fprintf_func) (stream, "%s", name); else (*info->fprintf_func) (stream, "(%ld)", X_ASI (insn)); break; } case 'C': (*info->fprintf_func) (stream, "%%csr"); break; case 'F': (*info->fprintf_func) (stream, "%%fsr"); break; case 'p': (*info->fprintf_func) (stream, "%%psr"); break; case 'q': (*info->fprintf_func) (stream, "%%fq"); break; case 'Q': (*info->fprintf_func) (stream, "%%cq"); break; case 't': (*info->fprintf_func) (stream, "%%tbr"); break; case 'w': (*info->fprintf_func) (stream, "%%wim"); break; case 'x': (*info->fprintf_func) (stream, "%ld", ((X_LDST_I (insn) << 8) + X_ASI (insn))); break; case 'y': (*info->fprintf_func) (stream, "%%y"); break; case 'u': case 'U': { int val = *s == 'U' ? X_RS1 (insn) : X_RD (insn); const char *name = sparc_decode_sparclet_cpreg (val); if (name) (*info->fprintf_func) (stream, "%s", name); else (*info->fprintf_func) (stream, "%%cpreg(%d)", val); break; } } } } /* If we are adding or or'ing something to rs1, then check to see whether the previous instruction was a sethi to the same register as in the sethi. If so, attempt to print the result of the add or or (in this context add and or do the same thing) and its symbolic value. */ if (imm_ored_to_rs1 || imm_added_to_rs1) { unsigned long prev_insn; int errcode; if (memaddr >= 4) errcode = (*info->read_memory_func) (memaddr - 4, buffer, sizeof (buffer), info); else errcode = 1; prev_insn = getword (buffer); if (errcode == 0) { /* If it is a delayed branch, we need to look at the instruction before the delayed branch. This handles sequences such as: sethi %o1, %hi(_foo), %o1 call _printf or %o1, %lo(_foo), %o1 */ if (is_delayed_branch (prev_insn)) { if (memaddr >= 8) errcode = (*info->read_memory_func) (memaddr - 8, buffer, sizeof (buffer), info); else errcode = 1; prev_insn = getword (buffer); } } /* If there was a problem reading memory, then assume the previous instruction was not sethi. */ if (errcode == 0) { /* Is it sethi to the same register? */ if ((prev_insn & 0xc1c00000) == 0x01000000 && X_RD (prev_insn) == X_RS1 (insn)) { (*info->fprintf_func) (stream, "\t! "); info->target = ((unsigned) 0xFFFFFFFF & ((int) X_IMM22 (prev_insn) << 10)); if (imm_added_to_rs1) info->target += X_SIMM (insn, 13); else info->target |= X_SIMM (insn, 13); (*info->print_address_func) (info->target, info); info->insn_type = dis_dref; info->data_size = 4; /* FIXME!!! */ } } } if (opcode->flags & (F_UNBR|F_CONDBR|F_JSR)) { /* FIXME -- check is_annulled flag. */ if (opcode->flags & F_UNBR) info->insn_type = dis_branch; if (opcode->flags & F_CONDBR) info->insn_type = dis_condbranch; if (opcode->flags & F_JSR) info->insn_type = dis_jsr; if (opcode->flags & F_DELAYED) info->branch_delay_insns = 1; } return sizeof (buffer); } }
iconv_t QIconvCodec::createIconv_t(const char *to, const char *from) { Q_ASSERT((to == 0 && from != 0) || (to != 0 && from == 0)); iconv_t cd = (iconv_t) -1; #if defined(__GLIBC__) || defined(GNU_LIBICONV) // both GLIBC and libgnuiconv will use the locale's encoding if from or to is an empty string static const char empty_codeset[] = ""; const char *codeset = empty_codeset; cd = iconv_open(to ? to : codeset, from ? from : codeset); #else char *codeset = 0; #endif #if defined(_XOPEN_UNIX) && !defined(Q_OS_QNX6) && !defined(Q_OS_OSF) if (cd == (iconv_t) -1) { codeset = nl_langinfo(CODESET); if (codeset) cd = iconv_open(to ? to : codeset, from ? from : codeset); } #endif if (cd == (iconv_t) -1) { // Very poorly defined and followed standards causes lots of // code to try to get all the cases... This logic is // duplicated in QTextCodec, so if you change it here, change // it there too. // Try to determine locale codeset from locale name assigned to // LC_CTYPE category. // First part is getting that locale name. First try setlocale() which // definitely knows it, but since we cannot fully trust it, get ready // to fall back to environment variables. char * ctype = qstrdup(setlocale(LC_CTYPE, 0)); // Get the first nonempty value from $LC_ALL, $LC_CTYPE, and $LANG // environment variables. char * lang = qstrdup(qgetenv("LC_ALL").constData()); if (!lang || lang[0] == 0 || strcmp(lang, "C") == 0) { if (lang) delete [] lang; lang = qstrdup(qgetenv("LC_CTYPE").constData()); } if (!lang || lang[0] == 0 || strcmp(lang, "C") == 0) { if (lang) delete [] lang; lang = qstrdup(qgetenv("LANG").constData()); } // Now try these in order: // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15) // 2. CODESET from lang if it contains a .CODESET part // 3. ctype (maybe the locale is named "ISO-8859-1" or something) // 4. locale (ditto) // 5. check for "@euro" // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15) codeset = ctype ? strchr(ctype, '.') : 0; if (codeset && *codeset == '.') { ++codeset; cd = iconv_open(to ? to : codeset, from ? from : codeset); } // 2. CODESET from lang if it contains a .CODESET part codeset = lang ? strchr(lang, '.') : 0; if (cd == (iconv_t) -1 && codeset && *codeset == '.') { ++codeset; cd = iconv_open(to ? to : codeset, from ? from : codeset); } // 3. ctype (maybe the locale is named "ISO-8859-1" or something) if (cd == (iconv_t) -1 && ctype && *ctype != 0 && strcmp (ctype, "C") != 0) cd = iconv_open(to ? to : ctype, from ? from : ctype); // 4. locale (ditto) if (cd == (iconv_t) -1 && lang && *lang != 0) cd = iconv_open(to ? to : lang, from ? from : lang); // 5. "@euro" if ((cd == (iconv_t) -1 && ctype && strstr(ctype, "@euro")) || (lang && strstr(lang, "@euro"))) cd = iconv_open(to ? to : "ISO8859-15", from ? from : "ISO8859-15"); delete [] ctype; delete [] lang; } return cd; }
/// Parse command line. Clobbers localbuf. static bool read_cmdline(int argc, char *argv[]) { assert(argv[argc-1]); assert(!argv[argc]); for (int i=1; i<argc; ++i) { assert(argv[i]); const char *nextarg = NULL; if (argv[i][0] != '-' || !argv[i][1]) { fprintf(stderr, "Illegal argument: %s\n", argv[i]); return false; } const char o = argv[i][1]; const char *optname; if (o == '-') { // Long option name (starting with double dash) optname = argv[i]+2; if (!optname[0] || !isalpha(optname[0])) { fprintf(stderr, "Illegal argument: %s\n", argv[i]); return false; } const char *const eqsign = strchr(optname, '='); if (eqsign) { // Option in '--foo=bar' style const size_t optnamelen = eqsign - optname; if (optnamelen >= sizeof(localbuf)) { fprintf(stderr, "Option name too long\n"); return false; } strncpy(localbuf, optname, optnamelen); localbuf[optnamelen] = '\0'; optname = localbuf; nextarg = eqsign + 1; } } else { // Short option name (starting with single dash) int j; for (j=0; j<sizeof(options)/sizeof(*options) && options[j].shortopt != o; ++j); if (j == sizeof(options)/sizeof(*options)) { fprintf(stderr, "Illegal option: -%c\n", o); return false; } optname = options[j].name; if (argv[i][2]) nextarg = argv[i] + 2; } if (!nextarg && argv[i+1] && (argv[i+1][0]!='-'||isdigit(argv[i+1][1]))) { ++i; nextarg = argv[i]; } if (!handle_configitem(optname, nextarg)) return false; } return true; }
/* EAM Nov 2012: * Unbelievably, the count parameter has been silently ignored or * improperly applied ever since this routine was introduced back * in version 3.7. Now fixed to prevent buffer overflow. */ void gprintf( char *outstring, size_t count, char *format, double log10_base, double x) { char tempdest[MAX_LINE_LEN + 1]; char temp[MAX_LINE_LEN + 1]; char *t; TBOOLEAN seen_mantissa = FALSE; /* remember if mantissa was already output */ double stored_power_base = 0; /* base for the last mantissa output*/ int stored_power = 0; /* power matching the mantissa output earlier */ TBOOLEAN got_hash = FALSE; char *dest = &tempdest[0]; char *limit = &tempdest[MAX_LINE_LEN]; static double log10_of_1024; /* to avoid excess precision comparison in check of connection %b -- %B */ log10_of_1024 = log10(1024); #define remaining_space (size_t)(limit-dest) *dest = '\0'; set_numeric_locale(); /* Oct 2013 - default format is now expected to be "%h" */ if (((term->flags & TERM_IS_LATEX)) && !strcmp(format, DEF_FORMAT)) format = DEF_FORMAT_LATEX; for (;;) { /*{{{ copy to dest until % */ while (*format != '%') if (!(*dest++ = *format++) || (remaining_space == 0)) { goto done; } /*}}} */ /*{{{ check for %% */ if (format[1] == '%') { *dest++ = '%'; format += 2; continue; } /*}}} */ /*{{{ copy format part to temp, excluding conversion character */ t = temp; *t++ = '%'; if (format[1] == '#') { *t++ = '#'; format++; got_hash = TRUE; } /* dont put isdigit first since side effect in macro is bad */ while (*++format == '.' || isdigit((unsigned char) *format) || *format == '-' || *format == '+' || *format == ' ' || *format == '\'') *t++ = *format; /*}}} */ /*{{{ convert conversion character */ switch (*format) { /*{{{ x and o */ case 'x': case 'X': case 'o': case 'O': if (fabs(x) >= (double)INT_MAX) { t[0] = 'l'; t[1] = 'l'; t[2] = *format; t[3] = '\0'; snprintf(dest, remaining_space, temp, (long long) x); } else { t[0] = *format; t[1] = '\0'; snprintf(dest, remaining_space, temp, (int) x); } break; /*}}} */ /*{{{ e, f and g */ case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': t[0] = *format; t[1] = 0; snprintf(dest, remaining_space, temp, x); break; case 'h': case 'H': /* g/G with enhanced formating (if applicable) */ t[0] = (*format == 'h') ? 'g' : 'G'; t[1] = 0; if ((term->flags & (TERM_ENHANCED_TEXT | TERM_IS_LATEX)) == 0) { /* Not enhanced, not latex, just print it */ snprintf(dest, remaining_space, temp, x); } else if (table_mode) { /* Tabular output should contain no markup */ snprintf(dest, remaining_space, temp, x); } else { /* in enhanced mode -- convert E/e to x10^{foo} or *10^{foo} */ #define LOCAL_BUFFER_SIZE 256 char tmp[LOCAL_BUFFER_SIZE]; char tmp2[LOCAL_BUFFER_SIZE]; int i,j; TBOOLEAN bracket_flag = FALSE; snprintf(tmp, 240, temp, x); /* magic number alert: why 240? */ for (i=j=0; tmp[i] && (i < LOCAL_BUFFER_SIZE); i++) { if (tmp[i]=='E' || tmp[i]=='e') { if ((term-> flags & TERM_IS_LATEX)) { if (*format == 'h') { strcpy(&tmp2[j], "\\times"); j+= 6; } else { strcpy(&tmp2[j], "\\cdot"); j+= 5; } } else switch (encoding) { case S_ENC_UTF8: strcpy(&tmp2[j], "\xc3\x97"); /* UTF character '×' */ j+= 2; break; case S_ENC_CP1252: tmp2[j++] = (*format=='h') ? 0xd7 : 0xb7; break; case S_ENC_ISO8859_1: case S_ENC_ISO8859_2: case S_ENC_ISO8859_9: case S_ENC_ISO8859_15: tmp2[j++] = (*format=='h') ? 0xd7 : '*'; break; default: tmp2[j++] = (*format=='h') ? 'x' : '*'; break; } strcpy(&tmp2[j], "10^{"); j += 4; bracket_flag = TRUE; /* Skip + and leading 0 in exponent */ i++; /* skip E */ if (tmp[i] == '+') i++; else if (tmp[i] == '-') /* copy sign */ tmp2[j++] = tmp[i++]; while (tmp[i] == '0') i++; i--; /* undo following loop increment */ } else { tmp2[j++] = tmp[i]; } } if (bracket_flag) tmp2[j++] = '}'; tmp2[j] = '\0'; strncpy(dest, tmp2, remaining_space); #undef LOCAL_BUFFER_SIZE } break; /*}}} */ /*{{{ l --- mantissa to current log base */ case 'l': { double mantissa; t[0] = 'f'; t[1] = 0; stored_power_base = log10_base; mant_exp(stored_power_base, x, FALSE, &mantissa, &stored_power, temp); seen_mantissa = TRUE; snprintf(dest, remaining_space, temp, mantissa); break; } /*}}} */ /*{{{ t --- base-10 mantissa */ case 't': { double mantissa; t[0] = 'f'; t[1] = 0; stored_power_base = 1.0; mant_exp(stored_power_base, x, FALSE, &mantissa, &stored_power, temp); seen_mantissa = TRUE; snprintf(dest, remaining_space, temp, mantissa); break; } /*}}} */ /*{{{ s --- base-1000 / 'scientific' mantissa */ case 's': { double mantissa; t[0] = 'f'; t[1] = 0; stored_power_base = 1.0; mant_exp(stored_power_base, x, TRUE, &mantissa, &stored_power, temp); seen_mantissa = TRUE; snprintf(dest, remaining_space, temp, mantissa); break; } /*}}} */ /*{{{ b --- base-1024 mantissa */ case 'b': { double mantissa; t[0] = 'f'; t[1] = 0; stored_power_base = log10_of_1024; mant_exp(stored_power_base, x, FALSE, &mantissa, &stored_power, temp); seen_mantissa = TRUE; snprintf(dest, remaining_space, temp, mantissa); break; } /*}}} */ /*{{{ L --- power to current log base */ case 'L': { int power; t[0] = 'd'; t[1] = 0; if (seen_mantissa) { if (stored_power_base == log10_base) { power = stored_power; } else { int_error(NO_CARET, "Format character mismatch: %%L is only valid with %%l"); } } else { stored_power_base = log10_base; mant_exp(log10_base, x, FALSE, NULL, &power, "%.0f"); } snprintf(dest, remaining_space, temp, power); break; } /*}}} */ /*{{{ T --- power of ten */ case 'T': { int power; t[0] = 'd'; t[1] = 0; if (seen_mantissa) { if (stored_power_base == 1.0) { power = stored_power; } else { int_error(NO_CARET, "Format character mismatch: %%T is only valid with %%t"); } } else { mant_exp(1.0, x, FALSE, NULL, &power, "%.0f"); } snprintf(dest, remaining_space, temp, power); break; } /*}}} */ /*{{{ S --- power of 1000 / 'scientific' */ case 'S': { int power; t[0] = 'd'; t[1] = 0; if (seen_mantissa) { if (stored_power_base == 1.0) { power = stored_power; } else { int_error(NO_CARET, "Format character mismatch: %%S is only valid with %%s"); } } else { mant_exp(1.0, x, TRUE, NULL, &power, "%.0f"); } snprintf(dest, remaining_space, temp, power); break; } /*}}} */ /*{{{ c --- ISO decimal unit prefix letters */ case 'c': { int power; t[0] = 'c'; t[1] = 0; if (seen_mantissa) { if (stored_power_base == 1.0) { power = stored_power; } else { int_error(NO_CARET, "Format character mismatch: %%c is only valid with %%s"); } } else { mant_exp(1.0, x, TRUE, NULL, &power, "%.0f"); } if (power >= -24 && power <= 24) { /* name power name power ------------------------- yocto -24 yotta 24 zepto -21 zetta 21 atto -18 Exa 18 femto -15 Peta 15 pico -12 Tera 12 nano -9 Giga 9 micro -6 Mega 6 milli -3 kilo 3 */ /* -18 -> 0, 0 -> 6, +18 -> 12, ... */ /* HBB 20010121: avoid division of -ve ints! */ power = (power + 24) / 3; snprintf(dest, remaining_space, temp, "yzafpnum kMGTPEZY"[power]); } else { /* please extend the range ! */ /* fall back to simple exponential */ snprintf(dest, remaining_space, "e%+02d", power); } break; } /*}}} */ /*{{{ B --- IEC 60027-2 A.2 / ISO/IEC 80000 binary unit prefix letters */ case 'B': { int power; t[0] = 'c'; t[1] = 'i'; t[2] = '\0'; if (seen_mantissa) { if (stored_power_base == log10_of_1024) { power = stored_power; } else { int_error(NO_CARET, "Format character mismatch: %%B is only valid with %%b"); } } else { mant_exp(log10_of_1024, x, FALSE, NULL, &power, "%.0f"); } if (power > 0 && power <= 8) { /* name power ----------- Yobi 8 Zebi 7 Exbi 9 Pebi 5 Tebi 4 Gibi 3 Mebi 2 kibi 1 */ snprintf(dest, remaining_space, temp, " kMGTPEZY"[power]); } else if (power > 8) { /* for the larger values, print x2^{10}Gi for example */ snprintf(dest, remaining_space, "x2^{%d}Yi", power-8); } else if (power < 0) { snprintf(dest, remaining_space, "x2^{%d}", power*10); } else { snprintf(dest, remaining_space, " "); } break; } /*}}} */ /*{{{ P --- multiple of pi */ case 'P': { t[0] = 'f'; t[1] = 0; snprintf(dest, remaining_space, temp, x / M_PI); break; } /*}}} */ default: reset_numeric_locale(); int_error(NO_CARET, "Bad format character"); } /* switch */ /*}}} */ if (got_hash && (format != strpbrk(format,"oeEfFgG"))) { reset_numeric_locale(); int_error(NO_CARET, "Bad format character"); } /* change decimal '.' to the actual entry in decimalsign */ if (decimalsign != NULL) { char *dotpos1 = dest; char *dotpos2; size_t newlength = strlen(decimalsign); /* dot is the default decimalsign we will be replacing */ int dot = *get_decimal_locale(); /* replace every dot by the contents of decimalsign */ while ((dotpos2 = strchr(dotpos1,dot)) != NULL) { if (newlength == 1) { /* The normal case */ *dotpos2 = *decimalsign; dotpos1++; } else { /* Some multi-byte decimal marker */ size_t taillength = strlen(dotpos2); dotpos1 = dotpos2 + newlength; if (dotpos1 + taillength > limit) int_error(NO_CARET, "format too long due to decimalsign string"); /* move tail end of string out of the way */ memmove(dotpos1, dotpos2 + 1, taillength); /* insert decimalsign */ memcpy(dotpos2, decimalsign, newlength); } } } /* this was at the end of every single case, before: */ dest += strlen(dest); ++format; } /* for ever */ done: #if (0) /* Oct 2013 - Not safe because it fails to recognize LaTeX macros. */ /* For LaTeX terminals, if the user has not already provided a */ /* format in math mode, wrap whatever we got by default in $...$ */ if (((term->flags & TERM_IS_LATEX)) && !strchr(tempdest, '$')) { *(outstring++) = '$'; strcat(tempdest, "$"); count -= 2; } #endif /* Copy as much as fits */ safe_strncpy(outstring, tempdest, count); reset_numeric_locale(); }
void list_modules() { DIR* dir = NULL; struct dirent *dp = NULL; char *moddir = NULL; moddir = get_module_dir(); if(moddir == NULL) { error("Failure getting module directory! (Perhaps set MPG123_MODDIR?)"); exit(-1); /* TODO: change this to return a value instead of exit()! */ } /* Open the module directory */ dir = opendir(moddir); if (dir==NULL) { error2("Failed to open the module directory (%s): %s\n", PKGLIBDIR, strerror(errno)); free(moddir); exit(-1); } if(chdir(moddir) != 0) { error2("Failed to enter module directory (%s): %s\n", PKGLIBDIR, strerror(errno)); closedir( dir ); free(moddir); exit(-1); } /* Display the program title */ /* print_title(stderr); */ /* List the output modules */ printf("\n"); printf("Available modules\n"); printf("-----------------\n"); while( (dp = readdir(dir)) != NULL ) { struct stat fst; if(stat(dp->d_name, &fst) != 0) continue; if(S_ISREG(fst.st_mode)) /* Allow links? */ { char* ext = dp->d_name + strlen( dp->d_name ) - strlen( MODULE_FILE_SUFFIX ); if (strcmp(ext, MODULE_FILE_SUFFIX) == 0) { char *module_name = NULL; char *module_type = NULL; char *uscore_pos = NULL; mpg123_module_t *module = NULL; /* Extract the module type */ module_type = strdup( dp->d_name ); uscore_pos = strchr( module_type, '_' ); if (uscore_pos==NULL || (uscore_pos>=module_type+strlen(module_type)+1) ) { free(module_type); continue; } *uscore_pos = '\0'; /* Extract the short name of the module */ module_name = strdup( dp->d_name + strlen( module_type ) + 1 ); module_name[ strlen( module_name ) - strlen( MODULE_FILE_SUFFIX ) ] = '\0'; /* Open the module */ module = open_module_here(module_type, module_name); if (module) { printf("%-15s%s %s\n", module->name, module_type, module->description ); /* Close the module again */ close_module( module ); } free( module_name ); free( module_type ); } } } closedir( dir ); free(moddir); exit(0); }
/* * I used to try to select platform-provided getopt() or * getopt_long(), but that caused a lot of headaches. In particular, * I couldn't consistently use long options in the test harness * because not all platforms have getopt_long(). That in turn led to * overuse of the -W hack in the test harness, which made it rough to * run the test harness against GNU cpio. (I periodically run the * test harness here against GNU cpio as a sanity-check. Yes, * I've found a couple of bugs in GNU cpio that way.) */ int cpio_getopt(struct cpio *cpio) { enum { state_start = 0, state_next_word, state_short, state_long }; static int state = state_start; static char *opt_word; const struct option *popt, *match = NULL, *match2 = NULL; const char *p, *long_prefix = "--"; size_t optlength; int opt = '?'; int required = 0; cpio->argument = NULL; /* First time through, initialize everything. */ if (state == state_start) { /* Skip program name. */ ++cpio->argv; --cpio->argc; state = state_next_word; } /* * We're ready to look at the next word in argv. */ if (state == state_next_word) { /* No more arguments, so no more options. */ if (cpio->argv[0] == NULL) return (-1); /* Doesn't start with '-', so no more options. */ if (cpio->argv[0][0] != '-') return (-1); /* "--" marks end of options; consume it and return. */ if (strcmp(cpio->argv[0], "--") == 0) { ++cpio->argv; --cpio->argc; return (-1); } /* Get next word for parsing. */ opt_word = *cpio->argv++; --cpio->argc; if (opt_word[1] == '-') { /* Set up long option parser. */ state = state_long; opt_word += 2; /* Skip leading '--' */ } else { /* Set up short option parser. */ state = state_short; ++opt_word; /* Skip leading '-' */ } } /* * We're parsing a group of POSIX-style single-character options. */ if (state == state_short) { /* Peel next option off of a group of short options. */ opt = *opt_word++; if (opt == '\0') { /* End of this group; recurse to get next option. */ state = state_next_word; return cpio_getopt(cpio); } /* Does this option take an argument? */ p = strchr(short_options, opt); if (p == NULL) return ('?'); if (p[1] == ':') required = 1; /* If it takes an argument, parse that. */ if (required) { /* If arg is run-in, opt_word already points to it. */ if (opt_word[0] == '\0') { /* Otherwise, pick up the next word. */ opt_word = *cpio->argv; if (opt_word == NULL) { lafe_warnc(0, "Option -%c requires an argument", opt); return ('?'); } ++cpio->argv; --cpio->argc; } if (opt == 'W') { state = state_long; long_prefix = "-W "; /* For clearer errors. */ } else { state = state_next_word; cpio->argument = opt_word; } } } /* We're reading a long option, including -W long=arg convention. */ if (state == state_long) { /* After this long option, we'll be starting a new word. */ state = state_next_word; /* Option name ends at '=' if there is one. */ p = strchr(opt_word, '='); if (p != NULL) { optlength = (size_t)(p - opt_word); cpio->argument = (char *)(uintptr_t)(p + 1); } else { optlength = strlen(opt_word); } /* Search the table for an unambiguous match. */ for (popt = cpio_longopts; popt->name != NULL; popt++) { /* Short-circuit if first chars don't match. */ if (popt->name[0] != opt_word[0]) continue; /* If option is a prefix of name in table, record it.*/ if (strncmp(opt_word, popt->name, optlength) == 0) { match2 = match; /* Record up to two matches. */ match = popt; /* If it's an exact match, we're done. */ if (strlen(popt->name) == optlength) { match2 = NULL; /* Forget the others. */ break; } } } /* Fail if there wasn't a unique match. */ if (match == NULL) { lafe_warnc(0, "Option %s%s is not supported", long_prefix, opt_word); return ('?'); } if (match2 != NULL) { lafe_warnc(0, "Ambiguous option %s%s (matches --%s and --%s)", long_prefix, opt_word, match->name, match2->name); return ('?'); } /* We've found a unique match; does it need an argument? */ if (match->required) { /* Argument required: get next word if necessary. */ if (cpio->argument == NULL) { cpio->argument = *cpio->argv; if (cpio->argument == NULL) { lafe_warnc(0, "Option %s%s requires an argument", long_prefix, match->name); return ('?'); } ++cpio->argv; --cpio->argc; } } else { /* Argument forbidden: fail if there is one. */ if (cpio->argument != NULL) { lafe_warnc(0, "Option %s%s does not allow an argument", long_prefix, match->name); return ('?'); } } return (match->equivalent); } return (opt); }
/* Scan STRING for variable references and expansion-function calls. Only LENGTH bytes of STRING are actually scanned. If LENGTH is -1, scan until a null byte is found. Write the results to LINE, which must point into 'variable_buffer'. If LINE is NULL, start at the beginning of the buffer. Return a pointer to LINE, or to the beginning of the buffer if LINE is NULL. */ char * variable_expand_string (char *line, const char *string, long length) { struct variable *v; const char *p, *p1; char *save; char *o; unsigned int line_offset; if (!line) line = initialize_variable_output(); o = line; line_offset = line - variable_buffer; if (length == 0) { variable_buffer_output (o, "", 1); return (variable_buffer); } /* We need a copy of STRING: due to eval, it's possible that it will get freed as we process it (it might be the value of a variable that's reset for example). Also having a nil-terminated string is handy. */ save = length < 0 ? xstrdup (string) : xstrndup (string, length); p = save; while (1) { /* Copy all following uninteresting chars all at once to the variable output buffer, and skip them. Uninteresting chars end at the next $ or the end of the input. */ p1 = strchr (p, '$'); o = variable_buffer_output (o, p, p1 != 0 ? (unsigned int)(p1 - p) : strlen (p) + 1); if (p1 == 0) break; p = p1 + 1; /* Dispatch on the char that follows the $. */ switch (*p) { case '$': /* $$ seen means output one $ to the variable output buffer. */ o = variable_buffer_output (o, p, 1); break; case '(': case '{': /* $(...) or ${...} is the general case of substitution. */ { char openparen = *p; char closeparen = (openparen == '(') ? ')' : '}'; const char *begp; const char *beg = p + 1; char *op; char *abeg = NULL; const char *end, *colon; op = o; begp = p; if (handle_function (&op, &begp)) { o = op; p = begp; break; } /* Is there a variable reference inside the parens or braces? If so, expand it before expanding the entire reference. */ end = strchr (beg, closeparen); if (end == 0) /* Unterminated variable reference. */ fatal (*expanding_var, _("unterminated variable reference")); p1 = lindex (beg, end, '$'); if (p1 != 0) { /* BEG now points past the opening paren or brace. Count parens or braces until it is matched. */ int count = 0; for (p = beg; *p != '\0'; ++p) { if (*p == openparen) ++count; else if (*p == closeparen && --count < 0) break; } /* If COUNT is >= 0, there were unmatched opening parens or braces, so we go to the simple case of a variable name such as '$($(a)'. */ if (count < 0) { abeg = expand_argument (beg, p); /* Expand the name. */ beg = abeg; end = strchr (beg, '\0'); } } else /* Advance P to the end of this reference. After we are finished expanding this one, P will be incremented to continue the scan. */ p = end; /* This is not a reference to a built-in function and any variable references inside are now expanded. Is the resultant text a substitution reference? */ colon = lindex (beg, end, ':'); if (colon) { /* This looks like a substitution reference: $(FOO:A=B). */ const char *subst_beg, *subst_end, *replace_beg, *replace_end; subst_beg = colon + 1; subst_end = lindex (subst_beg, end, '='); if (subst_end == 0) /* There is no = in sight. Punt on the substitution reference and treat this as a variable name containing a colon, in the code below. */ colon = 0; else { replace_beg = subst_end + 1; replace_end = end; /* Extract the variable name before the colon and look up that variable. */ v = lookup_variable (beg, colon - beg); if (v == 0) warn_undefined (beg, colon - beg); /* If the variable is not empty, perform the substitution. */ if (v != 0 && *v->value != '\0') { char *pattern, *replace, *ppercent, *rpercent; char *value = (v->recursive ? recursively_expand (v) : v->value); /* Copy the pattern and the replacement. Add in an extra % at the beginning to use in case there isn't one in the pattern. */ pattern = alloca (subst_end - subst_beg + 2); *(pattern++) = '%'; memcpy (pattern, subst_beg, subst_end - subst_beg); pattern[subst_end - subst_beg] = '\0'; replace = alloca (replace_end - replace_beg + 2); *(replace++) = '%'; memcpy (replace, replace_beg, replace_end - replace_beg); replace[replace_end - replace_beg] = '\0'; /* Look for %. Set the percent pointers properly based on whether we find one or not. */ ppercent = find_percent (pattern); if (ppercent) { ++ppercent; rpercent = find_percent (replace); if (rpercent) ++rpercent; } else { ppercent = pattern; rpercent = replace; --pattern; --replace; } o = patsubst_expand_pat (o, value, pattern, replace, ppercent, rpercent); if (v->recursive) free (value); } } } if (colon == 0) /* This is an ordinary variable reference. Look up the value of the variable. */ o = reference_variable (o, beg, end - beg); if (abeg) free (abeg); } break; case '\0': break; default: if (isblank ((unsigned char)p[-1])) break; /* A $ followed by a random char is a variable reference: $a is equivalent to $(a). */ o = reference_variable (o, p, 1); break; } if (*p == '\0') break; ++p; } free (save); variable_buffer_output (o, "", 1); return (variable_buffer + line_offset); }
/* * mgmt_get_main_config() loads main configuration * from scf into a node tree. * Main configuration includes: admin/target/tpgt/initiator info. * admin info is stored in "iscsitgt" property group * target info is stored in "target_<name>" property group * initiator info is stored in "initiator_<name>" property group * tpgt info is stored in "tpgt_<number>" property group */ Boolean_t mgmt_get_main_config(tgt_node_t **node) { targ_scf_t *h = NULL; scf_property_t *prop = NULL; scf_value_t *value = NULL; scf_iter_t *iter = NULL; scf_iter_t *iter_v = NULL; scf_iter_t *iter_pv = NULL; char *pname = NULL; char *valuebuf = NULL; ssize_t max_name_len; ssize_t max_value_len; char passcode[32]; unsigned int outlen; tgt_node_t *n; tgt_node_t *pn; tgt_node_t *vn; Boolean_t status = False; h = mgmt_handle_init(); if (h == NULL) return (status); prop = scf_property_create(h->t_handle); value = scf_value_create(h->t_handle); iter = scf_iter_create(h->t_handle); if ((alloc_scf_name(&max_name_len, (void *)&pname) == False) || (alloc_scf_value(&max_value_len, (void *)&valuebuf) == False)) { goto error; } (void) pthread_mutex_lock(&scf_conf_mutex); /* Basic Information is stored in iscsitgt pg */ if (scf_service_get_pg(h->t_service, "iscsitgt", h->t_pg) == -1) { goto error; } *node = NULL; *node = tgt_node_alloc("main_config", String, NULL); if (*node == NULL) goto error; if (scf_iter_pg_properties(iter, h->t_pg) == -1) { goto error; } while (scf_iter_next_property(iter, prop) > 0) { (void) scf_property_get_value(prop, value); (void) scf_value_get_as_string(value, valuebuf, max_value_len); (void) scf_property_get_name(prop, pname, max_name_len); /* avoid load auth to incore data */ if (strcmp(pname, ISCSI_READ_AUTHNAME) == 0 || strcmp(pname, ISCSI_MODIFY_AUTHNAME) == 0 || strcmp(pname, ISCSI_VALUE_AUTHNAME) == 0) continue; n = tgt_node_alloc(pname, String, valuebuf); if (n == NULL) goto error; /* put version info into root node's attr */ if (strcmp(pname, XML_ELEMENT_VERS) == 0) { tgt_node_add_attr(*node, n); } else { /* add other basic info into root node */ tgt_node_add(*node, n); } } /* * targets/initiators/tpgt information is * stored as type "configuration" in scf * each target's param is stored as type "parameter" */ if (scf_iter_service_pgs_typed(iter, h->t_service, "configuration") == -1) { goto error; } while (scf_iter_next_pg(iter, h->t_pg) > 0) { char *iname; (void) scf_pg_get_name(h->t_pg, pname, max_name_len); pgname_decode(pname); iname = strchr(pname, '_'); if (iname == NULL) { /* the pg found here is not a tgt/initiator/tpgt */ continue; } *iname = '\0'; iname++; /* * now pname is "target" or "initiator" or "tpgt" * meanwhile iname is the actual name of the item */ n = tgt_node_alloc(pname, String, iname); if (n == NULL) goto error; iter_v = scf_iter_create(h->t_handle); if (scf_iter_pg_properties(iter_v, h->t_pg) == -1) { goto error; } while (scf_iter_next_property(iter_v, prop) > 0) { /* there may be many values in one property */ char *vname; (void) scf_property_get_name(prop, pname, max_name_len); /* avoid load auth to incore data */ if (strcmp(pname, ISCSI_READ_AUTHNAME) == 0 || strcmp(pname, ISCSI_MODIFY_AUTHNAME) == 0 || strcmp(pname, ISCSI_VALUE_AUTHNAME) == 0) continue; vname = strstr(pname, "-list"); if (vname == NULL) { (void) scf_property_get_value(prop, value); (void) scf_value_get_as_string(value, valuebuf, max_value_len); pn = tgt_node_alloc(pname, String, valuebuf); if (pn == NULL) goto error; tgt_node_add(n, pn); } else { pn = tgt_node_alloc(pname, String, NULL); if (pn == NULL) goto error; tgt_node_add(n, pn); *vname = '\0'; iter_pv = scf_iter_create(h->t_handle); (void) scf_iter_property_values(iter_pv, prop); while (scf_iter_next_value(iter_pv, value) > 0) { (void) scf_value_get_as_string( value, valuebuf, max_value_len); /* * map 'acl' to 'initiator' since that * is what used inside the acl-list. */ if (strcmp(pname, XML_ELEMENT_ACL) == 0) { vn = tgt_node_alloc( XML_ELEMENT_INIT, String, valuebuf); } else { vn = tgt_node_alloc( pname, String, valuebuf); } if (vn == NULL) goto error; tgt_node_add(pn, vn); } scf_iter_destroy(iter_pv); iter_pv = NULL; } } tgt_node_add(*node, n); scf_iter_destroy(iter_v); iter_v = NULL; } /* chap-secrets are stored in "passwords" pgroup as "application" */ if (scf_service_get_pg(h->t_service, "passwords", h->t_pg) == 0) { if (scf_iter_pg_properties(iter, h->t_pg) == -1) { goto error; } while (scf_iter_next_property(iter, prop) > 0) { (void) scf_property_get_value(prop, value); (void) scf_value_get_as_string(value, valuebuf, max_value_len); (void) scf_property_get_name(prop, pname, max_name_len); /* avoid load auth to incore data */ if (strcmp(pname, ISCSI_READ_AUTHNAME) == 0 || strcmp(pname, ISCSI_MODIFY_AUTHNAME) == 0 || strcmp(pname, ISCSI_VALUE_AUTHNAME) == 0) continue; /* max length of decoded passwd is 16B */ (void) sasl_decode64(valuebuf, strlen(valuebuf), passcode, sizeof (passcode), &outlen); if (strcmp(pname, "radius") == 0) { pn = tgt_node_alloc(XML_ELEMENT_RAD_SECRET, String, passcode); tgt_node_add(*node, pn); } else if (strcmp(pname, "main") == 0) { pn = tgt_node_alloc(XML_ELEMENT_CHAPSECRET, String, passcode); tgt_node_add(*node, pn); } else { /* find corresponding initiator */ n = NULL; while (n = tgt_node_next_child(*node, XML_ELEMENT_INIT, n)) { if (strcmp(pname + 2, n->x_value) != 0) continue; pn = tgt_node_alloc( XML_ELEMENT_CHAPSECRET, String, passcode); tgt_node_add(n, pn); } } } } status = True; error: if ((status != True) && (*node != NULL)) tgt_node_free(*node); (void) pthread_mutex_unlock(&scf_conf_mutex); if (iter_pv != NULL) scf_iter_destroy(iter_pv); if (iter_v != NULL) scf_iter_destroy(iter_v); free(valuebuf); free(pname); scf_iter_destroy(iter); scf_value_destroy(value); scf_property_destroy(prop); mgmt_handle_fini(h); return (status); }
struct ftp_connection_info *add_file_cmd_to_str(struct connection *c) { unsigned char *d = get_url_data(c->url); unsigned char *de; int del; unsigned char pc[6]; int ps; struct ftp_connection_info *inf, *inf2; unsigned char *s; int l; if (!d) { internal("get_url_data failed"); setcstate(c, S_INTERNAL); abort_connection(c); return NULL; } de = init_str(), del = 0; add_conv_str(&de, &del, d, strlen(d), -2); d = de; inf = mem_alloc(sizeof(struct ftp_connection_info)); memset(inf, 0, sizeof(struct ftp_connection_info)); l = 0; s = init_str(); inf->pasv = ftp_options.passive_ftp; if (*c->socks_proxy) inf->pasv = 1; c->info = inf; if (!inf->pasv) if ((ps = get_pasv_socket(c, c->sock1, &c->sock2, pc))) { mem_free(d); return NULL; } #ifdef HAVE_IPTOS if (ftp_options.set_tos) { int on = IPTOS_THROUGHPUT; setsockopt(c->sock2, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)); } #endif if (!(de = strchr(d, POST_CHAR))) de = d + strlen(d); if (d == de || de[-1] == '/') { inf->dir = 1; inf->pending_commands = 4; add_to_str(&s, &l, "TYPE A\r\n"); if (!inf->pasv) { add_to_str(&s, &l, "PORT "); add_num_to_str(&s, &l, pc[0]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[1]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[2]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[3]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[4]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[5]); add_to_str(&s, &l, "\r\n"); } else { add_to_str(&s, &l, "PASV\r\n"); } add_to_str(&s, &l, "CWD /"); add_bytes_to_str(&s, &l, d, de - d); add_to_str(&s, &l, "\r\nLIST\r\n"); c->from = 0; } else { inf->dir = 0; inf->pending_commands = 3; add_to_str(&s, &l, "TYPE I\r\n"); if (!inf->pasv) { add_to_str(&s, &l, "PORT "); add_num_to_str(&s, &l, pc[0]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[1]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[2]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[3]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[4]); add_chr_to_str(&s, &l, ','); add_num_to_str(&s, &l, pc[5]); add_to_str(&s, &l, "\r\n"); } else { add_to_str(&s, &l, "PASV\r\n"); } if (c->from && c->no_cache < NC_IF_MOD) { add_to_str(&s, &l, "REST "); add_num_to_str(&s, &l, c->from); add_to_str(&s, &l, "\r\n"); inf->rest_sent = 1; inf->pending_commands++; } else c->from = 0; add_to_str(&s, &l, "RETR /"); add_bytes_to_str(&s, &l, d, de - d); add_to_str(&s, &l, "\r\n"); } inf->opc = inf->pending_commands; if ((unsigned)l > MAXINT - sizeof(struct ftp_connection_info) - 1) overalloc(); inf2 = mem_realloc(inf, sizeof(struct ftp_connection_info) + l + 1); strcpy((inf = inf2)->cmdbuf, s); mem_free(s); c->info = inf; mem_free(d); return inf; }