/* * Leaves f->fd open on success, caller must close */ static int extend_file(struct thread_data *td, struct fio_file *f) { int r, new_layout = 0, unlink_file = 0, flags; unsigned long long left; unsigned int bs; char *b = NULL; if (read_only) { log_err("fio: refusing extend of file due to read-only\n"); return 0; } /* * check if we need to lay the file out complete again. fio * does that for operations involving reads, or for writes * where overwrite is set */ if (td_read(td) || (td_write(td) && td->o.overwrite && !td->o.file_append) || (td_write(td) && td->io_ops->flags & FIO_NOEXTEND)) new_layout = 1; if (td_write(td) && !td->o.overwrite && !td->o.file_append) unlink_file = 1; if (unlink_file || new_layout) { dprint(FD_FILE, "layout unlink %s\n", f->file_name); if ((unlink(f->file_name) < 0) && (errno != ENOENT)) { td_verror(td, errno, "unlink"); return 1; } } flags = O_WRONLY | O_CREAT; if (new_layout) flags |= O_TRUNC; #ifdef WIN32 flags |= _O_BINARY; #endif dprint(FD_FILE, "open file %s, flags %x\n", f->file_name, flags); f->fd = open(f->file_name, flags, 0644); if (f->fd < 0) { td_verror(td, errno, "open"); return 1; } #ifdef CONFIG_POSIX_FALLOCATE if (!td->o.fill_device) { switch (td->o.fallocate_mode) { case FIO_FALLOCATE_NONE: break; case FIO_FALLOCATE_POSIX: dprint(FD_FILE, "posix_fallocate file %s size %llu\n", f->file_name, (unsigned long long) f->real_file_size); r = posix_fallocate(f->fd, 0, f->real_file_size); if (r > 0) { log_err("fio: posix_fallocate fails: %s\n", strerror(r)); } break; #ifdef CONFIG_LINUX_FALLOCATE case FIO_FALLOCATE_KEEP_SIZE: dprint(FD_FILE, "fallocate(FALLOC_FL_KEEP_SIZE) " "file %s size %llu\n", f->file_name, (unsigned long long) f->real_file_size); r = fallocate(f->fd, FALLOC_FL_KEEP_SIZE, 0, f->real_file_size); if (r != 0) td_verror(td, errno, "fallocate"); break; #endif /* CONFIG_LINUX_FALLOCATE */ default: log_err("fio: unknown fallocate mode: %d\n", td->o.fallocate_mode); assert(0); } } #endif /* CONFIG_POSIX_FALLOCATE */ if (!new_layout) goto done; /* * The size will be -1ULL when fill_device is used, so don't truncate * or fallocate this file, just write it */ if (!td->o.fill_device) { dprint(FD_FILE, "truncate file %s, size %llu\n", f->file_name, (unsigned long long) f->real_file_size); if (ftruncate(f->fd, f->real_file_size) == -1) { if (errno != EFBIG) { td_verror(td, errno, "ftruncate"); goto err; } } } b = malloc(td->o.max_bs[DDIR_WRITE]); left = f->real_file_size; while (left && !td->terminate) { bs = td->o.max_bs[DDIR_WRITE]; if (bs > left) bs = left; fill_io_buffer(td, b, bs, bs); r = write(f->fd, b, bs); if (r > 0) { left -= r; continue; } else { if (r < 0) { int __e = errno; if (__e == ENOSPC) { if (td->o.fill_device) break; log_info("fio: ENOSPC on laying out " "file, stopping\n"); break; } td_verror(td, errno, "write"); } else td_verror(td, EIO, "write"); break; } } if (td->terminate) { dprint(FD_FILE, "terminate unlink %s\n", f->file_name); unlink(f->file_name); } else if (td->o.create_fsync) { if (fsync(f->fd) < 0) { td_verror(td, errno, "fsync"); goto err; } } if (td->o.fill_device && !td_write(td)) { fio_file_clear_size_known(f); if (td_io_get_file_size(td, f)) goto err; if (f->io_size > f->real_file_size) f->io_size = f->real_file_size; } free(b); done: return 0; err: close(f->fd); f->fd = -1; if (b) free(b); return 1; }
int Process(etPMode PMode, // processing mode etFMode FMode, // output format mode int MovAvgFilter, // apply this moving average window size filter int BaselineFilter, // baseline normalisation window size char *pszTrackName, // UCSC track name double DyadratioThres, // dyad grooves must be at least this ratio to background double Dyad2ratioThres, // immediately flanking grooves must be at least this ratio to background double Dyad3ratioThres, // remainder of flanking grooves must be at least this ration to background char *pszInGenomefile, // bioseq genome file char *pszInConfFile, // file containing conformation characteristics char *pszOutFile, // where to write nucleosome predictions char *pszInclRegionFile, // only report predicted nucleosomes if intersecting with regions in this file int OfsLoci, // offset region start loci by this many nt int DeltaLen, // change region length by this many nt int TruncLength) // truncate regions to be a maximum of this length { int Rslt = 0; bool bRegionFilter; // set true if region filtering int SeqIdx; int WindLen = 147; // nucleosomes are this length - agreed :-) int ChkGroove[13]; // to hold dyad (ChkGroove[6]) and +/- 6 at approx decimer (depends on twist) offsets int DecIdx; // index into ChkGroove, incr/decr every 360 degree twist int GrooveCnt; // to hold number of groove values contributing to current ChkGroove[DecIdx] so average can be calculated int AccumTwist; // to hold accumulated twist relative to dyad int ChkTwist; // AccumTwist % 360 used to determine if minor groove back on same plane as at dyad int BaseLineValueSum; double BaseLineAv; double ChromBaseLineSum; int NumBaseLines; Init(); m_PMode = PMode; m_FMode = FMode; strcpy(m_szTrackName,pszTrackName); m_DyadratioThres = DyadratioThres; m_Dyad2ratioThres = Dyad2ratioThres; m_Dyad3ratioThres = Dyad3ratioThres; if((m_pszOutBuff = new char [cAllocOutBuff])==NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to alloc memory (%d bytes requested) for bufering output results",cAllocOutBuff); Reset(); return(eBSFerrMem); } m_AllocdOutBuff = cAllocOutBuff; if((m_pBioSeqFile = new CBioSeqFile) == NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to instantiate CBioSeqFile object"); Reset(); return(eBSFerrObj); } if((Rslt = m_pBioSeqFile->Open(pszInGenomefile))!=eBSFSuccess) { while(m_pBioSeqFile->NumErrMsgs()) gDiagnostics.DiagOut(eDLFatal,gszProcName,m_pBioSeqFile->GetErrMsg()); gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to open genome assembly sequence file '%s'",pszInGenomefile); Reset(); return(Rslt); } if(pszInclRegionFile != NULL && pszInclRegionFile[0] != '\0') { if((Rslt = LoadRegions(pszInclRegionFile,OfsLoci,DeltaLen,TruncLength))!=eBSFSuccess) { Reset(); return(Rslt); } bRegionFilter = true; } else bRegionFilter = false; if((m_pTwister = new CTwister)==NULL) { gDiagnostics.DiagOut(eDLFatal,"ProcessFastaStruct","Unable to create CTwister object"); Reset(); return(eBSFerrObj); } if((Rslt = m_pTwister->LoadStructParams(pszInConfFile)) < eBSFSuccess) { while(m_pTwister->NumErrMsgs()) gDiagnostics.DiagOut(eDLFatal,gszProcName,m_pTwister->GetErrMsg()); gDiagnostics.DiagOut(eDLFatal,"ProcessFastaStruct","LoadStructParams(%s) failed",pszInConfFile); Reset(); return(Rslt); } #ifdef _WIN32 if((m_hOutFile = open(pszOutFile, _O_RDWR | _O_BINARY | _O_SEQUENTIAL | _O_CREAT | _O_TRUNC, _S_IREAD | _S_IWRITE ))==-1) #else if((m_hOutFile = open(pszOutFile, O_RDWR | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE ))==-1) #endif { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to create predicted nucleosome output file: %s - %s",pszOutFile,strerror(errno)); Reset(); return(eBSFerrCreateFile); } if(FMode == eFMbedGraphDyads || FMode == eFMbedGraphNucs) { m_UsedOutBuff = sprintf(m_pszOutBuff, "track type=bedGraph name=\"%s\" description=\"%s\" visibility=full color=200,100,0 altColor=0,100,200 priority=20 autoScale=on alwaysZero=on graphType=bar smoothingWindow=4\n", pszTrackName,pszTrackName); CUtility::SafeWrite(m_hOutFile,m_pszOutBuff,m_UsedOutBuff); m_UsedOutBuff = 0; } // iterate over chromosomes tBSFEntryID ChromID = 0; while((ChromID = m_pBioSeqFile->Next(ChromID))>0) { m_pBioSeqFile->GetName(ChromID,sizeof(m_szCurChrom),m_szCurChrom); gDiagnostics.DiagOut(eDLInfo,gszProcName,"Processing %s...",m_szCurChrom); m_ChromSeqLen = m_pBioSeqFile->GetDataLen(ChromID); if(m_pChromSeq == NULL || m_ChromSeqLen > m_AllocdChromSeq) { if(m_pChromSeq != NULL) { delete m_pChromSeq; m_pChromSeq = NULL; } int AllocLen = m_ChromSeqLen + m_ChromSeqLen/10; if((m_pChromSeq = new unsigned char [AllocLen])==NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to alloc memory (%d requested) for holding raw sequence data",AllocLen); Reset(); return(eBSFerrMem); } m_AllocdChromSeq = AllocLen; if(m_pScores != NULL) { delete m_pScores; m_pScores = NULL; } if((m_pScores = new int [AllocLen])==NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to allocate memory (%d bytes) for holding scores",AllocLen); Reset(); return(eBSFerrMem); } if(m_pConfGroove != NULL) { delete m_pConfGroove; m_pConfGroove = NULL; } if((m_pConfGroove = new int [AllocLen])==NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to allocate memory (%d bytes) for holding minor groove conformation values",AllocLen); Reset(); return(eBSFerrMem); } if(m_pConfTwist != NULL) { delete m_pConfTwist; m_pConfTwist = NULL; } if((m_pConfTwist = new int [AllocLen])==NULL) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Unable to allocate memory (%d bytes) for holding rotational twist conformation values",AllocLen); Reset(); return(eBSFerrMem); } } if((Rslt=m_pBioSeqFile->GetData(ChromID,eSeqBaseType,0,m_pChromSeq,m_ChromSeqLen)) != m_ChromSeqLen) { gDiagnostics.DiagOut(eDLFatal,gszProcName,"Loading sequence of length %d failed from chrom: %s file: '%s'",m_ChromSeqLen,m_szCurChrom,pszInGenomefile); Reset(); return(Rslt); } // remove any repeat masking and randomly substitute bases for eBaseN's - not expecting too many of these say's he hopefully! etSeqBase *pSeq = m_pChromSeq; for(SeqIdx = 0; SeqIdx < m_ChromSeqLen; SeqIdx++,pSeq++) if((*pSeq &= ~cRptMskFlg) > eBaseT) *pSeq = rand() % 4; if((Rslt = m_pTwister->GetSequenceConformation(eSSminorgroove, // process for this conformational parameter 0, // initial starting offset (0..n) in pSeq 0, // number of steps (0 for all) to process starting at pSeq[iStartPsn]|pSeq[iStartPsn+1] m_ChromSeqLen, // total length of sequence m_pChromSeq, // sequence to be processed m_pConfGroove))!=eBSFSuccess) // where to return step conformational values { gDiagnostics.DiagOut(eDLFatal,"GetSequenceConformation","minor groove failed"); Reset(); return(Rslt); } if((Rslt = m_pTwister->GetSequenceConformation(eSStwist, // process for this conformational parameter 0, // initial starting offset (0..n) in pSeq 0, // number of steps (0 for all) to process starting at pSeq[iStartPsn]|pSeq[iStartPsn+1] m_ChromSeqLen, // total length of sequence m_pChromSeq, // sequence to be processed m_pConfTwist))!=eBSFSuccess) // where to return step conformational values { gDiagnostics.DiagOut(eDLFatal,"GetSequenceConformation","rotational twist failed"); Reset(); return(Rslt); } memset(m_pScores,0,m_ChromSeqLen * sizeof(int)); // reset all scores back to minimum // establish the baseline conformational characteristic value over initial window which is centered around the WindLen window // the baseline will be updated as the putative dyad is slid along the chromosome int *pConfGroove; int *pBaseLineWin5; int *pBaseLineWin3; int *pConfTwist; int BaseLineWin = min(5 * WindLen,m_ChromSeqLen); BaseLineValueSum = 0; pBaseLineWin3 = m_pConfGroove; for(SeqIdx = 0; SeqIdx < BaseLineWin; SeqIdx++) BaseLineValueSum += *pBaseLineWin3++; double BestMaxRatio = 0.0f; double BestMinRatio = 10000.0f; int DyadFirstOfs = 73; int DyadLastOfs = m_ChromSeqLen - 73; m_ChromPutDyads = 0; ChromBaseLineSum = 0.0; NumBaseLines = 0; pBaseLineWin5 = m_pConfGroove; for(SeqIdx = DyadFirstOfs; SeqIdx < DyadLastOfs; SeqIdx++) { if(SeqIdx > BaseLineWin/2 && SeqIdx < (m_ChromSeqLen - (BaseLineWin+1)/2)) { BaseLineValueSum -= *pBaseLineWin5++; BaseLineValueSum += *pBaseLineWin3++; } BaseLineAv = (double)BaseLineValueSum/BaseLineWin; ChromBaseLineSum += BaseLineAv/10000.0f; NumBaseLines += 1; if(bRegionFilter && !InAnyRegion(ChromID,SeqIdx-74,SeqIdx+73,0)) continue; DecIdx = 6; pConfGroove = &m_pConfGroove[SeqIdx]; ChkGroove[DecIdx++] = *pConfGroove++; m_DyadRatio = (double)ChkGroove[6]/BaseLineAv; if(m_DyadRatio < DyadratioThres) continue; pConfTwist = &m_pConfTwist[SeqIdx+1]; AccumTwist = *pConfTwist; ChkGroove[DecIdx] = 0; GrooveCnt = 0; // iterate over bases to right of putative dyad and every rotation of the dsDNA get the minor groove int Bases = 1; while(DecIdx <= 12) { Bases += 1; pConfTwist += 1; pConfGroove += 1; AccumTwist += *pConfTwist; ChkTwist = AccumTwist % 3600000; if(ChkTwist >= 3300000 || ChkTwist <= 300000) { ChkGroove[DecIdx] += *pConfGroove; GrooveCnt += 1; } else { if(GrooveCnt > 0) { ChkGroove[DecIdx] /= GrooveCnt; GrooveCnt = 0; if(DecIdx++ < 12) ChkGroove[DecIdx]= 0; } } } // now iterate over bases to left of putative dyad and every rotation of the dsDNA get the minor groove DecIdx = 5; pConfGroove = &m_pConfGroove[SeqIdx-1]; pConfTwist = &m_pConfTwist[SeqIdx-1]; AccumTwist = *pConfTwist; ChkGroove[DecIdx] = 0; GrooveCnt = 0; Bases = 1; while(DecIdx >= 0) { Bases += 1; pConfTwist -= 1; pConfGroove -= 1; AccumTwist += *pConfTwist; ChkTwist = AccumTwist % 3600000; if(ChkTwist >= 3300000 || ChkTwist <= 300000) { ChkGroove[DecIdx] += *pConfGroove; GrooveCnt += 1; } else { if(GrooveCnt > 0) { ChkGroove[DecIdx] /= GrooveCnt; GrooveCnt = 0; if(DecIdx-- > 0) ChkGroove[DecIdx] = 0; } } } m_Dyad2Ratio = (double)(ChkGroove[5] + ChkGroove[7])/(2*BaseLineAv); m_Dyad3Ratio = (double)(ChkGroove[0] + ChkGroove[1] + ChkGroove[2] + ChkGroove[3] + ChkGroove[4] + ChkGroove[8] + ChkGroove[9] + ChkGroove[10] + ChkGroove[11] + ChkGroove[12])/(10*BaseLineAv); if(m_Dyad2Ratio < Dyad2ratioThres || m_Dyad3Ratio < Dyad3ratioThres) continue; if(bRegionFilter) InAnyRegion(ChromID,SeqIdx-74,SeqIdx+73,1); int LocScore = (int)(1000 * ((m_DyadRatio - 1.0f) + ((m_Dyad2Ratio - 1.0f) * 0.85) + ((m_Dyad3Ratio - 1.0f) * 0.75))); if(LocScore < 0) printf("\nHave an issue!"); m_pScores[SeqIdx] = LocScore; } OutputDyads(m_hOutFile, // results file FMode, // output format mode MovAvgFilter, // apply this width moving average filter BaselineFilter, // use this window size when normalising for baseline pszTrackName, // track name m_szCurChrom, // dyads on this chromosome m_ChromSeqLen, // last dyad loci m_pScores); // dyad scores gDiagnostics.DiagOut(eDLInfo,gszProcName,"On chromosome '%s' (length %d), %d putative nucleosome dyads were identified - running total: %d",m_szCurChrom,m_ChromSeqLen,m_ChromPutDyads,m_NumPutDyads); gDiagnostics.DiagOut(eDLInfo,gszProcName,"On chromosome '%s' (length %d), averaged minor groove baseline was %1.6f",m_szCurChrom,m_ChromSeqLen,ChromBaseLineSum/NumBaseLines); } if(m_UsedOutBuff) { if((Rslt=write(m_hOutFile,m_pszOutBuff,m_UsedOutBuff))!=m_UsedOutBuff) Rslt = eBSFerrWrite; m_UsedOutBuff = 0; } gDiagnostics.DiagOut(eDLInfo,gszProcName,"After processing a total of %d putative nucleosome dyads have been identified",m_NumPutDyads); DumpRegionHitStats(); Reset(); return(Rslt); }
static int filehash58_cb (const char *p, const char *f, const char *h, probe_ctx *ctx) { SEXP_t *itm; char pbuf[PATH_MAX+1]; size_t plen, flen; int fd; if (f == NULL) return (0); /* * Prepare path */ plen = strlen (p); flen = strlen (f); if (plen + flen + 1 > PATH_MAX) return (-1); memcpy (pbuf, p, sizeof (char) * plen); if (p[plen - 1] != FILE_SEPARATOR) { pbuf[plen] = FILE_SEPARATOR; ++plen; } memcpy (pbuf + plen, f, sizeof (char) * flen); pbuf[plen+flen] = '\0'; /* * Open the file */ fd = open (pbuf, O_RDONLY); if (fd < 0) { strerror_r (errno, pbuf, PATH_MAX); pbuf[PATH_MAX] = '\0'; itm = probe_item_create (OVAL_INDEPENDENT_FILE_HASH58, NULL, "filepath", OVAL_DATATYPE_STRING, pbuf, "path", OVAL_DATATYPE_STRING, p, "filename", OVAL_DATATYPE_STRING, f, "hash_type",OVAL_DATATYPE_STRING, h, NULL); probe_item_add_msg(itm, OVAL_MESSAGE_LEVEL_ERROR, "Can't open \"%s\": errno=%d, %s.", pbuf, errno, strerror (errno)); probe_item_setstatus(itm, SYSCHAR_STATUS_ERROR); } else { uint8_t hash_dst[1025]; size_t hash_dstlen = sizeof hash_dst; char hash_str[2051]; crapi_alg_t hash_type; hash_type = oscap_string_to_enum(CRAPI_ALG_MAP, h); hash_dstlen = oscap_string_to_enum(CRAPI_ALG_MAP_SIZE, h); /* * Compute hash value */ if (crapi_mdigest_fd (fd, 1, hash_type, hash_dst, &hash_dstlen) != 0) { close (fd); return (-1); } close (fd); hash_str[0] = '\0'; mem2hex (hash_dst, hash_dstlen, hash_str, sizeof hash_str); /* * Create and add the item */ itm = probe_item_create(OVAL_INDEPENDENT_FILE_HASH58, NULL, "filepath", OVAL_DATATYPE_STRING, pbuf, "path", OVAL_DATATYPE_STRING, p, "filename", OVAL_DATATYPE_STRING, f, "hash_type",OVAL_DATATYPE_STRING, h, "hash", OVAL_DATATYPE_STRING, hash_str, NULL); if (hash_dstlen == 0) { probe_item_add_msg(itm, OVAL_MESSAGE_LEVEL_ERROR, "Unable to compute %s hash value of \"%s\".", h, pbuf); probe_item_setstatus(itm, SYSCHAR_STATUS_ERROR); } } probe_item_collect(ctx, itm); return (0); }
int PX4IO_Uploader::upload(const char *filenames[]) { int ret; const char *filename = NULL; size_t fw_size; #ifndef PX4IO_SERIAL_DEVICE #error Must define PX4IO_SERIAL_DEVICE in board configuration to support firmware upload #endif /* allow an early abort and look for file first */ for (unsigned i = 0; filenames[i] != nullptr; i++) { _fw_fd = open(filenames[i], O_RDONLY); if (_fw_fd < 0) { log("failed to open %s", filenames[i]); continue; } log("using firmware from %s", filenames[i]); filename = filenames[i]; break; } if (filename == NULL) { log("no firmware found"); close(_io_fd); _io_fd = -1; return -ENOENT; } _io_fd = open(PX4IO_SERIAL_DEVICE, O_RDWR); if (_io_fd < 0) { log("could not open interface"); return -errno; } /* save initial uart configuration to reset after the update */ struct termios t_original; tcgetattr(_io_fd, &t_original); /* adjust line speed to match bootloader */ struct termios t; tcgetattr(_io_fd, &t); cfsetspeed(&t, 115200); tcsetattr(_io_fd, TCSANOW, &t); /* look for the bootloader */ ret = sync(); if (ret != OK) { /* this is immediately fatal */ log("bootloader not responding"); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return -EIO; } struct stat st; if (stat(filename, &st) != 0) { log("Failed to stat %s - %d\n", filename, (int)errno); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return -errno; } fw_size = st.st_size; if (_fw_fd == -1) { tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return -ENOENT; } /* do the usual program thing - allow for failure */ for (unsigned retries = 0; retries < 1; retries++) { if (retries > 0) { log("retrying update..."); ret = sync(); if (ret != OK) { /* this is immediately fatal */ log("bootloader not responding"); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return -EIO; } } ret = get_info(INFO_BL_REV, bl_rev); if (ret == OK) { if (bl_rev <= BL_REV) { log("found bootloader revision: %d", bl_rev); } else { log("found unsupported bootloader revision %d, exiting", bl_rev); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return OK; } } ret = erase(); if (ret != OK) { log("erase failed"); continue; } ret = program(fw_size); if (ret != OK) { log("program failed"); continue; } if (bl_rev <= 2) ret = verify_rev2(fw_size); else if(bl_rev == 3) { ret = verify_rev3(fw_size); } if (ret != OK) { log("verify failed"); continue; } ret = reboot(); if (ret != OK) { log("reboot failed"); tcsetattr(_io_fd, TCSANOW, &t_original); close(_io_fd); _io_fd = -1; return ret; } log("update complete"); ret = OK; break; } /* reset uart to previous/default baudrate */ tcsetattr(_io_fd, TCSANOW, &t_original); close(_fw_fd); close(_io_fd); _io_fd = -1; return ret; }
static int lock_and_daemon(bool daemonize, const char *base_dir) { int ret, devnull_fd = 0, status = 0; int pipefd[2]; ret = pipe(pipefd); if (ret < 0) panic("pipe() for passing exit status failed: %m"); if (daemonize) { switch (fork()) { case 0: break; case -1: panic("fork() failed during daemonize: %m"); break; default: ret = read(pipefd[0], &status, sizeof(status)); if (ret != sizeof(status)) panic("read exit status failed: %m"); exit(status); break; } if (setsid() == -1) { sd_err("becoming a leader of a new session failed: %m"); status = 1; goto end; } switch (fork()) { case 0: break; case -1: sd_err("fork() failed during daemonize: %m"); status = 1; goto end; default: exit(0); break; } if (chdir("/")) { sd_err("chdir to / failed: %m"); status = 1; goto end; } devnull_fd = open("/dev/null", O_RDWR); if (devnull_fd < 0) { sd_err("opening /dev/null failed: %m"); status = 1; goto end; } } ret = lock_base_dir(base_dir); if (ret < 0) { sd_err("locking directory: %s failed", base_dir); status = 1; goto end; } if (daemonize) { /* * now we can use base_dir/sheep.log for logging error messages, * we can close 0, 1, and 2 safely */ dup2(devnull_fd, 0); dup2(devnull_fd, 1); dup2(devnull_fd, 2); close(devnull_fd); } end: ret = write(pipefd[1], &status, sizeof(status)); if (ret != sizeof(status)) panic("writing exit status failed: %m"); return status; }
int test(char *URL) { int res = 0; CURL *curl; FILE *hd_src ; int hd ; int error; struct_stat file_info; int running; char done=FALSE; CURLM *m; struct timeval ml_start; struct timeval mp_start; char ml_timedout = FALSE; char mp_timedout = FALSE; if (!libtest_arg2) { fprintf(stderr, "Usage: lib525 [url] [uploadfile]\n"); return -1; } /* get the file size of the local file */ hd = open(libtest_arg2, O_RDONLY) ; fstat(hd, &file_info); close(hd) ; /* get a FILE * of the same file, could also be made with fdopen() from the previous descriptor, but hey this is just an example! */ hd_src = fopen(libtest_arg2, "rb"); if(NULL == hd_src) { error = ERRNO; fprintf(stderr, "fopen() failed with error: %d %s\n", error, strerror(error)); fprintf(stderr, "Error opening file: %s\n", libtest_arg2); return TEST_ERR_MAJOR_BAD; } if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { fprintf(stderr, "curl_global_init() failed\n"); fclose(hd_src); return TEST_ERR_MAJOR_BAD; } if ((curl = curl_easy_init()) == NULL) { fprintf(stderr, "curl_easy_init() failed\n"); fclose(hd_src); curl_global_cleanup(); return TEST_ERR_MAJOR_BAD; } /* enable uploading */ curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); /* specify target */ curl_easy_setopt(curl,CURLOPT_URL, URL); /* go verbose */ curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); /* use active FTP */ curl_easy_setopt(curl, CURLOPT_FTPPORT, "-"); /* now specify which file to upload */ curl_easy_setopt(curl, CURLOPT_READDATA, hd_src); /* NOTE: if you want this code to work on Windows with libcurl as a DLL, you MUST also provide a read callback with CURLOPT_READFUNCTION. Failing to do so will give you a crash since a DLL may not use the variable's memory when passed in to it from an app like this. */ /* Set the size of the file to upload (optional). If you give a *_LARGE option you MUST make sure that the type of the passed-in argument is a curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must make sure that to pass in a type 'long' argument. */ curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_info.st_size); if ((m = curl_multi_init()) == NULL) { fprintf(stderr, "curl_multi_init() failed\n"); curl_easy_cleanup(curl); curl_global_cleanup(); fclose(hd_src); return TEST_ERR_MAJOR_BAD; } if ((res = (int)curl_multi_add_handle(m, curl)) != CURLM_OK) { fprintf(stderr, "curl_multi_add_handle() failed, " "with code %d\n", res); curl_multi_cleanup(m); curl_easy_cleanup(curl); curl_global_cleanup(); fclose(hd_src); return TEST_ERR_MAJOR_BAD; } ml_timedout = FALSE; ml_start = tutil_tvnow(); while (!done) { fd_set rd, wr, exc; int max_fd; struct timeval interval; interval.tv_sec = 1; interval.tv_usec = 0; if (tutil_tvdiff(tutil_tvnow(), ml_start) > MAIN_LOOP_HANG_TIMEOUT) { ml_timedout = TRUE; break; } mp_timedout = FALSE; mp_start = tutil_tvnow(); while (res == CURLM_CALL_MULTI_PERFORM) { res = (int)curl_multi_perform(m, &running); if (tutil_tvdiff(tutil_tvnow(), mp_start) > MULTI_PERFORM_HANG_TIMEOUT) { mp_timedout = TRUE; break; } if (running <= 0) { done = TRUE; break; } } if (mp_timedout || done) break; if (res != CURLM_OK) { fprintf(stderr, "not okay???\n"); break; } FD_ZERO(&rd); FD_ZERO(&wr); FD_ZERO(&exc); max_fd = 0; if (curl_multi_fdset(m, &rd, &wr, &exc, &max_fd) != CURLM_OK) { fprintf(stderr, "unexpected failured of fdset.\n"); res = 189; break; } if (select_test(max_fd+1, &rd, &wr, &exc, &interval) == -1) { fprintf(stderr, "bad select??\n"); res = 195; break; } res = CURLM_CALL_MULTI_PERFORM; } if (ml_timedout || mp_timedout) { if (ml_timedout) fprintf(stderr, "ml_timedout\n"); if (mp_timedout) fprintf(stderr, "mp_timedout\n"); fprintf(stderr, "ABORTING TEST, since it seems " "that it would have run forever.\n"); res = TEST_ERR_RUNS_FOREVER; } #ifdef LIB529 /* test 529 */ curl_multi_remove_handle(m, curl); curl_multi_cleanup(m); curl_easy_cleanup(curl); #else /* test 525 */ curl_multi_remove_handle(m, curl); curl_easy_cleanup(curl); curl_multi_cleanup(m); #endif fclose(hd_src); /* close the local file */ curl_global_cleanup(); return res; }
static CURLcode file_upload(struct connectdata *conn) { struct FILEPROTO *file = conn->data->req.protop; const char *dir = strchr(file->path, DIRSEP); int fd; int mode; CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; char *buf = data->state.buffer; size_t nread; size_t nwrite; curl_off_t bytecount = 0; struct timeval now = Curl_tvnow(); struct_stat file_stat; const char* buf2; /* * Since FILE: doesn't do the full init, we need to provide some extra * assignments here. */ conn->data->req.upload_fromhere = buf; if(!dir) return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ if(!dir[1]) return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */ #ifdef O_BINARY #define MODE_DEFAULT O_WRONLY|O_CREAT|O_BINARY #else #define MODE_DEFAULT O_WRONLY|O_CREAT #endif if(data->state.resume_from) mode = MODE_DEFAULT|O_APPEND; else mode = MODE_DEFAULT|O_TRUNC; fd = open(file->path, mode, conn->data->set.new_file_perms); if(fd < 0) { failf(data, "Can't open %s for writing", file->path); return CURLE_WRITE_ERROR; } if(-1 != data->state.infilesize) /* known size of data to "upload" */ Curl_pgrsSetUploadSize(data, data->state.infilesize); /* treat the negative resume offset value as the case of "-" */ if(data->state.resume_from < 0) { if(fstat(fd, &file_stat)) { close(fd); failf(data, "Can't get the size of %s", file->path); return CURLE_WRITE_ERROR; } else data->state.resume_from = (curl_off_t)file_stat.st_size; } while(!result) { int readcount; result = Curl_fillreadbuffer(conn, BUFSIZE, &readcount); if(result) break; if(readcount <= 0) /* fix questionable compare error. curlvms */ break; nread = (size_t)readcount; /*skip bytes before resume point*/ if(data->state.resume_from) { if((curl_off_t)nread <= data->state.resume_from ) { data->state.resume_from -= nread; nread = 0; buf2 = buf; } else { buf2 = buf + data->state.resume_from; nread -= (size_t)data->state.resume_from; data->state.resume_from = 0; } } else buf2 = buf; /* write the data to the target */ nwrite = write(fd, buf2, nread); if(nwrite != nread) { result = CURLE_SEND_ERROR; break; } bytecount += nread; Curl_pgrsSetUploadCounter(data, bytecount); if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, now); } if(!result && Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; close(fd); return result; }
void run_pcie_logging(void) { char dev_name[40]; int pq_fd; unsigned int host_ring_buffer_size = RING_BUF_ELEMS * RING_BUF_ELEM_SIZE; volatile TrioMsg *p; printf("Waiting for PCIe logging data from card %d on queue %d...\n", card_index, queue_index); if (path_prefix) { printf("PCIe logging into directory: '%s'\n", path_prefix); fflush(stdout); } /* Open the packet queue file. */ snprintf(dev_name, sizeof(dev_name), "/dev/tilegxpci%d/packet_queue/t2h/%d", card_index, queue_index); do { pq_fd = open(dev_name, O_RDWR); if (pq_fd < 0) { sleep(1); } } while (pq_fd < 0); /* mmap the register space. */ struct gxpci_host_pq_regs_app* pq_regs = (struct gxpci_host_pq_regs_app*) mmap(0, sizeof(struct gxpci_host_pq_regs_app), PROT_READ | PROT_WRITE, MAP_SHARED, pq_fd, TILEPCI_PACKET_QUEUE_INDICES_MMAP_OFFSET); if (pq_regs == MAP_FAILED) { fprintf(stderr, "Failed to mmap PCIe control registers.\n"); exit(EXIT_FAILURE); } /* Configure and allocate the ring buffer for the receive queue. */ tilepci_packet_queue_info_t buf_info; buf_info.buf_size = RING_BUF_ELEM_SIZE; int err = ioctl(pq_fd, TILEPCI_IOC_SET_PACKET_QUEUE_BUF, &buf_info); if (err < 0) { fprintf(stderr, "Failed TILEPCI_IOC_SET_PACKET_QUEUE_BUF: %s\n", strerror(errno)); abort(); } /* On the host side, mmap the receive queue region. */ void* buffer = mmap(0, host_ring_buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, pq_fd, TILEPCI_PACKET_QUEUE_BUF_MMAP_OFFSET); assert(buffer != MAP_FAILED); /* On the host side, mmap the queue status. */ struct tlr_pq_status *pq_status = mmap(0, sizeof(struct tlr_pq_status), PROT_READ | PROT_WRITE, MAP_SHARED, pq_fd, TILEPCI_PACKET_QUEUE_STS_MMAP_OFFSET); assert(pq_status != MAP_FAILED); pq_regs->consumer_index = 0; uint64_t packet_count = 0; volatile uint32_t write; uint32_t read = 0; #ifdef CHECK_SEQ_NUM uint32_t expect_seq = 1; #endif #ifdef HOST_INTERRUPT_MODE volatile uint32_t* producer_index = &(pq_status->drv_consumer_index); #else volatile uint32_t* producer_index = &(pq_regs->producer_index); #endif volatile uint32_t* consumer_index = &(pq_regs->consumer_index); volatile enum gxpci_chan_status_t* status = &(pq_status->status); while (1) { if (*status == GXPCI_CHAN_RESET) { printf("Tile to Host PCIe logging channel was reset.\n"); fflush(stdout); return; } // Get packets off the ring buffer by accessing the receive queue at // the new write index. write = *producer_index; while (write != read) { if (*status == GXPCI_CHAN_RESET) { printf("Tile to Host PCIe logging channel was reset.\n"); fflush(stdout); return; } packet_count++; p = (TrioMsg *)(buffer + ((read&(RING_BUF_ELEMS-1))*RING_BUF_ELEM_SIZE)); if (debug) { fprintf(stdout, "got a message\n"); fprintf(stdout, "p->magic: %d\n", p->magic); fprintf(stdout, "p->fileno: %d\n", p->fileno); #ifdef CHECK_SEQ_NUM fprintf(stdout, "p->seq: %d\n", p->seq); #endif fprintf(stdout, "p->len: %d\n", p->len); fprintf(stdout, "p->next_offset: %d\n", p->next_offset); fprintf(stdout, "p->buf: "); fwrite(&p->buf, sizeof(char), p->len - offsetof(TrioMsg, buf), stdout); fprintf(stdout, "\n"); fflush(stdout); } #ifdef CHECK_SEQ_NUM if (p->seq != expect_seq) { /* Check for a reset before reporting a bad sequence * number to prevent confusing users. */ if (*status == GXPCI_CHAN_RESET) { printf("Tile to Host PCIe logging channel was reset.\n"); fflush(stdout); return; } fprintf(stderr, "BAD sequence expected %d got %d\n", expect_seq, p->seq); return; } expect_seq = p->seq + 1; #endif switch (p->op) { case OP_OPEN: if (p->fileno < MAX_FDESC) { fdesc[p->fileno] = malloc(sizeof(FDesc)); if (fdesc[p->fileno]) { char mode[2]; mode[0] = p->buf[0]; mode[1] = '\0'; char *file_name = (char *)&p->buf[1]; if (path_prefix) { /* Added path_prefix to the start of the * file name. Added space for '\0' and '\'. * By default, no prefix is added. */ int new_size = strlen(path_prefix) + strlen(file_name) + 1 + 1; char *new_name = malloc(new_size); if (!new_name) { fprintf(stderr, "Failed to allocate memory for %s/%s\n", path_prefix, file_name); return; } snprintf(new_name, new_size, "%s/%s", path_prefix, file_name); file_name = new_name; } if ((fdesc[p->fileno]->fd = fopen(file_name, mode)) == NULL) { fprintf(stderr, "Could not open %s: %s\n", file_name, strerror(errno)); } else { printf("Opened '%s' for logging.\n", file_name); fflush(stdout); } } } else { fprintf(stderr, "File number %d exceeds Max of %d\n", p->fileno, MAX_FDESC); } break; case OP_WRITE: if (drop_alerts) { /* TODO: Report alert count periodically. */ } else { if (fdesc[p->fileno] && fdesc[p->fileno]->fd) { fwrite(&p->buf, sizeof(char), p->len - offsetof(TrioMsg, buf), fdesc[p->fileno]->fd); fflush(fdesc[p->fileno]->fd); } } break; case OP_CLOSE: if (fdesc[p->fileno] && fdesc[p->fileno]->fd) { fclose( fdesc[p->fileno]->fd); free(fdesc[p->fileno]); fdesc[p->fileno] = NULL; } break; } read++; /* Update the read index register to inform the tile side * that the packet has been read. */ #ifdef TAIL_UPDATE_LIMIT_ENABLE if ((packet_count & 0x3f) == 0) *consumer_index = read; #else *consumer_index = read; #endif } } return; }
//***************************************************************************** mlMainWindow::mlMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::mlMainWindow), uniConverter(0) { ui->setupUi(this); //------------------------------------------------------------------------- // Load the mapping file QByteArray map; QFile mfile(":/maps/maps/mollana-urdu.tec"); if( mfile.open( QIODevice::ReadOnly ) ) { qDebug() << "Internal Urdu mapping file loaded..."; map = mfile.readAll(); mfile.close(); qDebug() << "Map size: " << map.size() << ""; } else { qDebug() << "Unable to open Internal Urdu mapping file for reading...\n"; //raise exception return; } //------------------------------------------------------------------------- // Create the converter uniConverter = new TECkitConverter( map ); if( !uniConverter->isValid() ) { qDebug() << "Unable to create Unicode TECkit converter..."; //raise exception return; } //------------------------------------------------------------------------- // Toolbars ui->mainToolBar->addAction( ui->actionNew ); ui->mainToolBar->addAction( ui->actionOpen ); ui->mainToolBar->addAction( ui->actionSave ); ui->mainToolBar->addSeparator(); ui->mainToolBar->addAction( ui->actionUndo ); ui->mainToolBar->addAction( ui->actionRedo ); ui->mainToolBar->addSeparator(); ui->mainToolBar->addAction( ui->actionCopy ); ui->mainToolBar->addAction( ui->actionCut ); ui->mainToolBar->addAction( ui->actionPaste ); ui->mainToolBar->addSeparator(); ui->mainToolBar->addAction( ui->actionUnicodeViewFont ); ui->mainToolBar->addAction( ui->actionWordWrap ); ui->mainToolBar->addSeparator(); //------------------------------------------------------------------------- // Signal/Slots connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(newFile()) ); connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(open()) ); connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(save()) ); connect(ui->actionSaveAs, SIGNAL(triggered()), this, SLOT(saveAs()) ); connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(close()) ); connect(ui->actionSelectAll,SIGNAL(triggered()), ui->tbxEditor, SLOT(selectAll()) ); connect(ui->actionEditorFont, SIGNAL(triggered()), this, SLOT(editorFontChanged()) ); connect(ui->actionUnicodeViewFont, SIGNAL(triggered()), this, SLOT(unicodeFontChanged()) ); connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(about()) ); connect(ui->tbxEditor->document(), SIGNAL(contentsChanged()), this, SLOT(documentModified()) ); // Copy, Cut & Paste connect(ui->actionCut, SIGNAL(triggered()), ui->tbxEditor, SLOT(cut()) ); connect(ui->actionCopy, SIGNAL(triggered()), ui->tbxEditor, SLOT(copy()) ); connect(ui->actionPaste, SIGNAL(triggered()), ui->tbxEditor, SLOT(paste()) ); connect(ui->tbxEditor, SIGNAL(copyAvailable(bool)), ui->actionCopy, SLOT(setEnabled(bool)) ); connect(ui->tbxEditor, SIGNAL(copyAvailable(bool)), ui->actionCut, SLOT(setEnabled(bool)) ); // Undo & Redo connect(ui->actionUndo, SIGNAL(triggered()), ui->tbxEditor, SLOT(undo()) ); connect(ui->actionCopy, SIGNAL(triggered()), ui->tbxEditor, SLOT(redo()) ); connect(ui->tbxEditor, SIGNAL(undoAvailable(bool)), ui->actionUndo, SLOT(setEnabled(bool)) ); connect(ui->tbxEditor, SIGNAL(redoAvailable(bool)), ui->actionRedo, SLOT(setEnabled(bool)) ); connect(ui->actionWordWrap, SIGNAL(toggled(bool)), this, SLOT(wordWrapChanged(bool)) ); connect(ui->actionUnicodeOutput, SIGNAL(toggled(bool)), ui->dckUnicodeOutput, SLOT(setVisible(bool)) ); connect(ui->tbxEditor, SIGNAL(textChanged()), this, SLOT(translateText()) ); //------------------------------------------------------------------------- QFont f = ui->tbxUnicodeView->font(); f.setStyleStrategy(QFont::PreferAntialias); ui->tbxUnicodeView->setFont(f); //------------------------------------------------------------------------- // Start with a new file newFile(); }
int main(int argc, char *argv[]) { int status = EXIT_SUCCESS; int timeout = 0; int numFileSystems = 0; int *fileSystemDescriptors = NULL; int i = 0; if (argc < 3) { printUsage(); JUMPWITHSTATUS(EXIT_FAILURE); } if ((timeout = atoi(argv[1])) <= 0) { printUsage(); JUMPWITHSTATUS(EXIT_FAILURE); } numFileSystems = argc - 2; fileSystemDescriptors = (int *) malloc(sizeof(int) * numFileSystems); for (i = 0; i < numFileSystems; i++) { fileSystemDescriptors[i] = -1; } for (i = 0; i < numFileSystems; i++) { char *mountPoint = argv[i + 2]; if ((fileSystemDescriptors[i] = open(mountPoint, O_RDONLY)) < 0) { printf("Failed to open: %s\n", mountPoint); JUMPWITHSTATUS(EXIT_FAILURE); } struct stat sb; if (fstat(fileSystemDescriptors[i], &sb) == -1) { printf("Failed to stat: %s\n", mountPoint); JUMPWITHSTATUS(EXIT_FAILURE); } if ((sb.st_mode & S_IFDIR) == 0) { printf("Path not a directory: %s\n", mountPoint); JUMPWITHSTATUS(EXIT_FAILURE); } } struct sigaction globalSignalAction = {0}; globalSignalAction.sa_handler = globalSignalHandler; if (sigaction(SIGHUP, &globalSignalAction, NULL) || sigaction(SIGINT, &globalSignalAction, NULL) || sigaction(SIGQUIT, &globalSignalAction, NULL) || sigaction(SIGABRT, &globalSignalAction, NULL) || sigaction(SIGPIPE, &globalSignalAction, NULL) || sigaction(SIGTERM, &globalSignalAction, NULL) || sigaction(SIGUSR1, &globalSignalAction, NULL) || sigaction(SIGUSR2, &globalSignalAction, NULL) || sigaction(SIGTSTP, &globalSignalAction, NULL) || sigaction(SIGTTIN, &globalSignalAction, NULL) || sigaction(SIGTTOU, &globalSignalAction, NULL) ) { printf("Failed to setup signal handlers\n"); JUMPWITHSTATUS(EXIT_FAILURE); } for (i = 0; i < numFileSystems; i++) { char *mountPoint = argv[i + 2]; printf("freezing the mount: %s\n", mountPoint); if (ioctl(fileSystemDescriptors[i], FIFREEZE, 0) != 0) { printf("Failed to FIFREEZE: %s\n", mountPoint); JUMPWITHSTATUS(EXIT_FAILURE); } } if (kill(getppid(), SIGUSR1) != 0) { printf("Failed to send FreezeCompletion to parent process\n"); JUMPWITHSTATUS(EXIT_FAILURE); } for (i = 0; i < timeout; i++) { if (gThaw == 1 || sleep(1) != 0) { break; } } if (gThaw != 1) { printf("Failed to receive timely Thaw from parent process\n"); JUMPWITHSTATUS(EXIT_FAILURE); } CLEANUP: if (fileSystemDescriptors != NULL) { for (i = 0; i < numFileSystems; i++) { if (fileSystemDescriptors[i] >= 0) { char *mountPoint = argv[i + 2]; printf("unfreezing the mount: %s\n", mountPoint); if (ioctl(fileSystemDescriptors[i], FITHAW, 0) != 0) { printf("Failed to FITHAW: %s\n", mountPoint); status = EXIT_FAILURE; } close(fileSystemDescriptors[i]); fileSystemDescriptors[i] = -1; } } free(fileSystemDescriptors); fileSystemDescriptors = NULL; } return status; }
bool SerialPort::Open( const char *inDevName, const char *param ) { char devName[ 40 ]; unsigned baudRate; devName[ 0 ] = '\0'; #if 1 if ( inDevName[ 0 ] != '/' ) { StrMaxCpy( devName, "/dev/", sizeof( devName )); } #endif StrMaxCat( devName, inDevName, sizeof( devName )); // Translate the params, if any speed_t speed = B0; if ( param == NULL ) { speed = B38400; baudRate = 38400; } else { baudRate = atoi( param ); for ( unsigned i = 0; i < ARRAY_LEN( gBaudTable ); i++ ) { if ( gBaudTable[ i ].baudRate == baudRate ) { speed = gBaudTable[ i ].speed; break; } } if ( speed == B0 ) { LogError( "Unrecognized baud rate: '%s'\n", param ); return false; } } LogVerbose( "Port: '%s' Baud: %d\n", devName, baudRate ); if (( m_fd = open( devName, O_RDWR | O_EXCL )) < 0 ) { LogError( "Unable to open serial port '%s': %s\n", devName, strerror( errno )); return false; } // Setup the serial port struct termios attr; if ( tcgetattr( m_fd, &attr ) < 0 ) { LogError( "A: Call to tcgetattr failed: %s\n", strerror( errno )); return false; } attr.c_iflag = 0; attr.c_oflag = 0; attr.c_cflag = CLOCAL | CREAD | CS8; attr.c_lflag = 0; attr.c_cc[ VTIME ] = 0; // timeout in tenths of a second attr.c_cc[ VMIN ] = 1; cfsetispeed( &attr, speed ); cfsetospeed( &attr, speed ); if ( tcsetattr( m_fd, TCSAFLUSH, &attr ) < 0 ) { LogError( "Call to tcsetattr failed: %s\n", strerror( errno )); return false; } return true; } // Open
int main( int argc, char **argv ) { int fd, fsz; int i, j, k; char tmp[ 3 ]; char c; // Check input if( argc != 2 ) { help(); return 0; } // Open the file fd = open( argv[ 1 ], O_RDWR); if( fd < 0 ) { fprintf( stderr, "Cannot open file: %s\n", argv[ 1 ] ); return -1; } // Get file size fsz = lseek( fd, 0, SEEK_END ); lseek( fd, 0, SEEK_SET ); // Allocate memory buf = malloc( fsz ); if( !buf ) { fprintf( stderr, "Out of memory (buf)\n" ); return -1; } // Clear the memory memset( buf, 0, fsz ); // Read in the file if( read( fd, buf, fsz ) != fsz ) { fprintf( stderr, "Cannot read full length of the file\n" ); close( fd ); return -1; } // Close close( fd ); // Allocate memory tmpbuf = malloc( fsz ); if( !tmpbuf ) { fprintf( stderr, "Out of memory (tmpbuf)\n" ); return -1; } // Convert hex ascii to binary tmp[ 2 ] = '\0'; for( i = 0, j = 0, k = 0 ; i < fsz ; i++ ) { // Read a character c = *(buf + i); // Ignore non-ASCII one if( checkHexAscii( c ) ) continue; // Assign to the tmp tmp[ j++ ] = c; if( j >= 2 ) { j = 0; // Convert to binary tmpbuf[ k++ ] = (char)(strtol( tmp, NULL, 16 ) & 0xFF); //printf( "val = 0x%2.2X\n", tmpbuf[ k - 1 ] ); } } #if 0 // Allocate the final buffer inst = malloc( k ); if( !inst ) { fprintf( stderr, "Out of memory( inst )\n" ); free( tmpbuf ); free( buf ); return -1; } #endif memset( inst, 0, sizeof( inst ) ); // Copy the free resources memcpy( inst, tmpbuf, k ); free( tmpbuf ); free( buf ); // Print out the address of the buf printf( "Oops Code @ address: %p\n", inst ); *(int *)0 = 0; // Return return 0; }
int Client::_listen() { int client_recv_pipe_fd = open(_recv_pipe_path, O_RDONLY); if (client_recv_pipe_fd < 0) { PX4_ERR("open failed, errno: %d, %s", errno, strerror(errno)); } bool exit_loop = false; int exit_arg = 0; while (!exit_loop) { // We only read as much as we need, otherwise we might get out of // sync with packets. client_recv_packet_s packet_recv; int bytes_read = read(client_recv_pipe_fd, &packet_recv, sizeof(client_recv_packet_s::header)); if (bytes_read > 0) { // Using the header we can determine how big the payload is. int payload_to_read = sizeof(packet_recv) - sizeof(packet_recv.header) - sizeof(packet_recv.payload) + packet_recv.header.payload_length; // Again, we only read as much as we need because otherwise we need // hold a buffer and parse it. bytes_read = read(client_recv_pipe_fd, ((uint8_t *)&packet_recv) + bytes_read, payload_to_read); if (bytes_read > 0) { int retval = 0; bool should_exit = false; int parse_ret = _parse_client_recv_packet(packet_recv, retval, should_exit); if (parse_ret != 0) { PX4_ERR("retval could not be parsed"); exit_arg = -1; } else { exit_arg = retval; } exit_loop = should_exit; } else if (bytes_read == 0) { exit_arg = 0; exit_loop = true; } } else if (bytes_read == 0) { // 0 means the pipe has been closed by all clients. exit_arg = 0; exit_loop = true; } } close(_client_send_pipe_fd); return exit_arg; }
int main(int argc, char *argv[]) { int pipefd[2],pip[2]; pid_t cpid; if (pipe(pipefd) == -1 || pipe(pip) == -1) { perror("pipe"); exit(EXIT_FAILURE); } cpid = fork(); if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (cpid == 0) { /* Child reads from pipe */ char fname[30]; printf("\n enter the file name:"); scanf("%s",fname); close(pip[0]); /* Close unused read end */ write(pip[1], fname, strlen(fname)); close(pip[1]); close(pipefd[1]); /* Close unused write end */ char buff[300];int i=0; int rd=read(pipefd[0], buff, 300); write(STDOUT_FILENO,buff, rd); write(STDOUT_FILENO, "\n", 1); close(pipefd[0]); _exit(EXIT_SUCCESS); } else { /* Parent writes argv[1] to pipe */ /* Close unused write end */ close(pip[1]); char buf[30]; int rd=read(pip[0], buf, 30); write(STDOUT_FILENO, buf, rd); write(STDOUT_FILENO, "\n", 1); close(pip[0]); //write(STDOUT_FILENO, "\n", 1); int fp=open(buf,O_RDONLY,0666); if(fp!=-1) { char buff[300]; int rd=read(fp,buff,300); close(pipefd[0]); /* Close unused read end */ write(pipefd[1], buff,rd); close(pipefd[1]); /* Reader will see EOF */ } wait(NULL); /* Wait for child */ exit(EXIT_SUCCESS); } return 0; }
int switch_p_libstate_restore(char *dir_name, bool recover) { #ifdef HAVE_NATIVE_CRAY char *data = NULL, *file_name; Buf buffer = NULL; int error_code = SLURM_SUCCESS; int state_fd, data_allocated = 0, data_read = 0, data_size = 0; xassert(dir_name != NULL); if (debug_flags & DEBUG_FLAG_SWITCH) { CRAY_INFO("restore from %s, recover %d", dir_name, (int) recover); } if (!recover) /* clean start, no recovery */ return SLURM_SUCCESS; file_name = xstrdup(dir_name); xstrcat(file_name, "/switch_cray_state"); state_fd = open (file_name, O_RDONLY); if (state_fd >= 0) { data_allocated = SWITCH_BUF_SIZE; data = xmalloc(data_allocated); while (1) { data_read = read (state_fd, &data[data_size], SWITCH_BUF_SIZE); if ((data_read < 0) && (errno == EINTR)) continue; if (data_read < 0) { CRAY_ERR("Read error on %s, %m", file_name); error_code = SLURM_ERROR; break; } else if (data_read == 0) break; data_size += data_read; data_allocated += data_read; xrealloc(data, data_allocated); } close (state_fd); (void) unlink(file_name); /* One chance to recover */ xfree(file_name); } else { CRAY_ERR("No %s file for switch/cray state recovery", file_name); CRAY_ERR("Starting switch/cray with clean state"); xfree(file_name); return SLURM_SUCCESS; } if (error_code == SLURM_SUCCESS) { buffer = create_buf (data, data_size); data = NULL; /* now in buffer, don't xfree() */ _state_read_buf(buffer); } if (buffer) free_buf(buffer); xfree(data); #endif return SLURM_SUCCESS; }
int blkdev_refresh(blkdev_t *blk) { int fd = 0; char *devpath = NULL; unsigned char *block = NULL; int i, rc; if (!(block = malloc(512))) goto out; /* * Get the device size */ devpath = blkdev_get_devpath(blk); if ((fd = open(devpath, O_RDONLY)) < 0) { LOGE("Unable to open device '%s' (%s)", devpath, strerror(errno)); return -errno; } if (ioctl(fd, BLKGETSIZE, &blk->nr_sec)) { LOGE("Unable to get device size (%s)", strerror(errno)); return -errno; } close(fd); free(devpath); /* * Open the disk partition table */ devpath = blkdev_get_devpath(blk->disk); if ((fd = open(devpath, O_RDONLY)) < 0) { LOGE("Unable to open device '%s' (%s)", devpath, strerror(errno)); free(devpath); return -errno; } free(devpath); if ((rc = read(fd, block, 512)) != 512) { LOGE("Unable to read device partition table (%d, %s)", rc, strerror(errno)); goto out; } /* * If we're a disk, then process the partition table. Otherwise we're * a partition so get the partition type */ if (blk->type == blkdev_disk) { blk->nr_parts = 0; if ((block[0x1fe] != 0x55) || (block[0x1ff] != 0xAA)) { LOGI("Disk %d:%d does not contain a partition table", blk->major, blk->minor); goto out; } for (i = 0; i < NDOSPART; i++) { struct dos_partition part; dos_partition_dec(block + DOSPARTOFF + i * sizeof(struct dos_partition), &part); if (part.dp_flag != 0 && part.dp_flag != 0x80) { struct fat_boot_sector *fb = (struct fat_boot_sector *) &block[0]; if (!i && fb->reserved && fb->fats && fat_valid_media(fb->media)) { LOGI("Detected FAT filesystem in partition table"); break; } else { LOGI("Partition table looks corrupt"); break; } } if (part.dp_size != 0 && part.dp_typ != 0) blk->nr_parts++; } } else if (blk->type == blkdev_partition) { struct dos_partition part; int part_no; if (blk->media->media_type == media_mmc) part_no = blk->minor % MMC_PARTS_PER_CARD -1; else part_no = blk->minor -1; if (part_no < NDOSPART) { dos_partition_dec(block + DOSPARTOFF + part_no * sizeof(struct dos_partition), &part); blk->part_type = part.dp_typ; } else { LOGW("Skipping partition %d", part_no); } } out: if (block) free(block); char tmp[255]; char tmp2[32]; sprintf(tmp, "%s (blkdev %d:%d), %u secs (%u MB)", (blk->type == blkdev_disk ? "Disk" : "Partition"), blk->major, blk->minor, blk->nr_sec, (uint32_t) (((uint64_t) blk->nr_sec * 512) / 1024) / 1024); if (blk->type == blkdev_disk) sprintf(tmp2, " %d partitions", blk->nr_parts); else sprintf(tmp2, " type 0x%x", blk->part_type); strcat(tmp, tmp2); LOGI(tmp); close(fd); return 0; }
int /* O - New file descriptor or -1 on error */ cupsTempFd(char *filename, /* I - Pointer to buffer */ int len) /* I - Size of buffer */ { int fd; /* File descriptor for temp file */ int tries; /* Number of tries */ const char *tmpdir; /* TMPDIR environment var */ #ifdef WIN32 char tmppath[1024]; /* Windows temporary directory */ DWORD curtime; /* Current time */ #else struct timeval curtime; /* Current time */ #endif /* WIN32 */ /* * See if TMPDIR is defined... */ #ifdef WIN32 if ((tmpdir = getenv("TEMP")) == NULL) { GetTempPath(sizeof(tmppath), tmppath); tmpdir = tmppath; } #else /* * Previously we put root temporary files in the default CUPS temporary * directory under /var/spool/cups. However, since the scheduler cleans * out temporary files there and runs independently of the user apps, we * don't want to use it unless specifically told to by cupsd. */ if ((tmpdir = getenv("TMPDIR")) == NULL) # if defined(__APPLE__) && !TARGET_OS_IOS tmpdir = "/private/tmp"; /* /tmp is a symlink to /private/tmp */ # else tmpdir = "/tmp"; # endif /* __APPLE__ && !TARGET_OS_IOS */ #endif /* WIN32 */ /* * Make the temporary name using the specified directory... */ tries = 0; do { #ifdef WIN32 /* * Get the current time of day... */ curtime = GetTickCount() + tries; /* * Format a string using the hex time values... */ snprintf(filename, (size_t)len - 1, "%s/%05lx%08lx", tmpdir, GetCurrentProcessId(), curtime); #else /* * Get the current time of day... */ gettimeofday(&curtime, NULL); /* * Format a string using the hex time values... */ snprintf(filename, (size_t)len - 1, "%s/%05x%08x", tmpdir, (unsigned)getpid(), (unsigned)(curtime.tv_sec + curtime.tv_usec + tries)); #endif /* WIN32 */ /* * Open the file in "exclusive" mode, making sure that we don't * stomp on an existing file or someone's symlink crack... */ #ifdef WIN32 fd = open(filename, _O_CREAT | _O_RDWR | _O_TRUNC | _O_BINARY, _S_IREAD | _S_IWRITE); #elif defined(O_NOFOLLOW) fd = open(filename, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW, 0600); #else fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600); #endif /* WIN32 */ if (fd < 0 && errno != EEXIST) break; tries ++; } while (fd < 0 && tries < 1000); /* * Return the file descriptor... */ return (fd); }
/* * Function : libaroma_stream_file * Return Value: LIBAROMA_STREAMP * Descriptions: new stream from file */ LIBAROMA_STREAMP libaroma_stream_file( char * path) { #ifdef LIBAROMA_SYSCAL_HAVE_MMAP if (!path) { ALOGW("libaroma_stream_file path is invalid"); return NULL; } LIBAROMA_STREAMP ret; /* Read File Stat */ int filesize=libaroma_filesize(path); if (filesize < 0) { ALOGI("libaroma_stream_file (%s) not found", path); return NULL; } /* Open File */ int fd = open(path, O_RDONLY, 0); if (fd < 0) { ALOGW("libaroma_stream_file unable to open (%s)", path); return NULL; } /* MAP */ bytep mem = (bytep) mmap(NULL, filesize, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0); /* Close FD */ close(fd); if (mem == MAP_FAILED) { ALOGW("libaroma_stream_file unable to mmap (%s)", path); return NULL; } /* Return */ ret = (LIBAROMA_STREAMP) malloc(sizeof(LIBAROMA_STREAM)); ret->data = mem; ret->size = filesize; ret->ismmap = 1; snprintf(ret->uri, LIBAROMA_STREAM_URI_LENGTH, "file://%s", path); return ret; #else if (!path) { ALOGW("libaroma_stream_file path is invalid"); return 0; } LIBAROMA_STREAMP ret; /* Read File Stat */ int filesize=libaroma_filesize(path); if (filesize < 0) { ALOGI("libaroma_stream_file (%s) not found", path); return NULL; } /* Allocating Memory */ bytep mem = malloc(filesize); FILE * f = fopen(path, "rb"); if (f == NULL) { ALOGW("libaroma_stream_file fopen error (%s)", path); goto error; } if (((int) fread(mem, 1, filesize, f)) != filesize) { ALOGW("libaroma_stream_file fread error (%s)", path); fclose(f); goto error; } fclose(f); goto done; error: free(mem); return NULL; done: ret = (LIBAROMA_STREAMP) malloc(sizeof(LIBAROMA_STREAM)); ret->data = mem; ret->size = filesize; ret->ismmap = 0; snprintf(ret->uri, LIBAROMA_STREAM_URI_LENGTH, "file://%s", path); return ret; #endif } /* End of libaroma_stream_file */
/** open file. The same as fiob_open but receives additional open (2) flags */ FILE * fiob_open(const char *path, const char *mode) { int omode = 0666; int flags = 0; int save_errno; size_t bsize = 0; void *buf = NULL; int um = umask(0722); umask(um); omode &= ~um; if (strchr(mode, 'r')) { if (strchr(mode, '+')) flags |= O_RDWR; else flags |= O_RDONLY; } else if (strchr(mode, 'w')) { flags |= O_TRUNC | O_CREAT; if (strchr(mode, '+')) flags |= O_RDWR; else flags |= O_WRONLY; } else if (strchr(mode, 'a')) { flags |= O_CREAT | O_APPEND; if (strchr(mode, '+')) flags |= O_RDWR; else flags |= O_WRONLY; } else { errno = EINVAL; return NULL; } /* O_EXCL */ #ifdef O_EXCL if (strchr(mode, 'x')) flags |= O_EXCL; #endif /* O_DIRECT */ if (strchr(mode, 'd')) { #ifdef O_DIRECT flags |= O_DIRECT; #endif bsize = O_DIRECT_BSIZE; posix_memalign(&buf, 4096, bsize); if (!buf) { errno = ENOMEM; return NULL; } /* for valgrind */ memset(buf, 0, bsize); } /* O_SYNC */ if (strchr(mode, 's')) { flags |= WAL_SYNC_FLAG; } struct fiob *f = (struct fiob *)calloc(1, sizeof(struct fiob)); if (!f) { free(buf); errno = ENOMEM; return NULL; } f->path = strdup(path); if (!f->path) { errno = ENOMEM; goto error; } f->buf = buf; f->bsize = bsize; f->fd = open(path, flags, omode); if (f->fd < 0) goto error; f->io.read = fiob_read; f->io.write = fiob_write; f->io.seek = fiob_seek; f->io.close = fiob_close; FILE *file; #ifdef HAVE_FUNOPEN file = funopen(f, f->io.read, f->io.write, f->io.seek, f->io.close); #else file = fopencookie(f, mode, f->io); #endif if (!file) goto error; #ifdef TARGET_OS_LINUX file->_fileno = f->fd; #else file->_file = f->fd; #endif return file; error: save_errno = errno; say_syserror("Can't open '%s'", path); if (f->fd > 0) close(f->fd); free(f->buf); free(f->path); free(f); errno = save_errno; return NULL; }
int main (void) { int result = 0; size_t cnt; AsmCtx_t *ctx; Elf *elf; int fd; elf_version (EV_CURRENT); Ebl *ebl = ebl_openbackend_machine (EM_386); if (ebl == NULL) { puts ("cannot open backend library"); return 1; } ctx = asm_begin (fname, ebl, false); if (ctx == NULL) { printf ("cannot create assembler context: %s\n", asm_errmsg (-1)); return 1; } if (asm_newabssym (ctx, "tst8-out.s", 4, 0xfeedbeef, STT_FILE, STB_LOCAL) == NULL) { printf ("cannot create absolute symbol: %s\n", asm_errmsg (-1)); asm_abort (ctx); return 1; } /* Create the output file. */ if (asm_end (ctx) != 0) { printf ("cannot create output file: %s\n", asm_errmsg (-1)); asm_abort (ctx); return 1; } /* Check the file. */ fd = open (fname, O_RDONLY); if (fd == -1) { printf ("cannot open generated file: %m\n"); result = 1; goto out; } elf = elf_begin (fd, ELF_C_READ, NULL); if (elf == NULL) { printf ("cannot create ELF descriptor: %s\n", elf_errmsg (-1)); result = 1; goto out_close; } if (elf_kind (elf) != ELF_K_ELF) { puts ("not a valid ELF file"); result = 1; goto out_close2; } for (cnt = 1; 1; ++cnt) { Elf_Scn *scn; GElf_Shdr shdr_mem; GElf_Shdr *shdr; scn = elf_getscn (elf, cnt); if (scn == NULL) { printf ("cannot get section %Zd: %s\n", cnt, elf_errmsg (-1)); result = 1; continue; } shdr = gelf_getshdr (scn, &shdr_mem); if (shdr == NULL) { printf ("cannot get section header for section %Zd: %s\n", cnt, elf_errmsg (-1)); result = 1; continue; } /* We are looking for the symbol table. */ if (shdr->sh_type != SHT_SYMTAB) continue; for (cnt = 1; cnt< (shdr->sh_size / gelf_fsize (elf, ELF_T_SYM, 1, EV_CURRENT)); ++cnt) { GElf_Sym sym_mem; GElf_Sym *sym; if (cnt > 1) { puts ("too many symbol"); result = 1; break; } sym = gelf_getsym (elf_getdata (scn, NULL), cnt, &sym_mem); if (sym == NULL) { printf ("cannot get symbol %zu: %s\n", cnt, elf_errmsg (-1)); result = 1; } else { if (sym->st_shndx != SHN_ABS) { printf ("expected common symbol, got section %u\n", (unsigned int) sym->st_shndx); result = 1; } if (sym->st_value != 0xfeedbeef) { printf ("requested value 0xfeedbeef, is %#" PRIxMAX "\n", (uintmax_t) sym->st_value); result = 1; } if (sym->st_size != 4) { printf ("requested size 4, is %" PRIuMAX "\n", (uintmax_t) sym->st_value); result = 1; } if (GELF_ST_TYPE (sym->st_info) != STT_FILE) { printf ("requested type FILE, is %u\n", (unsigned int) GELF_ST_TYPE (sym->st_info)); result = 1; } } } break; } out_close2: elf_end (elf); out_close: close (fd); out: /* We don't need the file anymore. */ unlink (fname); ebl_closebackend (ebl); return result; }
int main(int argc, char **argv) { int ret, i, mhblock, unitsize, block; unsigned int nblocks[4], npart; unsigned int totblocks; struct INFTLPartition *ip; unsigned char *oobbuf; struct mtd_oob_buf oob; char line[20]; int mhoffs; struct INFTLMediaHeader *mh2; if (argc < 2) { printf( "Usage: %s <mtddevice> [<size1> [<size2> [<size3> [<size4]]]]\n" " Sizes are in device units (run with no sizes to show unitsize and current\n" " partitions). Last size = 0 means go to end of device.\n", argv[0]); return 1; } npart = argc - 2; if (npart > 4) { printf("Max 4 partitions allowed.\n"); return 1; } for (i = 0; i < npart; i++) { nblocks[i] = strtoul(argv[2+i], NULL, 0); if (i && !nblocks[i-1]) { printf("No sizes allowed after 0\n"); return 1; } } // Open and size the device if ((fd = open(argv[1], O_RDWR)) < 0) { perror("Open flash device"); return 1; } if (ioctl(fd, MEMGETINFO, &meminfo) != 0) { perror("ioctl(MEMGETINFO)"); return 1; } printf("Device size is %d bytes. Erasesize is %d bytes.\n", meminfo.size, meminfo.erasesize); buf = malloc(meminfo.erasesize); oobbuf = malloc((meminfo.erasesize / meminfo.oobblock) * meminfo.oobsize); if (!buf || !oobbuf) { printf("Can't malloc block buffer\n"); return 1; } oob.length = meminfo.oobsize; mh = (struct INFTLMediaHeader *) buf; for (mhblock = 0; mhblock < MAXSCAN; mhblock++) { if ((ret = pread(fd, buf, meminfo.erasesize, mhblock * meminfo.erasesize)) < 0) { if (errno == EBADMSG) { printf("ECC error at eraseblock %d\n", mhblock); continue; } perror("Read eraseblock"); return 1; } if (ret != meminfo.erasesize) { printf("Short read!\n"); return 1; } if (!strcmp("BNAND", mh->bootRecordID)) break; } if (mhblock >= MAXSCAN) { printf("Unable to find INFTL Media Header\n"); return 1; } printf("Found INFTL Media Header at block %d:\n", mhblock); mhoffs = mhblock * meminfo.erasesize; oob.ptr = oobbuf; oob.start = mhoffs; for (i = 0; i < meminfo.erasesize; i += meminfo.oobblock) { if (ioctl(fd, MEMREADOOB, &oob)) { perror("ioctl(MEMREADOOB)"); return 1; } oob.start += meminfo.oobblock; oob.ptr += meminfo.oobsize; } show_header(mhoffs); if (!npart) return 0; printf("\n" "-------------------------------------------------------------------------\n"); unitsize = meminfo.erasesize >> le32_to_cpu(mh->BlockMultiplierBits); totblocks = meminfo.size / unitsize; block = mhoffs / unitsize; block++; mh->NoOfBDTLPartitions = 0; mh->NoOfBinaryPartitions = npart; for (i = 0; i < npart; i++) { ip = &(mh->Partitions[i]); ip->firstUnit = cpu_to_le32(block); if (!nblocks[i]) nblocks[i] = totblocks - block; ip->virtualUnits = cpu_to_le32(nblocks[i]); block += nblocks[i]; ip->lastUnit = cpu_to_le32(block-1); ip->spareUnits = 0; ip->flags = cpu_to_le32(INFTL_BINARY); } if (block > totblocks) { printf("Requested partitions extend beyond end of device.\n"); return 1; } ip->flags = cpu_to_le32(INFTL_BINARY | INFTL_LAST); /* update the spare as well */ mh2 = (struct INFTLMediaHeader *) (buf + 4096); memcpy((void *) mh2, (void *) mh, sizeof(struct INFTLMediaHeader)); printf("\nProposed new Media Header:\n"); show_header(mhoffs); printf("\nReady to update device. Type 'yes' to proceed, anything else to abort: "); fgets(line, sizeof(line), stdin); if (strcmp("yes\n", line)) return 0; printf("Updating MediaHeader...\n"); erase.start = mhoffs; erase.length = meminfo.erasesize; if (ioctl(fd, MEMERASE, &erase)) { perror("ioctl(MEMERASE)"); printf("Your MediaHeader may be hosed. UHOH!\n"); return 1; } oob.ptr = oobbuf; oob.start = mhoffs; for (i = 0; i < meminfo.erasesize; i += meminfo.oobblock) { memset(oob.ptr, 0xff, 6); // clear ECC. if (ioctl(fd, MEMWRITEOOB, &oob)) { perror("ioctl(MEMWRITEOOB)"); printf("Your MediaHeader may be hosed. UHOH!\n"); return 1; } if ((ret = pwrite(fd, buf, meminfo.oobblock, oob.start)) < 0) { perror("Write page"); printf("Your MediaHeader may be hosed. UHOH!\n"); return 1; } if (ret != meminfo.oobblock) { printf("Short write!\n"); printf("Your MediaHeader may be hosed. UHOH!\n"); return 1; } oob.start += meminfo.oobblock; oob.ptr += meminfo.oobsize; buf += meminfo.oobblock; } printf("Success. REBOOT or unload the diskonchip module to update partitions!\n"); return 0; }
static storage_status_t xml_load_real( irc_t *irc, const char *my_nick, const char *password, xml_pass_st action ) { GMarkupParseContext *ctx; struct xml_parsedata *xd; char *fn, buf[512]; GError *gerr = NULL; int fd, st; xd = g_new0( struct xml_parsedata, 1 ); xd->irc = irc; xd->given_nick = g_strdup( my_nick ); xd->given_pass = g_strdup( password ); xd->pass_st = action; nick_lc( xd->given_nick ); fn = g_strdup_printf( "%s%s%s", global.conf->configdir, xd->given_nick, ".xml" ); if( ( fd = open( fn, O_RDONLY ) ) < 0 ) { xml_destroy_xd( xd ); g_free( fn ); return STORAGE_NO_SUCH_USER; } g_free( fn ); ctx = g_markup_parse_context_new( &xml_parser, 0, xd, xml_destroy_xd ); while( ( st = read( fd, buf, sizeof( buf ) ) ) > 0 ) { if( !g_markup_parse_context_parse( ctx, buf, st, &gerr ) || gerr ) { xml_pass_st pass_st = xd->pass_st; g_markup_parse_context_free( ctx ); close( fd ); if( pass_st == XML_PASS_WRONG ) { g_clear_error( &gerr ); return STORAGE_INVALID_PASSWORD; } else { if( gerr && irc ) irc_rootmsg( irc, "Error from XML-parser: %s", gerr->message ); g_clear_error( &gerr ); return STORAGE_OTHER_ERROR; } } } /* Just to be sure... */ g_clear_error( &gerr ); g_markup_parse_context_free( ctx ); close( fd ); if( action == XML_PASS_CHECK_ONLY ) return STORAGE_OK; return STORAGE_OK; }
int main(int ac, char **av) { int rwfd; int i; int j; int c; off_t file_size = 1 * 1024 * 1024 * 1024; int first_stage = WRITE; struct io_oper *oper; int status = 0; int num_files = 0; int open_fds = 0; struct thread_info *t; page_size_mask = getpagesize() - 1; while (1) { c = getopt(ac, av, "a:b:c:C:m:s:r:d:i:I:o:t:lLnhOSxvu"); if (c < 0) break; switch (c) { case 'a': page_size_mask = parse_size(optarg, 1024); page_size_mask--; break; case 'c': num_contexts = atoi(optarg); break; case 'C': context_offset = parse_size(optarg, 1024 * 1024); case 'b': max_io_submit = atoi(optarg); break; case 's': file_size = parse_size(optarg, 1024 * 1024); break; case 'd': depth = atoi(optarg); break; case 'r': rec_len = parse_size(optarg, 1024); break; case 'i': io_iter = atoi(optarg); break; case 'I': iterations = atoi(optarg); break; case 'n': fsync_stages = 0; break; case 'l': latency_stats = 1; break; case 'L': completion_latency_stats = 1; break; case 'm': if (!strcmp(optarg, "shm")) { fprintf(stderr, "using ipc shm\n"); use_shm = USE_SHM; } else if (!strcmp(optarg, "shmfs")) { fprintf(stderr, "using /dev/shm for buffers\n"); use_shm = USE_SHMFS; } break; case 'o': i = atoi(optarg); stages |= 1 << i; fprintf(stderr, "adding stage %s\n", stage_name(i)); break; case 'O': o_direct = O_DIRECT; break; case 'S': o_sync = O_SYNC; break; case 't': num_threads = atoi(optarg); break; case 'x': stonewall = 0; break; case 'u': unlink_files = 1; break; case 'v': verify = 1; break; case 'h': default: print_usage(); exit(1); } } /* * make sure we don't try to submit more I/O than we have allocated * memory for */ if (depth < io_iter) { io_iter = depth; fprintf(stderr, "dropping io_iter to %d\n", io_iter); } if (optind >= ac) { print_usage(); exit(1); } num_files = ac - optind; if (num_threads > (num_files * num_contexts)) { num_threads = num_files * num_contexts; fprintf(stderr, "dropping thread count to the number of contexts %d\n", num_threads); } t = malloc(num_threads * sizeof(*t)); if (!t) { perror("malloc"); exit(1); } global_thread_info = t; /* by default, allow a huge number of iocbs to be sent towards * io_submit */ if (!max_io_submit) max_io_submit = num_files * io_iter * num_contexts; /* * make sure we don't try to submit more I/O than max_io_submit allows */ if (max_io_submit < io_iter) { io_iter = max_io_submit; fprintf(stderr, "dropping io_iter to %d\n", io_iter); } if (!stages) { stages = (1 << WRITE) | (1 << READ) | (1 << RREAD) | (1 << RWRITE); } else { for (i = 0; i < LAST_STAGE; i++) { if (stages & (1 << i)) { first_stage = i; fprintf(stderr, "starting with %s\n", stage_name(i)); break; } } } if (file_size < num_contexts * context_offset) { fprintf(stderr, "file size %ld too small for %d contexts\n", (long)file_size, num_contexts); exit(1); } fprintf(stderr, "file size %ldMB, record size %ldKB, depth %d, " "I/O per iteration %d\n", (long)(file_size / (1024 * 1024)), rec_len / 1024, depth, io_iter); fprintf(stderr, "max io_submit %d, buffer alignment set to %luKB\n", max_io_submit, (page_size_mask + 1) / 1024); fprintf(stderr, "threads %d files %d contexts %d context offset %ldMB " "verification %s\n", num_threads, num_files, num_contexts, (long)(context_offset / (1024 * 1024)), verify ? "on" : "off"); /* open all the files and do any required setup for them */ for (i = optind; i < ac; i++) { int thread_index; for (j = 0; j < num_contexts; j++) { thread_index = open_fds % num_threads; open_fds++; rwfd = open(av[i], O_CREAT | O_RDWR | o_direct | o_sync, 0600); if (rwfd == -1) { fprintf(stderr, "error while creating file %s: %s", av[i], strerror(errno)); exit(1); } oper = create_oper(rwfd, first_stage, j * context_offset, file_size - j * context_offset, rec_len, depth, io_iter, av[i]); if (!oper) { fprintf(stderr, "error in create_oper\n"); exit(-1); } oper_list_add(oper, &t[thread_index].active_opers); t[thread_index].num_files++; } } if (setup_shared_mem(num_threads, num_files * num_contexts, depth, rec_len, max_io_submit)) { exit(1); } for (i = 0; i < num_threads; i++) { if (setup_ious (&t[i], t[i].num_files, depth, rec_len, max_io_submit)) exit(1); } if (num_threads > 1) { printf("Running multi thread version num_threads:%d\n", num_threads); run_workers(t, num_threads); } else { printf("Running single thread version \n"); status = worker(t); } if (unlink_files) { for (i = optind; i < ac; i++) { printf("Cleaning up file %s \n", av[i]); unlink(av[i]); } } if (status) { exit(1); } return status; }
int main(void) { #ifndef TEST_BZIP2 return 77; #else const char *filedir = "dirfile"; const char *format = "dirfile/format"; const char *format1 = "dirfile/format1"; const char *data = "dirfile/data"; const char *bz2data = "dirfile/data.bz2"; const char *format_data = "/INCLUDE format1\ndata RAW UINT16 11\nENCODING bzip2\n"; const char *format1_data = "ENCODING none\n"; uint16_t data_data[128]; int fd, ret, error, ge_ret, unlink_data, unlink_bz2data, r = 0, i = 0; char command[4096]; gd_entry_t E; DIRFILE *D; uint16_t d; rmdirfile(); mkdir(filedir, 0777); for (fd = 0; fd < 128; ++fd) data_data[fd] = fd * 0x201; fd = open(format, O_CREAT | O_EXCL | O_WRONLY, 0666); write(fd, format_data, strlen(format_data)); close(fd); fd = open(format1, O_CREAT | O_EXCL | O_WRONLY, 0666); write(fd, format1_data, strlen(format1_data)); close(fd); fd = open(data, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, 0666); write(fd, data_data, 128 * sizeof(uint16_t)); close(fd); /* compress */ snprintf(command, 4096, "%s -f %s > /dev/null", BZIP2, data); if (gd_system(command)) return 1; #ifdef USE_BZIP2 D = gd_open(filedir, GD_RDWR | GD_VERBOSE | GD_UNENCODED); #else D = gd_open(filedir, GD_RDWR | GD_UNENCODED); #endif ret = gd_move(D, "data", 1, 1); error = gd_error(D); ge_ret = gd_entry(D, "data", &E); gd_close(D); #ifdef USE_BZIP2 fd = open(data, O_RDONLY | O_BINARY); if (fd >= 0) { while (read(fd, &d, sizeof(uint16_t))) { CHECKI(d, i * 0x201); i++; } close(fd); } else { perror("open"); r = 1; } #endif unlink(format1); unlink(format); unlink_data = unlink(data); unlink_bz2data = unlink(bz2data); rmdir(filedir); #ifdef USE_BZIP2 CHECKI(ret, 0); CHECKI(error, GD_E_OK); CHECKI(ge_ret, 0); CHECKI(E.fragment_index, 1); CHECKI(unlink_data, 0); CHECKI(unlink_bz2data, -1); #else CHECKI(ret, -1); CHECKI(error, GD_E_UNSUPPORTED); CHECKI(ge_ret, 0); CHECKI(E.fragment_index, 0); CHECKI(unlink_data, -1); CHECKI(unlink_bz2data, 0); #endif gd_free_entry_strings(&E); return r; #endif }
DIR * __opendir2(const char *name, int flags) { DIR *dirp = NULL; int fd; int serrno; struct stat sb; int incr; _DIAGASSERT(name != NULL); if ((fd = open(name, O_RDONLY | O_NONBLOCK, 0)) == -1 || fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) goto error; if (fstat(fd, &sb) || !S_ISDIR(sb.st_mode)) { errno = ENOTDIR; goto error; } if ((dirp = (DIR *)malloc(sizeof(DIR))) == NULL) goto error; dirp->dd_buf = NULL; /* * If the machine's page size is an exact multiple of DIRBLKSIZ, * use a buffer that is cluster boundary aligned. * Hopefully this can be a big win someday by allowing page trades * to user space to be done by getdirentries() */ incr = DIRBLKSIZ; dirp->dd_len = incr; dirp->dd_buf = malloc((size_t)dirp->dd_len); if (dirp->dd_buf == NULL) goto error; dirp->dd_seek = 0; flags &= ~DTF_REWIND; dirp->dd_loc = 0; dirp->dd_fd = fd; dirp->dd_flags = flags; /* * Set up seek point for rewinddir. */ #ifdef _REENTRANT if (__isthreaded) { if ((dirp->dd_lock = malloc(sizeof(mutex_t))) == NULL) goto error; mutex_init((mutex_t *)dirp->dd_lock, NULL); } #endif dirp->dd_internal = NULL; return (dirp); error: serrno = errno; if (dirp && dirp->dd_buf) free(dirp->dd_buf); if (dirp) free(dirp); if (fd != -1) (void)close(fd); errno = serrno; return NULL; }
static int tty_connect(struct scpi_instrument *scpi) { struct termios ti; char strbuf[250]; ssize_t status; scpi->ttyfd = open(scpi->tty_path, O_RDWR | O_NOCTTY); if (scpi->ttyfd < 0) { print_output_sys(stderr, "%s: Can't open serial port: %s %s (%d)\n", __func__, scpi->tty_path, strerror(errno), errno); return -1; } tcflush(scpi->ttyfd, TCIOFLUSH); if (tcgetattr(scpi->ttyfd, &ti) < 0) { print_output_sys(stderr, strbuf, "%s: Can't get port settings: %s (%d)\n", __func__, strerror(errno), errno); close(scpi->ttyfd); scpi->ttyfd = -1; return -1; } #ifdef TTY_RAW_MODE cfmakeraw(&ti); ti.c_cc[VMIN] = 1; ti.c_cc[VTIME] = 0; #else ti.c_cflag |= ICANON; #endif ti.c_cflag |= CLOCAL; ti.c_cflag &= ~CRTSCTS; ti.c_cflag &= ~PARENB; ti.c_cflag &= ~PARODD; ti.c_cflag &= ~CSIZE; ti.c_cflag |= CS8; ti.c_cflag &= ~CSTOPB; ti.c_oflag &= ~OPOST; ti.c_iflag = ti.c_lflag = 0; cfsetospeed(&ti, B19200); /* We don't need that for USB-GPIB */ if (tcsetattr(scpi->ttyfd, TCSANOW, &ti) < 0) { print_output_sys(stderr, strbuf, "%s: Can't change port settings: %s (%d)\n", __func__, strerror(errno), errno); close(scpi->ttyfd); scpi->ttyfd = -1; return -1; } tcflush(scpi->ttyfd, TCIOFLUSH); #ifdef TTY_RAW_MODE if (fcntl(scpi->ttyfd, F_SETFL, fcntl(scpi->ttyfd, F_GETFL, 0) | O_NONBLOCK) < 0) { print_output_sys(stderr, "%s: Can't set non blocking mode: %s (%d)\n", __func__, strerror(errno), errno); close(scpi->ttyfd); scpi->ttyfd = -1; return -1; } #endif print_output_sys(stdout, "%s: GPIB tty: connecting to %s\n", __func__, scpi->tty_path); /* set up controller and GPIB address */ sprintf(strbuf, "++mode 1\n"); status = write(scpi->ttyfd, strbuf, strlen(strbuf)); if (status < 0) return -1; sprintf(strbuf, "++addr %d\n", scpi->gpib_addr); status = write(scpi->ttyfd, strbuf, strlen(strbuf)); if (status < 0) return -1; sprintf(strbuf, "++auto 1\n"); status = write(scpi->ttyfd, strbuf, strlen(strbuf)); if (status < 0) return -1; return 0; }
static gboolean afprogram_popen(const gchar *cmdline, GIOCondition cond, pid_t *pid, gint *fd) { int msg_pipe[2]; g_return_val_if_fail(cond == G_IO_IN || cond == G_IO_OUT, FALSE); if (pipe(msg_pipe) == -1) { msg_error("Error creating program pipe", evt_tag_str("cmdline", cmdline), evt_tag_errno(EVT_TAG_OSERROR, errno), NULL); return FALSE; } if ((*pid = fork()) < 0) { msg_error("Error in fork()", evt_tag_errno(EVT_TAG_OSERROR, errno), NULL); close(msg_pipe[0]); close(msg_pipe[1]); return FALSE; } if (*pid == 0) { /* child */ int devnull = open("/dev/null", O_WRONLY); if (devnull == -1) { _exit(127); } if (cond == G_IO_IN) { dup2(msg_pipe[1], 1); dup2(devnull, 0); dup2(devnull, 2); } else { dup2(msg_pipe[0], 0); dup2(devnull, 1); dup2(devnull, 2); } close(devnull); close(msg_pipe[0]); close(msg_pipe[1]); execl("/bin/sh", "/bin/sh", "-c", cmdline, NULL); _exit(127); } if (cond == G_IO_IN) { *fd = msg_pipe[0]; close(msg_pipe[1]); } else { *fd = msg_pipe[1]; close(msg_pipe[0]); } return TRUE; }
int fillmesgwindow(int fd, Article *m) { Biobuf *b; char *p, tmp[40]; int i, inhdr, copy, xfd; Window *w; xfd = -1; if(fd == -1){ sprint(tmp, "%d/article", m->n); p = estrstrdup(dir, tmp); if((xfd = open(p, OREAD)) < 0){ free(p); return 0; } free(p); fd = xfd; } w = m->w; if(w->data < 0) w->data = winopenfile(w, "data"); if(winsetaddr(w, ",", 0)) write(w->data, "", 0); winopenbody(m->w, OWRITE); b = emalloc(sizeof(*b)); Binit(b, fd, OREAD); inhdr = 1; copy = 1; while(p = Brdline(b, '\n')){ if(Blinelen(b)==1) inhdr = 0, copy=1; if(inhdr && !isspace(p[0])){ copy = 1; if(!m->headers){ if(cistrncmp(p, "from:", 5)==0){ p[Blinelen(b)-1] = '\0'; p = fixfrom(skip(p, "from:")); Bprint(m->w->body, "From: %s\n", p); free(p); copy = 0; continue; } for(i=0; i<nelem(skipheader); i++) if(cistrncmp(p, skipheader[i], strlen(skipheader[i]))==0) copy=0; } } if(copy) Bwrite(m->w->body, p, Blinelen(b)); } Bterm(b); free(b); winclean(m->w); if(xfd != -1) close(xfd); return 1; }
char *entry_path(char *path, uint8_t *id, char *suffix) { size_t len = ID_LEN; encode64url((uint8_t *) path, id, &len, false); if (suffix) { memcpy(&path[len], suffix, strlen(suffix)); len += strlen(suffix); } path[len] = '\0'; return path; } bool update_db(idx *idx, uint8_t *kek, kdfp *kdfp, uint8_t *id, entry *entry, bool delete) { char path[PATH_MAX], work[PATH_MAX]; bool ok = false; int lock = open(".lock", O_CREAT | O_EXCL, 0600); if (lock != -1) { entry_path(path, id, NULL); entry_path(work, id, ".work"); if (delete) entry->count = 0; if (update_index("index.work", idx, kek, kdfp, id, entry)) { if (!delete) { ok = store_entry(work, idx->key, entry); ok = ok && !rename(work, path); } else { ok = !unlink(path); } ok = ok && !rename("index.work", "index"); }
int main(int argc, char **argv) { int fd = -1, c; int action = NOOP, rc = EXIT_FAILURE; char *path; struct stat sb; static const struct option longopts[] = { { "help", no_argument, NULL, 'h' }, { "freeze", no_argument, NULL, 'f' }, { "unfreeze", no_argument, NULL, 'u' }, { "version", no_argument, NULL, 'V' }, { NULL, 0, NULL, 0 } }; static const ul_excl_t excl[] = { /* rows and cols in ASCII order */ { 'f','u' }, /* freeze, unfreeze */ { 0 } }; int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT; setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); atexit(close_stdout); while ((c = getopt_long(argc, argv, "hfuV", longopts, NULL)) != -1) { err_exclusive_options(c, longopts, excl, excl_st); switch(c) { case 'h': usage(stdout); break; case 'f': action = FREEZE; break; case 'u': action = UNFREEZE; break; case 'V': printf(UTIL_LINUX_VERSION); exit(EXIT_SUCCESS); default: errtryhelp(EXIT_FAILURE); } } if (action == NOOP) errx(EXIT_FAILURE, _("neither --freeze or --unfreeze specified")); if (optind == argc) errx(EXIT_FAILURE, _("no filename specified")); path = argv[optind++]; if (optind != argc) { warnx(_("unexpected number of arguments")); usage(stderr); } fd = open(path, O_RDONLY); if (fd < 0) err(EXIT_FAILURE, _("cannot open %s"), path); if (fstat(fd, &sb) == -1) { warn(_("stat of %s failed"), path); goto done; } if (!S_ISDIR(sb.st_mode)) { warnx(_("%s: is not a directory"), path); goto done; } switch (action) { case FREEZE: if (ioctl(fd, FIFREEZE, 0)) { warn(_("%s: freeze failed"), path); goto done; } break; case UNFREEZE: if (ioctl(fd, FITHAW, 0)) { warn(_("%s: unfreeze failed"), path); goto done; } break; default: abort(); } rc = EXIT_SUCCESS; done: if (fd >= 0) close(fd); return rc; }