struct tracing_data *tracing_data_get(struct list_head *pattrs, int fd, bool temp) { struct tracepoint_path *tps; struct tracing_data *tdata; int err; output_fd = fd; tps = get_tracepoints_path(pattrs); if (!tps) return NULL; tdata = malloc(sizeof(*tdata)); if (!tdata) return NULL; tdata->temp = temp; tdata->size = 0; if (temp) { int temp_fd; snprintf(tdata->temp_file, sizeof(tdata->temp_file), "/tmp/perf-XXXXXX"); if (!mkstemp(tdata->temp_file)) { pr_debug("Can't make temp file"); return NULL; } temp_fd = open(tdata->temp_file, O_RDWR); if (temp_fd < 0) { pr_debug("Can't read '%s'", tdata->temp_file); return NULL; } /* * Set the temp file the default output, so all the * tracing data are stored into it. */ output_fd = temp_fd; } err = tracing_data_header(); if (err) goto out; err = record_header_files(); if (err) goto out; err = record_ftrace_files(tps); if (err) goto out; err = record_event_files(tps); if (err) goto out; err = record_proc_kallsyms(); if (err) goto out; err = record_ftrace_printk(); out: /* * All tracing data are stored by now, we can restore * the default output file in case we used temp file. */ if (temp) { tdata->size = lseek(output_fd, 0, SEEK_CUR); close(output_fd); output_fd = fd; } if (err) { free(tdata); tdata = NULL; } put_tracepoints_path(tps); return tdata; }
void TruncFile::seekBeg(long offset) { if(lseek(fd_, offset, SEEK_SET) == -1) LOG_SYSFATAL << "lseek error"; }
void TruncFile::seekEnd(long offset) { if(lseek(fd_, offset, SEEK_END) == -1) LOG_SYSFATAL << "lseek error"; }
/* * Write XLOG data to disk. */ static void XLogWalRcvWrite(char *buf, Size nbytes, XLogRecPtr recptr) { int startoff; int byteswritten; while (nbytes > 0) { int segbytes; if (recvFile < 0 || !XLByteInSeg(recptr, recvId, recvSeg)) { bool use_existent; /* * fsync() and close current file before we switch to next one. We * would otherwise have to reopen this file to fsync it later */ if (recvFile >= 0) { XLogWalRcvFlush(false); /* * XLOG segment files will be re-read by recovery in startup * process soon, so we don't advise the OS to release cache * pages associated with the file like XLogFileClose() does. */ if (close(recvFile) != 0) ereport(PANIC, (errcode_for_file_access(), errmsg("could not close log file %u, segment %u: %m", recvId, recvSeg))); } recvFile = -1; /* Create/use new log file */ XLByteToSeg(recptr, recvId, recvSeg); use_existent = true; recvFile = XLogFileInit(recvId, recvSeg, &use_existent, true); recvOff = 0; } /* Calculate the start offset of the received logs */ startoff = recptr.xrecoff % XLogSegSize; if (startoff + nbytes > XLogSegSize) segbytes = XLogSegSize - startoff; else segbytes = nbytes; /* Need to seek in the file? */ if (recvOff != startoff) { if (lseek(recvFile, (off_t) startoff, SEEK_SET) < 0) ereport(PANIC, (errcode_for_file_access(), errmsg("could not seek in log file %u, " "segment %u to offset %u: %m", recvId, recvSeg, startoff))); recvOff = startoff; } /* OK to write the logs */ errno = 0; byteswritten = write(recvFile, buf, segbytes); if (byteswritten <= 0) { /* if write didn't set errno, assume no disk space */ if (errno == 0) errno = ENOSPC; ereport(PANIC, (errcode_for_file_access(), errmsg("could not write to log file %u, segment %u " "at offset %u, length %lu: %m", recvId, recvSeg, recvOff, (unsigned long) segbytes))); } /* Update state for write */ XLByteAdvance(recptr, byteswritten); recvOff += byteswritten; nbytes -= byteswritten; buf += byteswritten; LogstreamResult.Write = recptr; } }
static int save_external_coredump( const char *context[_CONTEXT_MAX], int input_fd, char **ret_filename, int *ret_node_fd, int *ret_data_fd, uint64_t *ret_size, bool *ret_truncated) { _cleanup_free_ char *fn = NULL, *tmp = NULL; _cleanup_close_ int fd = -1; uint64_t rlimit, process_limit, max_size; struct stat st; uid_t uid; int r; assert(context); assert(ret_filename); assert(ret_node_fd); assert(ret_data_fd); assert(ret_size); r = parse_uid(context[CONTEXT_UID], &uid); if (r < 0) return log_error_errno(r, "Failed to parse UID: %m"); r = safe_atou64(context[CONTEXT_RLIMIT], &rlimit); if (r < 0) return log_error_errno(r, "Failed to parse resource limit '%s': %m", context[CONTEXT_RLIMIT]); if (rlimit < page_size()) { /* Is coredumping disabled? Then don't bother saving/processing the coredump. * Anything below PAGE_SIZE cannot give a readable coredump (the kernel uses * ELF_EXEC_PAGESIZE which is not easily accessible, but is usually the same as PAGE_SIZE. */ return log_info_errno(SYNTHETIC_ERRNO(EBADSLT), "Resource limits disable core dumping for process %s (%s).", context[CONTEXT_PID], context[CONTEXT_COMM]); } process_limit = MAX(arg_process_size_max, storage_size_max()); if (process_limit == 0) return log_debug_errno(SYNTHETIC_ERRNO(EBADSLT), "Limits for coredump processing and storage are both 0, not dumping core."); /* Never store more than the process configured, or than we actually shall keep or process */ max_size = MIN(rlimit, process_limit); r = make_filename(context, &fn); if (r < 0) return log_error_errno(r, "Failed to determine coredump file name: %m"); (void) mkdir_p_label("/var/lib/systemd/coredump", 0755); fd = open_tmpfile_linkable(fn, O_RDWR|O_CLOEXEC, &tmp); if (fd < 0) return log_error_errno(fd, "Failed to create temporary file for coredump %s: %m", fn); r = copy_bytes(input_fd, fd, max_size, 0); if (r < 0) { log_error_errno(r, "Cannot store coredump of %s (%s): %m", context[CONTEXT_PID], context[CONTEXT_COMM]); goto fail; } *ret_truncated = r == 1; if (*ret_truncated) log_struct(LOG_INFO, LOG_MESSAGE("Core file was truncated to %zu bytes.", max_size), "SIZE_LIMIT=%zu", max_size, "MESSAGE_ID=" SD_MESSAGE_TRUNCATED_CORE_STR); if (fstat(fd, &st) < 0) { log_error_errno(errno, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp)); goto fail; } if (lseek(fd, 0, SEEK_SET) == (off_t) -1) { log_error_errno(errno, "Failed to seek on %s: %m", coredump_tmpfile_name(tmp)); goto fail; } #if HAVE_XZ || HAVE_LZ4 /* If we will remove the coredump anyway, do not compress. */ if (arg_compress && !maybe_remove_external_coredump(NULL, st.st_size)) { _cleanup_free_ char *fn_compressed = NULL, *tmp_compressed = NULL; _cleanup_close_ int fd_compressed = -1; fn_compressed = strappend(fn, COMPRESSED_EXT); if (!fn_compressed) { log_oom(); goto uncompressed; } fd_compressed = open_tmpfile_linkable(fn_compressed, O_RDWR|O_CLOEXEC, &tmp_compressed); if (fd_compressed < 0) { log_error_errno(fd_compressed, "Failed to create temporary file for coredump %s: %m", fn_compressed); goto uncompressed; } r = compress_stream(fd, fd_compressed, -1); if (r < 0) { log_error_errno(r, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed)); goto fail_compressed; } r = fix_permissions(fd_compressed, tmp_compressed, fn_compressed, context, uid); if (r < 0) goto fail_compressed; /* OK, this worked, we can get rid of the uncompressed version now */ if (tmp) unlink_noerrno(tmp); *ret_filename = TAKE_PTR(fn_compressed); /* compressed */ *ret_node_fd = TAKE_FD(fd_compressed); /* compressed */ *ret_data_fd = TAKE_FD(fd); /* uncompressed */ *ret_size = (uint64_t) st.st_size; /* uncompressed */ return 0; fail_compressed: if (tmp_compressed) (void) unlink(tmp_compressed); } uncompressed: #endif r = fix_permissions(fd, tmp, fn, context, uid); if (r < 0) goto fail; *ret_filename = TAKE_PTR(fn); *ret_data_fd = TAKE_FD(fd); *ret_node_fd = -1; *ret_size = (uint64_t) st.st_size; return 0; fail: if (tmp) (void) unlink(tmp); return r; }
int main(int argc, char *argv[]) { int err = 0; int fd; off_t offset; char buf[4096]; fd = open("./XYZ", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR); if (fd < 0) { goto out; } close(fd); fd = open("./XYZ", O_RDWR, S_IRUSR | S_IWUSR); if (fd < 0) { goto out; } /* write 1B to offset 2047 */ offset = lseek(fd, 2047, SEEK_SET); if (offset < 0) { goto out_close; } memset(buf, '1', 4096); err = write(fd, buf, 1); if (err < 0) { perror("write 1"); goto out_close; } else { printf("written 1B '1' w/ %d\n", err); } /* write 2048B to offset 0 */ offset = lseek(fd, 0, SEEK_SET); if (offset < 0) { goto out_close; } memset(buf, '2', 4096); err = write(fd, buf, 2048); if (err < 0) { perror("write 1"); goto out_close; } else { printf("written 1B '1' w/ %d\n", err); } close(fd); fd = open("./XYZ", O_RDWR, S_IRUSR | S_IWUSR); if (fd < 0) { goto out; } /* read 4096B to offset 4096 */ offset = lseek(fd, 0, SEEK_SET); if (offset < 0) { goto out_close; } memset(buf, 0, 4096); err = read(fd, buf, 2048); if (err < 0) { perror("read 2"); goto out_close; } else { printf("read 2048B w/ %d\n", err); } assert(buf[1] == '2'); if (err != 2048) { printf("Cached read failed for this build!\n"); err = EFAULT; } close(fd); out_unlink: unlink("./XYZ"); out: return err; out_close: close(fd); goto out_unlink; }
static int seek(stream_t * s, off_t newpos) { //OS_PRINTF("[%s] stream_file---s->pos:0x%llx, newpos:0x%llx\n", __func__, s->pos, newpos); s64 pos_seek; if (mp_timeshift_size > 0) { newpos = MAX(newpos, 1024); } if(file_size>0&&fp_is_timeshift_file() == 0) newpos = MIN(file_size, newpos); s->pos = newpos; pos_seek = s->pos; if (fp_is_timeshift_file() == 1) { int seek_index = 0; u64 mp_timeshift_byte = ((u64)mp_timeshift_size) * 1024; if (newpos < mp_rec_bytes) { s->pos = newpos; } else { s->pos = mp_rec_bytes; } recv_bytes = s->pos; // seek_index = s->pos / mp_timeshift_byte + 1; if (seek_index != rec_index) { int ret = 0; rec_index = seek_index; ret = open_ts_file(s); if (ret != 0) { free(s->fd); s->fd = 0; } } recv_bytes_inter = s->pos % mp_timeshift_byte; pos_seek = recv_bytes_inter; //mtos_printk("\n%s %d %d\n", __func__, __LINE__, (int)pos_seek); // } //mtos_task_sleep(10); //mtos_printk("\n%s %d %d\n", __func__, __LINE__, (int)pos_seek); #ifdef __LINUX__ if (lseek(s->fd, s->pos, SEEK_SET) < 0) { s->eof = 1; return 0; } #else if (s->fd == 0) { s->eof = 1; return 0; } { //OS_PRINTF("start to seek---%d---------\n", s->pos); if (ufs_lseek_mode(s, pos_seek, 0) != FR_OK) { OS_PRINTF("seek fail %lld\n", s->pos); s->eof = 1; return 0; } } //OS_PRINTF("end to seek------------\n"); #endif return 1; }
/* * Just pass in an unused filename. */ void cmd_snap(void) { int c, fd, n; physaddr_t paddr; size_t offset; char *buf; char *filename; struct node_table *nt; int type; char *elf_header; Elf64_Phdr *load; int load_index; if (!supported) error(FATAL, "command not supported on the %s architecture\n", pc->machine_type); filename = NULL; buf = GETBUF(PAGESIZE()); type = KDUMP_ELF64; while ((c = getopt(argcnt, args, "n")) != EOF) { switch(c) { case 'n': if (machine_type("X86_64")) option_not_supported('n'); else type = NETDUMP_ELF64; break; default: argerrs++; break; } } if (argerrs || !args[optind]) cmd_usage(pc->curcmd, SYNOPSIS); while (args[optind]) { if (filename) cmd_usage(pc->curcmd, SYNOPSIS); if (file_exists(args[optind], NULL)) error(FATAL, "%s: file already exists\n", args[optind]); else if ((fd = open(args[optind], O_RDWR|O_CREAT, 0644)) < 0) error(FATAL, args[optind]); filename = args[optind]; optind++; } if (!filename) cmd_usage(pc->curcmd, SYNOPSIS); init_ram_segments(); if (!(elf_header = generate_elf_header(type, fd, filename))) error(FATAL, "cannot generate ELF header\n"); load = (Elf64_Phdr *)(elf_header + sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr)); load_index = machine_type("X86_64") || machine_type("IA64") ? 1 : 0; for (n = 0; n < vt->numnodes; n++) { nt = &vt->node_table[n]; paddr = nt->start_paddr; offset = load[load_index + n].p_offset; for (c = 0; c < nt->size; c++, paddr += PAGESIZE()) { if (!verify_paddr(paddr)) continue; if (!readmem(paddr, PHYSADDR, &buf[0], PAGESIZE(), "memory page", QUIET|RETURN_ON_ERROR)) continue; lseek(fd, (off_t)(paddr + offset - nt->start_paddr), SEEK_SET); if (write(fd, &buf[0], PAGESIZE()) != PAGESIZE()) error(FATAL, "write to dumpfile failed\n"); if (!print_progress(filename, BTOP(paddr))) return; } } fprintf(stderr, "\r%s: [100%%] ", filename); fprintf(fp, "\n"); sprintf(buf, "/bin/ls -l %s\n", filename); system(buf); FREEBUF(elf_header); FREEBUF(buf); }
int main () { int use_cloexec; int bad_fd = getdtablesize (); #if O_CLOEXEC for (use_cloexec = 0; use_cloexec <= 1; use_cloexec++) #else use_cloexec = 0; #endif { const char *file = "test-dup3.tmp"; int fd = open (file, O_CREAT | O_TRUNC | O_RDWR, 0600); int o_flags; char buffer[1]; o_flags = 0; #if O_CLOEXEC if (use_cloexec) o_flags |= O_CLOEXEC; #endif /* Assume std descriptors were provided by invoker. */ ASSERT (STDERR_FILENO < fd); ASSERT (is_open (fd)); /* Ignore any other fd's leaked into this process. */ close (fd + 1); close (fd + 2); ASSERT (!is_open (fd + 1)); ASSERT (!is_open (fd + 2)); /* Assigning to self is invalid. */ errno = 0; ASSERT (dup3 (fd, fd, o_flags) == -1); ASSERT (errno == EINVAL); ASSERT (is_open (fd)); /* If the source is not open, then the destination is unaffected. */ errno = 0; ASSERT (dup3 (fd + 1, fd + 2, o_flags) == -1); ASSERT (errno == EBADF); ASSERT (!is_open (fd + 2)); errno = 0; ASSERT (dup3 (fd + 1, fd, o_flags) == -1); ASSERT (errno == EBADF); ASSERT (is_open (fd)); /* The destination must be valid. */ errno = 0; ASSERT (dup3 (fd, -2, o_flags) == -1); ASSERT (errno == EBADF); if (bad_fd > 256) { ASSERT (dup3 (fd, 255, 0) == 255); ASSERT (dup3 (fd, 256, 0) == 256); ASSERT (close (255) == 0); ASSERT (close (256) == 0); } ASSERT (dup3 (fd, bad_fd - 1, 0) == bad_fd - 1); ASSERT (close (bad_fd - 1) == 0); errno = 0; ASSERT (dup3 (fd, bad_fd, o_flags) == -1); ASSERT (errno == EBADF); /* Using dup3 can skip fds. */ ASSERT (dup3 (fd, fd + 2, o_flags) == fd + 2); ASSERT (is_open (fd)); ASSERT (!is_open (fd + 1)); ASSERT (is_open (fd + 2)); if (use_cloexec) ASSERT (is_cloexec (fd + 2)); else ASSERT (!is_cloexec (fd + 2)); /* Verify that dup3 closes the previous occupant of a fd. */ ASSERT (open ("/dev/null", O_WRONLY, 0600) == fd + 1); ASSERT (dup3 (fd + 1, fd, o_flags) == fd); ASSERT (close (fd + 1) == 0); ASSERT (write (fd, "1", 1) == 1); ASSERT (dup3 (fd + 2, fd, o_flags) == fd); ASSERT (lseek (fd, 0, SEEK_END) == 0); ASSERT (write (fd + 2, "2", 1) == 1); ASSERT (lseek (fd, 0, SEEK_SET) == 0); ASSERT (read (fd, buffer, 1) == 1); ASSERT (*buffer == '2'); /* Clean up. */ ASSERT (close (fd + 2) == 0); ASSERT (close (fd) == 0); ASSERT (unlink (file) == 0); } return 0; }
/* * newModule - handle a new module */ static void newModule( HANDLE hmod, char *name, samp_block_kinds kind ) { GLOBALENTRY ge; os2_exe_header ne; dos_exe_header de; seg_offset ovl; int i; LPVOID ptr; WORD sel; int handle; int numsegs; WORD win32ds; WORD win32cs; DWORD win32initialeip; int rc; ovl.offset = 0; ovl.segment = 0; rc = CheckIsModuleWin32App( hmod, &win32ds, &win32cs, &win32initialeip ); if( rc ) { if( win32ds != 0 ) { WriteCodeLoad( ovl, name, kind ); WriteAddrMap( 1, win32cs, win32initialeip ); WriteAddrMap( 2, win32ds, 0 ); } else if( kind == SAMP_MAIN_LOAD ) { FlagWin32AppAsDebugged( hmod ); WaitForInt3 = GetCurrentTask(); } else if( WaitForInt1 == 0 ) { FlagWin32AppAsDebugged( hmod ); WaitForInt1 = hmod; } return; } WriteCodeLoad( ovl, name, kind ); handle = open( name,O_BINARY | O_RDONLY ); if( handle >= 0 ) { read( handle, &de, sizeof( de ) ); if( de.signature == DOS_SIGNATURE ) { lseek( handle, (de.file_size-1L)*512L+(long)de.mod_size, SEEK_SET ); } else { lseek( handle, 0, SEEK_SET ); } read( handle, &ne, sizeof( ne ) ); if( ne.signature == OS2_SIGNATURE_WORD ) { numsegs = ne.segments; if( numsegs > 8192 ) { // must not really be a valid OS2 sig. numsegs = -1; } } else { numsegs = -1; } close( handle ); } for( i=1; i<8192; i++ ) { if( !MyGlobalEntryModule( &ge, hmod, i ) ) { if( numsegs > 0 ) { sel = horkyFindSegment( hmod, i ); if( sel == 0 ) continue; } else { continue; } } else { if( ge.hBlock != NULL ) { ptr = GlobalLock( ge.hBlock ); GlobalUnlock( ge.hBlock ); sel = FP_SEG( ptr ); if( sel == NULL ) { sel = (WORD)ge.hBlock + 1; } } else { continue; } } WriteAddrMap( i, sel, 0 ); numsegs--; if( numsegs == 0 ) { break; } } } /* newModule */
int main (void) { const char *tmpdir; char *fname; int fd; FILE *fp; const char outstr[] = "hello world!\n"; char strbuf[sizeof outstr]; char buf[200]; struct stat64 st1; struct stat64 st2; int result = 0; tmpdir = getenv ("TMPDIR"); if (tmpdir == NULL || tmpdir[0] == '\0') tmpdir = "/tmp"; asprintf (&fname, "%s/tst-fseek.XXXXXX", tmpdir); if (fname == NULL) error (EXIT_FAILURE, errno, "cannot generate name for temporary file"); /* Create a temporary file. */ fd = mkstemp (fname); if (fd == -1) error (EXIT_FAILURE, errno, "cannot open temporary file"); fp = fdopen (fd, "w+"); if (fp == NULL) error (EXIT_FAILURE, errno, "cannot get FILE for temporary file"); setbuffer (fp, strbuf, sizeof (outstr) -1); if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: write error\n", __LINE__); result = 1; goto out; } /* The EOF flag must be reset. */ if (fgetc (fp) != EOF) { printf ("%d: managed to read at end of file\n", __LINE__); result = 1; } else if (! feof (fp)) { printf ("%d: EOF flag not set\n", __LINE__); result = 1; } if (fseek (fp, 0, SEEK_CUR) != 0) { printf ("%d: fseek(fp, 0, SEEK_CUR) failed\n", __LINE__); result = 1; } else if (feof (fp)) { printf ("%d: fseek() didn't reset EOF flag\n", __LINE__); result = 1; } /* Do the same for fseeko(). */ if (fgetc (fp) != EOF) { printf ("%d: managed to read at end of file\n", __LINE__); result = 1; } else if (! feof (fp)) { printf ("%d: EOF flag not set\n", __LINE__); result = 1; } if (fseeko (fp, 0, SEEK_CUR) != 0) { printf ("%d: fseek(fp, 0, SEEK_CUR) failed\n", __LINE__); result = 1; } else if (feof (fp)) { printf ("%d: fseek() didn't reset EOF flag\n", __LINE__); result = 1; } /* Go back to the beginning of the file: absolute. */ if (fseek (fp, 0, SEEK_SET) != 0) { printf ("%d: fseek(fp, 0, SEEK_SET) failed\n", __LINE__); result = 1; } else if (fflush (fp) != 0) { printf ("%d: fflush() failed\n", __LINE__); result = 1; } else if (lseek (fd, 0, SEEK_CUR) != 0) { printf ("%d: lseek() returned different position\n", __LINE__); result = 1; } else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: fread() failed\n", __LINE__); result = 1; } else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0) { printf ("%d: content after fseek(,,SEEK_SET) wrong\n", __LINE__); result = 1; } /* Now with fseeko. */ if (fseeko (fp, 0, SEEK_SET) != 0) { printf ("%d: fseeko(fp, 0, SEEK_SET) failed\n", __LINE__); result = 1; } else if (fflush (fp) != 0) { printf ("%d: fflush() failed\n", __LINE__); result = 1; } else if (lseek (fd, 0, SEEK_CUR) != 0) { printf ("%d: lseek() returned different position\n", __LINE__); result = 1; } else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: fread() failed\n", __LINE__); result = 1; } else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0) { printf ("%d: content after fseeko(,,SEEK_SET) wrong\n", __LINE__); result = 1; } /* Go back to the beginning of the file: relative. */ if (fseek (fp, -((int) sizeof (outstr) - 1), SEEK_CUR) != 0) { printf ("%d: fseek(fp, 0, SEEK_SET) failed\n", __LINE__); result = 1; } else if (fflush (fp) != 0) { printf ("%d: fflush() failed\n", __LINE__); result = 1; } else if (lseek (fd, 0, SEEK_CUR) != 0) { printf ("%d: lseek() returned different position\n", __LINE__); result = 1; } else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: fread() failed\n", __LINE__); result = 1; } else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0) { printf ("%d: content after fseek(,,SEEK_SET) wrong\n", __LINE__); result = 1; } /* Now with fseeko. */ if (fseeko (fp, -((int) sizeof (outstr) - 1), SEEK_CUR) != 0) { printf ("%d: fseeko(fp, 0, SEEK_SET) failed\n", __LINE__); result = 1; } else if (fflush (fp) != 0) { printf ("%d: fflush() failed\n", __LINE__); result = 1; } else if (lseek (fd, 0, SEEK_CUR) != 0) { printf ("%d: lseek() returned different position\n", __LINE__); result = 1; } else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: fread() failed\n", __LINE__); result = 1; } else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0) { printf ("%d: content after fseeko(,,SEEK_SET) wrong\n", __LINE__); result = 1; } /* Go back to the beginning of the file: from the end. */ if (fseek (fp, -((int) sizeof (outstr) - 1), SEEK_END) != 0) { printf ("%d: fseek(fp, 0, SEEK_SET) failed\n", __LINE__); result = 1; } else if (fflush (fp) != 0) { printf ("%d: fflush() failed\n", __LINE__); result = 1; } else if (lseek (fd, 0, SEEK_CUR) != 0) { printf ("%d: lseek() returned different position\n", __LINE__); result = 1; } else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: fread() failed\n", __LINE__); result = 1; } else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0) { printf ("%d: content after fseek(,,SEEK_SET) wrong\n", __LINE__); result = 1; } /* Now with fseeko. */ if (fseeko (fp, -((int) sizeof (outstr) - 1), SEEK_END) != 0) { printf ("%d: fseeko(fp, 0, SEEK_SET) failed\n", __LINE__); result = 1; } else if (fflush (fp) != 0) { printf ("%d: fflush() failed\n", __LINE__); result = 1; } else if (lseek (fd, 0, SEEK_CUR) != 0) { printf ("%d: lseek() returned different position\n", __LINE__); result = 1; } else if (fread (buf, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: fread() failed\n", __LINE__); result = 1; } else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0) { printf ("%d: content after fseeko(,,SEEK_SET) wrong\n", __LINE__); result = 1; } if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: write error 2\n", __LINE__); result = 1; goto out; } if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: write error 3\n", __LINE__); result = 1; goto out; } if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: write error 4\n", __LINE__); result = 1; goto out; } if (fwrite (outstr, sizeof (outstr) - 1, 1, fp) != 1) { printf ("%d: write error 5\n", __LINE__); result = 1; goto out; } if (fputc ('1', fp) == EOF || fputc ('2', fp) == EOF) { printf ("%d: cannot add characters at the end\n", __LINE__); result = 1; goto out; } /* Check the access time. */ if (fstat64 (fd, &st1) < 0) { printf ("%d: fstat64() before fseeko() failed\n\n", __LINE__); result = 1; } else { sleep (1); if (fseek (fp, -(2 + 2 * (sizeof (outstr) - 1)), SEEK_CUR) != 0) { printf ("%d: fseek() after write characters failed\n", __LINE__); result = 1; goto out; } else { time_t t; /* Make sure the timestamp actually can be different. */ sleep (1); t = time (NULL); if (fstat64 (fd, &st2) < 0) { printf ("%d: fstat64() after fseeko() failed\n\n", __LINE__); result = 1; } if (st1.st_ctime >= t) { printf ("%d: st_ctime not updated\n", __LINE__); result = 1; } if (st1.st_mtime >= t) { printf ("%d: st_mtime not updated\n", __LINE__); result = 1; } if (st1.st_ctime >= st2.st_ctime) { printf ("%d: st_ctime not changed\n", __LINE__); result = 1; } if (st1.st_mtime >= st2.st_mtime) { printf ("%d: st_mtime not changed\n", __LINE__); result = 1; } } } if (fread (buf, 1, 2 + 2 * (sizeof (outstr) - 1), fp) != 2 + 2 * (sizeof (outstr) - 1)) { printf ("%d: reading 2 records plus bits failed\n", __LINE__); result = 1; } else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0 || memcmp (&buf[sizeof (outstr) - 1], outstr, sizeof (outstr) - 1) != 0 || buf[2 * (sizeof (outstr) - 1)] != '1' || buf[2 * (sizeof (outstr) - 1) + 1] != '2') { printf ("%d: reading records failed\n", __LINE__); result = 1; } else if (ungetc ('9', fp) == EOF) { printf ("%d: ungetc() failed\n", __LINE__); result = 1; } else if (fseek (fp, -(2 + 2 * (sizeof (outstr) - 1)), SEEK_END) != 0) { printf ("%d: fseek after ungetc failed\n", __LINE__); result = 1; } else if (fread (buf, 1, 2 + 2 * (sizeof (outstr) - 1), fp) != 2 + 2 * (sizeof (outstr) - 1)) { printf ("%d: reading 2 records plus bits failed\n", __LINE__); result = 1; } else if (memcmp (buf, outstr, sizeof (outstr) - 1) != 0 || memcmp (&buf[sizeof (outstr) - 1], outstr, sizeof (outstr) - 1) != 0 || buf[2 * (sizeof (outstr) - 1)] != '1') { printf ("%d: reading records for the second time failed\n", __LINE__); result = 1; } else if (buf[2 * (sizeof (outstr) - 1) + 1] == '9') { printf ("%d: unget character not ignored\n", __LINE__); result = 1; } else if (buf[2 * (sizeof (outstr) - 1) + 1] != '2') { printf ("%d: unget somehow changed character\n", __LINE__); result = 1; } fclose (fp); fp = fopen (fname, "r"); if (fp == NULL) { printf ("%d: fopen() failed\n\n", __LINE__); result = 1; } else if (fstat64 (fileno (fp), &st1) < 0) { printf ("%d: fstat64() before fseeko() failed\n\n", __LINE__); result = 1; } else if (fseeko (fp, 0, SEEK_END) != 0) { printf ("%d: fseeko(fp, 0, SEEK_END) failed\n", __LINE__); result = 1; } else if (ftello (fp) != st1.st_size) { printf ("%d: fstat64 st_size %zd ftello %zd\n", __LINE__, (size_t) st1.st_size, (size_t) ftello (fp)); result = 1; } else printf ("%d: SEEK_END works\n", __LINE__); if (fp != NULL) fclose (fp); fp = fopen (fname, "r"); if (fp == NULL) { printf ("%d: fopen() failed\n\n", __LINE__); result = 1; } else if (fstat64 (fileno (fp), &st1) < 0) { printf ("%d: fstat64() before fgetc() failed\n\n", __LINE__); result = 1; } else if (fgetc (fp) == EOF) { printf ("%d: fgetc() before fseeko() failed\n\n", __LINE__); result = 1; } else if (fseeko (fp, 0, SEEK_END) != 0) { printf ("%d: fseeko(fp, 0, SEEK_END) failed\n", __LINE__); result = 1; } else if (ftello (fp) != st1.st_size) { printf ("%d: fstat64 st_size %zd ftello %zd\n", __LINE__, (size_t) st1.st_size, (size_t) ftello (fp)); result = 1; } else printf ("%d: SEEK_END works\n", __LINE__); if (fp != NULL) fclose (fp); out: unlink (fname); return result; }
static unsigned long long store_flat_data_array(char *file, struct flat_data **fda) { int result = FALSE, fd; int64_t offset_fdh; unsigned long long num_allocated = 0; unsigned long long num_stored = 0; unsigned long long size_allocated; struct flat_data *ptr = NULL, *cur; struct makedumpfile_data_header fdh; fd = open(file, O_RDONLY); if (fd < 0) { error(INFO, "unable to open dump file %s", file); return -1; } if (lseek(fd, MAX_SIZE_MDF_HEADER, SEEK_SET) < 0) { error(INFO, "unable to seek dump file %s", file); close(fd); return -1; } while (1) { if (num_allocated <= num_stored) { num_allocated += 100; size_allocated = sizeof(struct flat_data) * num_allocated; ptr = realloc(ptr, size_allocated); if (ptr == NULL) { error(INFO, "unable to allocate"); break; } } offset_fdh = lseek(fd, 0x0, SEEK_CUR); if (read(fd, &fdh, sizeof(fdh)) < 0) { error(INFO, "unable to read dump file %s", file); break; } if (!is_bigendian()){ fdh.offset = bswap_64(fdh.offset); fdh.buf_size = bswap_64(fdh.buf_size); } if (fdh.offset == END_FLAG_FLAT_HEADER) { result = TRUE; break; } cur = ptr + num_stored; cur->off_flattened = offset_fdh + sizeof(fdh); cur->off_rearranged = fdh.offset; cur->buf_size = fdh.buf_size; num_stored++; /* seek for next makedumpfile_data_header. */ if (lseek(fd, fdh.buf_size, SEEK_CUR) < 0) { error(INFO, "unable to seek dump file %s", file); break; } } close(fd); if (result == FALSE) { free(ptr); return -1; } *fda = ptr; return num_stored; }
int io_shuffle(request * req) { int bytes_to_read; int bytes_written, bytes_to_write; if (req->method == M_HEAD) { return complete_response(req); } /* FIXME: This function doesn't take into account req->filesize * when *reading* into the buffer. Grr. * June 09, 2004: jdn, I don't think it's a problem anymore, * because the ranges are verified against the filesize, * and we cap bytes_to_read at bytes_to_write. */ bytes_to_read = BUFFER_SIZE - req->buffer_end - 256; bytes_to_write = (req->ranges->stop - req->ranges->start) + 1; if (bytes_to_read > bytes_to_write) bytes_to_read = bytes_to_write; if (bytes_to_read > 0 && req->data_fd) { int bytes_read; off_t temp; temp = lseek(req->data_fd, req->ranges->start, SEEK_SET); if (temp < 0) { req->status = DEAD; log_error_doc(req); perror("ioshuffle lseek"); return 0; } restartread: bytes_read = read(req->data_fd, req->buffer + req->buffer_end, bytes_to_read); if (bytes_read == -1) { if (errno == EINTR) goto restartread; else if (errno == EWOULDBLOCK || errno == EAGAIN) { /* not a fatal error, don't worry about it */ /* buffer is empty, we're blocking on read! */ if (req->buffer_end - req->buffer_start == 0) return -1; } else { req->status = DEAD; log_error_doc(req); perror("ioshuffle read"); return 0; } } else if (bytes_read == 0) { /* eof, write rest of buffer */ close(req->data_fd); req->data_fd = 0; } else { req->buffer_end += bytes_read; req->ranges->start += bytes_read; if ((req->ranges->stop + 1 - req->ranges->start) == 0) { return complete_response(req); } } } bytes_to_write = req->buffer_end - req->buffer_start; if (bytes_to_write == 0) { if (req->data_fd == 0) return 0; /* done */ req->buffer_end = req->buffer_start = 0; return 1; } restartwrite: bytes_written = write(req->fd, req->buffer + req->buffer_start, bytes_to_write); if (bytes_written == -1) { if (errno == EWOULDBLOCK || errno == EAGAIN) return -1; /* request blocked at the pipe level, but keep going */ else if (errno == EINTR) goto restartwrite; else { req->status = DEAD; log_error_doc(req); perror("ioshuffle write"); return 0; } } else if (bytes_written == 0) { } req->buffer_start += bytes_written; req->bytes_written += bytes_written; if (bytes_to_write == bytes_written) { req->buffer_end = req->buffer_start = 0; } return 1; }
int main ( int argc , char ** argv ) { if( argc != 2 ) { print_usage(); return 0; } fprintf( stderr , "This program wil format the %s file, continue? y/n : ", argv[1]); char in; in = getchar(); if( 'y' != in && 'Y' != in ) { fprintf( stderr , "format cancelled!\n"); return 0; } int fd; if( (fd = open( argv[1] , O_WRONLY )) < 0 ) { fprintf( stderr , "Error on open():%s\n", strerror( errno ) ); return 1; } struct sb tSuperBlock; //good habit is to memset memset( &tSuperBlock , 0 , sizeof( struct sb ) ); tSuperBlock.fs_size = (long)get_file_size( argv[1] ) / BLOCK_SIZE; tSuperBlock.us_size = 1 + SUPER_BLOCK_N + BITMAP_BLOCK_N ; //because the superblock and bitmapblock and root alread occupy some blocks tSuperBlock.bk_size = BLOCK_SIZE; tSuperBlock.first_blk = BLOCK_SIZE * ( SUPER_BLOCK_N + BITMAP_BLOCK_N ); tSuperBlock.bitmap = BITMAP_BLOCK_N; printf("Disk image file:%s\n" , argv[1] ); printf("Ready to Write :\n"); printf("fs_size(in blocks) : %ld\n", tSuperBlock.fs_size ); printf("us_size(in blocks) : %ld\n", tSuperBlock.us_size ); printf("bk_size(in bytes ) : %ld\n", tSuperBlock.bk_size ); printf("first_blk(location) : %ld\n", tSuperBlock.first_blk ); printf("bitmap(in blocks) : %ld\n\n", tSuperBlock.bitmap ); //diskimage too small no way to do if( tSuperBlock.fs_size < (SUPER_BLOCK_N + BITMAP_BLOCK_N + 1 ) ) { fprintf( stderr , "Diskimage file too small! Can't format, sorry!\n"); exit(1); } //write super block lseek( fd , (off_t) 0 , SEEK_SET ); ssize_t wc; struct u_fs_disk_block block; memset( &block , 0 , sizeof( struct u_fs_disk_block ) ); memcpy( &block , &tSuperBlock , sizeof( struct sb ) ); wc = write( fd , (void *) &block , sizeof( struct u_fs_disk_block )); if( wc != sizeof( struct u_fs_disk_block )) { fprintf( stderr , "Error on write():%s\n",strerror(errno)); exit(1); //it will help me to close file ? } //super block done //write bitmap block lseek( fd , (off_t) (SUPER_BLOCK_N * BLOCK_SIZE) , SEEK_SET ); char buffer[BLOCK_SIZE]; (void *) memset((void *) buffer , 0 , BLOCK_SIZE); int count; for( count=0; count < tSuperBlock.bitmap ; count++ ) { wc = write( fd , (void *)buffer , BLOCK_SIZE); if( wc != BLOCK_SIZE ) { fprintf( stderr , "Error on write():%s\n",strerror(errno)); exit(1); //it will help me to close file ? } } //the first block is occupy by the root dir lseek( fd , SUPER_BLOCK_N * BLOCK_SIZE , SEEK_SET ); unsigned char oc = 0x80; write( fd , (void *)&oc , sizeof( oc )); //bitmap block done //write data block. no much to do. clear the root block struct u_fs_disk_block root; memset( &root , 0 , sizeof( root )); root.size=0; root.nNextBlock=0; lseek( fd , tSuperBlock.first_blk , SEEK_SET ); write( fd , (void*)&root , sizeof( root)); (void) close(fd); //read and comfirm if( (fd = open( argv[1] , O_RDONLY )) < 0 ) { fprintf( stderr , "Error on open():%s\n", strerror( errno ) ); return 1; } struct sb uSuperBlock; struct u_fs_disk_block ablock; read( fd , (void *)&ablock , sizeof( struct u_fs_disk_block ) ); memcpy( &uSuperBlock , &ablock , sizeof( struct sb ) ); printf("Disk image file:%s\n" , argv[1] ); printf("After Writing :\n"); printf("fs_size(in blocks) : %ld\n", tSuperBlock.fs_size ); printf("us_size(in blocks) : %ld\n", tSuperBlock.us_size ); printf("bk_size(in bytes ) : %ld\n", tSuperBlock.bk_size ); printf("first_blk(location) : %ld\n", tSuperBlock.first_blk ); printf("bitmap(in blocks) : %ld\n\n", tSuperBlock.bitmap ); if( 0 == memcmp( (void*)&tSuperBlock , (void*)&uSuperBlock , sizeof( struct sb) )) { printf("Check....OK. Format Complete!\n"); } else { fprintf( stderr , "Check....FAILED. Format Failed!\n"); } ( void ) close( fd ); return 0; }
int mtd_write_buffer(int fd, const char *buf, int offset, int length) { lseek(fd, offset, SEEK_SET); write(fd, buf, length); return 0; }
int freadseek (FILE *fp, size_t offset) { size_t total_buffered; int fd; if (offset == 0) return 0; /* Seek over the already read and buffered input as quickly as possible, without doing any system calls. */ total_buffered = freadahead (fp); /* This loop is usually executed at most twice: once for ungetc buffer (if present) and once for the main buffer. */ while (total_buffered > 0) { size_t buffered; if (freadptr (fp, &buffered) != NULL && buffered > 0) { size_t increment = (buffered < offset ? buffered : offset); freadptrinc (fp, increment); offset -= increment; if (offset == 0) return 0; total_buffered -= increment; if (total_buffered == 0) break; } /* Read one byte. If we were reading from the ungetc buffer, this switches the stream back to the main buffer. */ if (fgetc (fp) == EOF) goto eof; offset--; if (offset == 0) return 0; total_buffered--; } /* Test whether the stream is seekable or not. */ fd = fileno (fp); if (fd >= 0 && lseek (fd, 0, SEEK_CUR) >= 0) { /* FP refers to a regular file. fseek is most efficient in this case. */ return fseeko (fp, offset, SEEK_CUR); } else { /* FP is a non-seekable stream, possibly not even referring to a file descriptor. Read OFFSET bytes explicitly and discard them. */ char buf[4096]; do { size_t count = (sizeof (buf) < offset ? sizeof (buf) : offset); if (fread (buf, 1, count, fp) < count) goto eof; offset -= count; } while (offset > 0); return 0; } eof: /* EOF, or error before or while reading. */ if (ferror (fp)) return EOF; else /* Encountered EOF. */ return 0; }
static int mtd_write(int imagefd, const char *mtd, char *fis_layout, size_t part_offset) { char *next = NULL; char *str = NULL; int fd, result; ssize_t r, w, e; ssize_t skip = 0; uint32_t offset = 0; int jffs2_replaced = 0; int skip_bad_blocks = 0; #ifdef FIS_SUPPORT static struct fis_part new_parts[MAX_ARGS]; static struct fis_part old_parts[MAX_ARGS]; int n_new = 0, n_old = 0; if (fis_layout) { const char *tmp = mtd; char *word, *brkt; int ret; memset(&old_parts, 0, sizeof(old_parts)); memset(&new_parts, 0, sizeof(new_parts)); do { next = strchr(tmp, ':'); if (!next) next = (char *) tmp + strlen(tmp); memcpy(old_parts[n_old].name, tmp, next - tmp); n_old++; tmp = next + 1; } while(*next); for (word = strtok_r(fis_layout, ",", &brkt); word; word = strtok_r(NULL, ",", &brkt)) { tmp = strtok(word, ":"); strncpy((char *) new_parts[n_new].name, tmp, sizeof(new_parts[n_new].name) - 1); tmp = strtok(NULL, ":"); if (!tmp) goto next; new_parts[n_new].size = strtoul(tmp, NULL, 0); tmp = strtok(NULL, ":"); if (!tmp) goto next; new_parts[n_new].loadaddr = strtoul(tmp, NULL, 16); next: n_new++; } ret = fis_validate(old_parts, n_old, new_parts, n_new); if (ret < 0) { fprintf(stderr, "Failed to validate the new FIS partition table\n"); exit(1); } if (ret == 0) fis_layout = NULL; } #endif if (strchr(mtd, ':')) { str = strdup(mtd); mtd = str; } r = 0; resume: next = strchr(mtd, ':'); if (next) { *next = 0; next++; } fd = mtd_check_open(mtd); if(fd < 0) { fprintf(stderr, "Could not open mtd device: %s\n", mtd); exit(1); } if (part_offset > 0) { fprintf(stderr, "Seeking on mtd device '%s' to: %zu\n", mtd, part_offset); lseek(fd, part_offset, SEEK_SET); } indicate_writing(mtd); w = e = 0; for (;;) { /* buffer may contain data already (from trx check or last mtd partition write attempt) */ while (buflen < erasesize) { r = read(imagefd, buf + buflen, erasesize - buflen); if (r < 0) { if ((errno == EINTR) || (errno == EAGAIN)) continue; else { perror("read"); break; } } if (r == 0) break; buflen += r; } if (buflen == 0) break; if (buflen < erasesize) { /* Pad block to eraseblock size */ memset(&buf[buflen], 0xff, erasesize - buflen); buflen = erasesize; } if (skip > 0) { skip -= buflen; buflen = 0; if (skip <= 0) indicate_writing(mtd); continue; } if (jffs2file && w >= jffs2_skip_bytes) { if (memcmp(buf, JFFS2_EOF, sizeof(JFFS2_EOF) - 1) == 0) { if (!quiet) fprintf(stderr, "\b\b\b "); if (quiet < 2) fprintf(stderr, "\nAppending jffs2 data from %s to %s..\n.", jffs2file, mtd); /* got an EOF marker - this is the place to add some jffs2 data */ skip = mtd_replace_jffs2(mtd, fd, e, jffs2file); jffs2_replaced = 1; /* don't add it again */ jffs2file = NULL; w += skip; e += skip; skip -= buflen; buflen = 0; offset = 0; continue; } /* no EOF marker, make sure we figure out the last inode number * before appending some data */ mtd_parse_jffs2data(buf, jffs2dir); } /* need to erase the next block before writing data to it */ if(!no_erase) { while (w + buflen > e - skip_bad_blocks) { if (!quiet) fprintf(stderr, "\b\b\b[e]"); if (mtd_block_is_bad(fd, e)) { if (!quiet) fprintf(stderr, "\nSkipping bad block at 0x%08zx ", e); skip_bad_blocks += erasesize; e += erasesize; // Move the file pointer along over the bad block. lseek(fd, erasesize, SEEK_CUR); continue; } if (mtd_erase_block(fd, e) < 0) { if (next) { if (w < e) { write(fd, buf + offset, e - w); offset = e - w; } w = 0; e = 0; close(fd); mtd = next; fprintf(stderr, "\b\b\b \n"); goto resume; } else { fprintf(stderr, "Failed to erase block\n"); exit(1); } } /* erase the chunk */ e += erasesize; } } if (!quiet) fprintf(stderr, "\b\b\b[w]"); if ((result = write(fd, buf + offset, buflen)) < buflen) { if (result < 0) { fprintf(stderr, "Error writing image.\n"); exit(1); } else { fprintf(stderr, "Insufficient space.\n"); exit(1); } } w += buflen; buflen = 0; offset = 0; } if (jffs2_replaced) { switch (imageformat) { case MTD_IMAGE_FORMAT_TRX: if (trx_fixup) trx_fixup(fd, mtd); break; case MTD_IMAGE_FORMAT_SEAMA: if (mtd_fixseama) mtd_fixseama(mtd, 0, 0); break; case MTD_IMAGE_FORMAT_WRG: if (mtd_fixwrg) mtd_fixwrg(mtd, 0, 0); break; case MTD_IMAGE_FORMAT_WRGG03: if (mtd_fixwrgg) mtd_fixwrgg(mtd, 0, 0); break; default: break; } } if (!quiet) fprintf(stderr, "\b\b\b\b "); if (quiet < 2) fprintf(stderr, "\n"); #ifdef FIS_SUPPORT if (fis_layout) { if (fis_remap(old_parts, n_old, new_parts, n_new) < 0) fprintf(stderr, "Failed to update the FIS partition table\n"); } #endif close(fd); return 0; }
/*********************************************************************** * new_region_list - initialize a new region_list * * * * Given a pid, new_region_list crawls through /proc/<pid>/maps and * * produces a linked list called region_list which contains the * * addresses for all the memory regions in the pid's address space. * * * * The flag RL_FLAG_ANON specifies whether it should include all the * * segments it can read in this list or just the interesting ones. * ***********************************************************************/ struct region_list * new_region_list(pid_t pid, int flags) { /* Variables */ char * path = NULL; int maps_fd = -1; int maps_len; char * maps = NULL; int i = 0; off_t offset = 0; char i_hate_proc; struct region_list * head; struct region_list * cur; char * tok/*en_of_my_appreciation*/; int chk; /* Initialize */ path = calloc(1, 25); err_chk(path == NULL); head = calloc(sizeof(struct region_list), 1); err_chk(head == NULL); cur = head; /* Open maps */ snprintf(path, 24, "%s%d%s", "/proc/", (int) pid, "/maps"); maps_fd = open(path, O_RDONLY); err_chk(maps_fd == -1); /* read maps into memory */ for(maps_len = 0; (chk = read(maps_fd, &i_hate_proc, 1)) == 1; maps_len++); /* find length because files in proc are silly */ err_chk(chk == -1 || maps_len == 0); lseek(maps_fd, 0, SEEK_SET); maps = calloc(maps_len + 1, 1); err_chk(maps == NULL); while(offset != maps_len) { chk = read(maps_fd, maps + offset, maps_len - offset); err_chk(chk == -1); offset += chk; } /* parse */ while(1) { cur->next = calloc(sizeof(struct region_list), 1); err_chk(cur->next == NULL); cur->next->begin = (void *) strtol(maps + i, &tok, 16); cur->next->end = (void *) strtol(tok + 1, &tok, 16); for(;maps[i] != '\n';i++); if(flags & RL_FLAG_RWANON) { if(tok[1] != 'r' || tok[2] != 'w' || tok[21] != '0' || tok[22] != ' ') { free(cur->next); cur->next = NULL; i++; if(i == maps_len) break; else continue; } } else { if(tok[1] != 'r') { free(cur->next); cur->next = NULL; i++; if(i == maps_len) break; else continue; } } if(i+1 == maps_len) break; else i++; cur = cur->next; } /* clean up */ cur = head->next; free(head); free(path); free(maps); close(maps_fd); return cur; err: /* Error handling */ /* perror("new_region_list"); */ if(path) free(path); if(maps) free(maps); if(maps_fd != -1) close(maps_fd); return NULL; }
/* * Reads in at most one less than size characters from a file descriptor and stores them into the buffer pointed to by s. * Reading stops after a newline. If a newline is read, it is stored into the buffer. * * On success, the number of bytes read is returned (zero indicates end of file). * On error, -1 is returned, and errno is set appropriately. */ int zbx_read(int fd, char *buf, size_t count, const char *encoding) { size_t i, szbyte; const char *cr, *lf; int nbytes; #ifdef _WINDOWS __int64 offset; #else off_t offset; #endif offset = lseek(fd, 0, SEEK_CUR); if (0 >= (nbytes = (int)read(fd, buf, count))) return nbytes; if (0 == strcmp(encoding, "UNICODE") || 0 == strcmp(encoding, "UNICODELITTLE") || 0 == strcmp(encoding, "UTF-16") || 0 == strcmp(encoding, "UTF-16LE") || 0 == strcmp(encoding, "UTF16") || 0 == strcmp(encoding, "UTF16LE")) { cr = "\r\0"; lf = "\n\0"; szbyte = 2; } else if (0 == strcmp(encoding, "UNICODEBIG") || 0 == strcmp(encoding, "UNICODEFFFE") || 0 == strcmp(encoding, "UTF-16BE") || 0 == strcmp(encoding, "UTF16BE")) { cr = "\0\r"; lf = "\0\n"; szbyte = 2; } else if (0 == strcmp(encoding, "UTF-32") || 0 == strcmp(encoding, "UTF-32LE") || 0 == strcmp(encoding, "UTF32") || 0 == strcmp(encoding, "UTF32LE")) { cr = "\r\0\0\0"; lf = "\n\0\0\0"; szbyte = 4; } else if (0 == strcmp(encoding, "UTF-32BE") || 0 == strcmp(encoding, "UTF32BE")) { cr = "\0\0\0\r"; lf = "\0\0\0\n"; szbyte = 4; } else /* Single or Multi Byte Character Sets */ { cr = "\r"; lf = "\n"; szbyte = 1; } for (i = 0; i + szbyte <= (size_t)nbytes; i += szbyte) { if (0 == memcmp(&buf[i], lf, szbyte)) /* LF (Unix) */ { i += szbyte; break; } if (0 == memcmp(&buf[i], cr, szbyte)) /* CR (Mac) */ { if (i + szbyte < (size_t)nbytes && 0 == memcmp(&buf[i + szbyte], lf, szbyte)) /* CR+LF (Windows) */ i += szbyte; i += szbyte; break; } } lseek(fd, offset + i, SEEK_SET); return (int)i; }
static int Android_JNI_FileOpen(SDL_RWops* ctx) { LocalReferenceHolder refs(__FUNCTION__); int result = 0; jmethodID mid; jobject context; jobject assetManager; jobject inputStream; jclass channels; jobject readableByteChannel; jstring fileNameJString; jobject fd; jclass fdCls; jfieldID descriptor; JNIEnv *mEnv = Android_JNI_GetEnv(); if (!refs.init(mEnv)) { goto failure; } fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef; ctx->hidden.androidio.position = 0; // context = SDLActivity.getContext(); mid = mEnv->GetStaticMethodID(mActivityClass, "getContext","()Landroid/content/Context;"); context = mEnv->CallStaticObjectMethod(mActivityClass, mid); // assetManager = context.getAssets(); mid = mEnv->GetMethodID(mEnv->GetObjectClass(context), "getAssets", "()Landroid/content/res/AssetManager;"); assetManager = mEnv->CallObjectMethod(context, mid); /* First let's try opening the file to obtain an AssetFileDescriptor. * This method reads the files directly from the APKs using standard *nix calls */ mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager), "openFd", "(Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;"); inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString); if (Android_JNI_ExceptionOccurred(true)) { goto fallback; } mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getStartOffset", "()J"); ctx->hidden.androidio.offset = mEnv->CallLongMethod(inputStream, mid); if (Android_JNI_ExceptionOccurred(true)) { goto fallback; } mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getDeclaredLength", "()J"); ctx->hidden.androidio.size = mEnv->CallLongMethod(inputStream, mid); if (Android_JNI_ExceptionOccurred(true)) { goto fallback; } mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getFileDescriptor", "()Ljava/io/FileDescriptor;"); fd = mEnv->CallObjectMethod(inputStream, mid); fdCls = mEnv->GetObjectClass(fd); descriptor = mEnv->GetFieldID(fdCls, "descriptor", "I"); ctx->hidden.androidio.fd = mEnv->GetIntField(fd, descriptor); ctx->hidden.androidio.assetFileDescriptorRef = mEnv->NewGlobalRef(inputStream); // Seek to the correct offset in the file. lseek(ctx->hidden.androidio.fd, (off_t)ctx->hidden.androidio.offset, SEEK_SET); if (false) { fallback: // Disabled log message because of spam on the Nexus 7 //__android_log_print(ANDROID_LOG_DEBUG, "SDL", "Falling back to legacy InputStream method for opening file"); /* Try the old method using InputStream */ ctx->hidden.androidio.assetFileDescriptorRef = NULL; // inputStream = assetManager.open(<filename>); mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager), "open", "(Ljava/lang/String;I)Ljava/io/InputStream;"); inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString, 1 /*ACCESS_RANDOM*/); if (Android_JNI_ExceptionOccurred()) { goto failure; } ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream); // Despite all the visible documentation on [Asset]InputStream claiming // that the .available() method is not guaranteed to return the entire file // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ... // android/apis/content/ReadAsset.java imply that Android's // AssetInputStream.available() /will/ always return the total file size // size = inputStream.available(); mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "available", "()I"); ctx->hidden.androidio.size = (long)mEnv->CallIntMethod(inputStream, mid); if (Android_JNI_ExceptionOccurred()) { goto failure; } // readableByteChannel = Channels.newChannel(inputStream); channels = mEnv->FindClass("java/nio/channels/Channels"); mid = mEnv->GetStaticMethodID(channels, "newChannel", "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;"); readableByteChannel = mEnv->CallStaticObjectMethod( channels, mid, inputStream); if (Android_JNI_ExceptionOccurred()) { goto failure; } ctx->hidden.androidio.readableByteChannelRef = mEnv->NewGlobalRef(readableByteChannel); // Store .read id for reading purposes mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel), "read", "(Ljava/nio/ByteBuffer;)I"); ctx->hidden.androidio.readMethod = mid; } if (false) { failure: result = -1; mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef); if(ctx->hidden.androidio.inputStreamRef != NULL) { mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef); } if(ctx->hidden.androidio.readableByteChannelRef != NULL) { mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef); } if(ctx->hidden.androidio.assetFileDescriptorRef != NULL) { mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.assetFileDescriptorRef); } } return result; }
static int open_f(stream_t * stream, int mode, void * opts, int * file_format) { #ifndef __LINUX__ ufs_file_t * f = malloc(sizeof(ufs_file_t)); //= stream->fd; recv_bytes = 0; memset(f, 0, sizeof(ufs_file_t)); memset(filename1, 0, 512); #else int f = 0; #endif mode_t m = 0; file_size = 0; long long len; unsigned char * filename = NULL; struct stream_priv_s * p = (struct stream_priv_s *)opts; if (mode == STREAM_READ) { m = O_RDONLY; } else if (mode == STREAM_WRITE) { m = O_RDWR | O_CREAT | O_TRUNC; } else { mp_msg(MSGT_OPEN, MSGL_ERR, "[file] Unknown open mode %d\n", mode); m_struct_free(&stream_opts, opts); return STREAM_UNSUPPORTED; } if (p->filename) { filename = p->filename; } else if (p->filename2) { filename = p->filename2; } else { filename = NULL; } if (!filename) { mp_msg(MSGT_OPEN, MSGL_ERR, "[file] No filename\n"); m_struct_free(&stream_opts, opts); return STREAM_ERROR; } #if HAVE_DOS_PATHS // extract '/' from '/x:/path' if (filename[ 0 ] == '/' && filename[ 1 ] && filename[ 2 ] == ':') { filename++; } #endif m |= O_BINARY; if (!strcmp(filename, "-")) { #ifdef __LINUX__ if (mode == STREAM_READ) { // read from stdin mp_msg(MSGT_OPEN, MSGL_INFO, MSGTR_ReadSTDIN); f = 0; // 0=stdin #if HAVE_SETMODE setmode(fileno(stdin), O_BINARY); #endif } else { mp_msg(MSGT_OPEN, MSGL_INFO, "Writing to stdout\n"); f = 1; #if HAVE_SETMODE setmode(fileno(stdout), O_BINARY); #endif } #endif } else { #ifdef __LINUX__ mode_t openmode = S_IRUSR | S_IWUSR; #ifndef __MINGW32__ openmode |= S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; #endif f = open(filename, m, openmode); if (f < 0) { mp_msg(MSGT_OPEN, MSGL_ERR, MSGTR_FileNotFound, filename); m_struct_free(&stream_opts, opts); return STREAM_ERROR; } #else // ufs_asc2uni(filename,filename1); //printf("\n before ufs open filename:%s \n",filename); memcpy(filename1, filename, strlen(filename)); int ret = 0; unsigned short * p_filename1; { unsigned short path_tmp[512] = {0}; p_filename1 = Convert_Utf8_To_Unicode((unsigned char *)filename, path_tmp); ret = ufs_open(f, p_filename1, UFS_READ); } if (ret != FR_OK) { mtos_printk("[%s][ERROR][ERROR] UFS OPEN FAIL %d!!!!!!!!!\n", __func__, ret); m_struct_free(&stream_opts, opts); free(f); return STREAM_ERROR; } #if 1 // mtos_printk("\n%s %d \n", __func__, __LINE__); { int r = 0; char pvr_timeshift[512] = {0}; char pvr_ists[32] = {0}; recv_bytes_inter = 0; ret = ufs_read(f, pvr_timeshift, 512, &r); int time_mode; mp_timeshift_size = 0; file_size = 0; sect_size = 0; if (ret != FR_OK) { mtos_printk("[%s][ERROR][ERROR] UFS OPEN FAIL %d!!!!!!!!!\n", __func__, ret); m_struct_free(&stream_opts, opts); return STREAM_ERROR; } if (strstr(pvr_timeshift, "pvrtimeshift")) { memcpy(&mp_timeshift_size, pvr_timeshift + 32, sizeof(int)); memcpy(&time_mode, pvr_timeshift + 32 + sizeof(int), sizeof(int)); memcpy(basename, pvr_timeshift + 32 + 2 * sizeof(int), 256); memcpy(&file_size, pvr_timeshift + 384, sizeof(int)); memcpy(§_size, pvr_timeshift + 384+sizeof(int), sizeof(int)); rec_index = 1; } } #endif printf("\n ufs open ok f: %x \n", f); #ifndef __LINUX__ ret = ufs_ioctl(f, FS_SEEK_LINKMAP, 0 , 0 , 0); #endif #endif } #ifdef __LINUX__ len = lseek(f, 0, SEEK_END); lseek(f, 0, SEEK_SET); #else if (fp_is_timeshift_file() == 1) { while(mp_rec_bytes<sect_size*2) { mtos_task_sleep(100); } len = mp_rec_bytes; } else if (file_size > 0) { len = file_size; } else { len = f->file_size; } if (ufs_lseek(f, 0, 0) == FR_OK) { OS_PRINTF("#########@@@@#######\n"); } else { OS_PRINTF("#########@@1111@@#######\n"); } #endif #ifdef __MINGW32__ // seeks on stdin incorrectly succeed on MinGW if (f == 0) { len = -1; } #endif if (len == -1) { if (mode == STREAM_READ) { stream->seek = seek_forward; } stream->type = STREAMTYPE_STREAM; // Must be move to STREAMTYPE_FILE stream->flags |= MP_STREAM_SEEK_FW; } else if (len >= 0) { stream->seek = seek; stream->end_pos = len; stream->type = STREAMTYPE_FILE; } mp_msg(MSGT_OPEN, MSGL_V, "[file] File size is %"PRId64" bytes\n", (int64_t)len); // #ifdef __LINUX__ stream->fd = f; //#endif stream->fill_buffer = fill_buffer; stream->write_buffer = write_buffer; stream->control = control; stream->read_chunk = 64 * 1024; m_struct_free(&stream_opts, opts); return STREAM_OK; }
extern "C" Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence) { if (ctx->hidden.androidio.assetFileDescriptorRef) { switch (whence) { case RW_SEEK_SET: if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size; offset += ctx->hidden.androidio.offset; break; case RW_SEEK_CUR: offset += ctx->hidden.androidio.position; if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size; offset += ctx->hidden.androidio.offset; break; case RW_SEEK_END: offset = ctx->hidden.androidio.offset + ctx->hidden.androidio.size + offset; break; default: return SDL_SetError("Unknown value for 'whence'"); } whence = SEEK_SET; off_t ret = lseek(ctx->hidden.androidio.fd, (off_t)offset, SEEK_SET); if (ret == -1) return -1; ctx->hidden.androidio.position = ret - ctx->hidden.androidio.offset; } else { Sint64 newPosition; switch (whence) { case RW_SEEK_SET: newPosition = offset; break; case RW_SEEK_CUR: newPosition = ctx->hidden.androidio.position + offset; break; case RW_SEEK_END: newPosition = ctx->hidden.androidio.size + offset; break; default: return SDL_SetError("Unknown value for 'whence'"); } /* Validate the new position */ if (newPosition < 0) { return SDL_Error(SDL_EFSEEK); } if (newPosition > ctx->hidden.androidio.size) { newPosition = ctx->hidden.androidio.size; } Sint64 movement = newPosition - ctx->hidden.androidio.position; if (movement > 0) { unsigned char buffer[4096]; // The easy case where we're seeking forwards while (movement > 0) { Sint64 amount = sizeof (buffer); if (amount > movement) { amount = movement; } size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount); if (result <= 0) { // Failed to read/skip the required amount, so fail return -1; } movement -= result; } } else if (movement < 0) { // We can't seek backwards so we have to reopen the file and seek // forwards which obviously isn't very efficient Android_JNI_FileClose(ctx, false); Android_JNI_FileOpen(ctx); Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET); } } return ctx->hidden.androidio.position; }
static int do_test (void) { /* fdopendir takes over the descriptor, make a copy. */ int dupfd = dup (dir_fd); if (dupfd == -1) { puts ("dup failed"); return 1; } if (lseek (dupfd, 0, SEEK_SET) != 0) { puts ("1st lseek failed"); return 1; } /* The directory should be empty safe the . and .. files. */ DIR *dir = fdopendir (dupfd); if (dir == NULL) { puts ("fdopendir failed"); return 1; } struct dirent64 *d; while ((d = readdir64 (dir)) != NULL) if (strcmp (d->d_name, ".") != 0 && strcmp (d->d_name, "..") != 0) { printf ("temp directory contains file \"%s\"\n", d->d_name); return 1; } closedir (dir); /* Try to create a file. */ int fd = openat (dir_fd, "some-file", O_CREAT|O_RDWR|O_EXCL, 0666); if (fd == -1) { if (errno == ENOSYS) { puts ("*at functions not supported"); return 0; } puts ("file creation failed"); return 1; } write (fd, "hello", 5); /* Before closing the file, try using this file descriptor to open another file. This must fail. */ int fd2 = openat (fd, "should-not-work", O_CREAT|O_RDWR, 0666); if (fd2 != -1) { puts ("openat using descriptor for normal file worked"); return 1; } if (errno != ENOTDIR) { puts ("error for openat using descriptor for normal file not ENOTDIR "); return 1; } close (fd); puts ("file created"); /* fdopendir takes over the descriptor, make a copy. */ dupfd = dup (dir_fd); if (dupfd == -1) { puts ("dup failed"); return 1; } if (lseek (dupfd, 0, SEEK_SET) != 0) { puts ("2nd lseek failed"); return 1; } /* The directory should be empty safe the . and .. files. */ dir = fdopendir (dupfd); if (dir == NULL) { puts ("fdopendir failed"); return 1; } bool seen_file = false; while ((d = readdir64 (dir)) != NULL) if (strcmp (d->d_name, ".") != 0 && strcmp (d->d_name, "..") != 0) { if (strcmp (d->d_name, "some-file") != 0) { printf ("temp directory contains file \"%s\"\n", d->d_name); return 1; } seen_file = true; } closedir (dir); if (!seen_file) { puts ("file not created in correct directory"); return 1; } int cwdfd = open (".", O_RDONLY | O_DIRECTORY); if (cwdfd == -1) { puts ("cannot get descriptor for cwd"); return 1; } if (fchdir (dir_fd) != 0) { puts ("1st fchdir failed"); return 1; } if (unlink ("some-file") != 0) { puts ("unlink failed"); return 1; } if (fchdir (cwdfd) != 0) { puts ("2nd fchdir failed"); return 1; } close (dir_fd); close (cwdfd); /* With the file descriptor closed the next call must fail. */ fd = openat (dir_fd, "some-file", O_CREAT|O_RDWR|O_EXCL, 0666); if (fd != -1) { puts ("openat using closed descriptor succeeded"); return 1; } if (errno != EBADF) { puts ("openat using closed descriptor did not set EBADF"); return 1; } fd = openat (-1, "some-file", O_CREAT|O_RDWR|O_EXCL, 0666); if (fd != -1) { puts ("openat using -1 descriptor succeeded"); return 1; } if (errno != EBADF) { puts ("openat using -1 descriptor did not set EBADF"); return 1; } return 0; }
static int mksplit(const char *file_src, const char *prefix, off_t maxpartsize, bool msdos) { int fd_src; struct stat st; char hash[MD5HASHLEN + 1]; char *package, *version, *arch; int nparts, curpart; off_t partsize; off_t cur_partsize, last_partsize; char *prefixdir = NULL, *msdos_prefix = NULL; struct varbuf file_dst = VARBUF_INIT; struct varbuf partmagic = VARBUF_INIT; struct varbuf partname = VARBUF_INIT; fd_src = open(file_src, O_RDONLY); if (fd_src < 0) ohshite(_("unable to open source file `%.250s'"), file_src); if (fstat(fd_src, &st)) ohshite(_("unable to fstat source file")); if (!S_ISREG(st.st_mode)) ohshit(_("source file `%.250s' not a plain file"), file_src); fd_md5(fd_src, hash, -1, "md5hash"); lseek(fd_src, 0, SEEK_SET); /* FIXME: Use libdpkg-deb. */ package = deb_field(file_src, "Package"); version = deb_field(file_src, "Version"); arch = deb_field(file_src, "Architecture"); partsize = maxpartsize - HEADERALLOWANCE; last_partsize = st.st_size % partsize; if (last_partsize == 0) last_partsize = partsize; nparts = (st.st_size + partsize - 1) / partsize; setvbuf(stdout, NULL, _IONBF, 0); printf(P_("Splitting package %s into %d part: ", "Splitting package %s into %d parts: ", nparts), package, nparts); if (msdos) { char *t; t = m_strdup(prefix); prefixdir = m_strdup(dirname(t)); free(t); msdos_prefix = m_strdup(path_basename(prefix)); prefix = clean_msdos_filename(msdos_prefix); } for (curpart = 1; curpart <= nparts; curpart++) { int fd_dst; varbuf_reset(&file_dst); /* Generate output filename. */ if (msdos) { char *refname; int prefix_max; m_asprintf(&refname, "%dof%d", curpart, nparts); prefix_max = max(8 - strlen(refname), 0); varbuf_printf(&file_dst, "%s/%.*s%.8s.deb", prefixdir, prefix_max, prefix, refname); free(refname); } else { varbuf_printf(&file_dst, "%s.%dof%d.deb", prefix, curpart, nparts); } if (curpart == nparts) cur_partsize = last_partsize; else cur_partsize = partsize; if (cur_partsize > maxpartsize) { ohshit(_("Header is too long, making part too long. " "Your package name or version\n" "numbers must be extraordinarily long, " "or something. Giving up.\n")); } /* Split the data. */ fd_dst = creat(file_dst.buf, 0644); if (fd_dst < 0) ohshite(_("unable to open file '%s'"), file_dst.buf); /* Write the ar header. */ dpkg_ar_put_magic(file_dst.buf, fd_dst); /* Write the debian-split part. */ varbuf_printf(&partmagic, "%s\n%s\n%s\n%s\n%jd\n%jd\n%d/%d\n%s\n", SPLITVERSION, package, version, hash, (intmax_t)st.st_size, (intmax_t)partsize, curpart, nparts, arch); dpkg_ar_member_put_mem(file_dst.buf, fd_dst, PARTMAGIC, partmagic.buf, partmagic.used); varbuf_reset(&partmagic); /* Write the data part. */ varbuf_printf(&partname, "data.%d", curpart); dpkg_ar_member_put_file(file_dst.buf, fd_dst, partname.buf, fd_src, cur_partsize); varbuf_reset(&partname); close(fd_dst); printf("%d ", curpart); } varbuf_destroy(&file_dst); varbuf_destroy(&partname); varbuf_destroy(&partmagic); free(prefixdir); free(msdos_prefix); close(fd_src); printf(_("done\n")); return 0; }
int main(int argc, char* argv[]){ long i; long iterations = DEFAULT_ITERATIONS; struct sched_param param; int rv, policy, num_processes, status; int inputFD; int outputFD; double x, y; double inCircle = 0.0; double inSquare = 0.0; double pCircle = 0.0; double piCalc = 0.0; ssize_t transfersize = DEFAULT_TRANSFERSIZE; ssize_t blocksize = DEFAULT_BLOCKSIZE; char* transferBuffer = NULL; ssize_t buffersize; char inputFilename[MAXFILENAMELENGTH]; char outputFilename[MAXFILENAMELENGTH]; char outputFilenameBase[MAXFILENAMELENGTH]; ssize_t bytesRead = 0; ssize_t totalBytesRead = 0; int totalReads = 0; ssize_t bytesWritten = 0; ssize_t totalBytesWritten = 0; int totalWrites = 0; int inputFileResets = 0; pid_t pid, wpid; int j = 0; strncpy(inputFilename, DEFAULT_INPUTFILENAME, MAXFILENAMELENGTH); strncpy(outputFilenameBase, DEFAULT_OUTPUTFILENAMEBASE, MAXFILENAMELENGTH); if(argc < 2){ policy = SCHED_OTHER; } if(argc < 3){ num_processes = MED; } /* Set policy if supplied */ if(argc > 1){ if(!strcmp(argv[1], "SCHED_OTHER")){ policy = SCHED_OTHER; } else if(!strcmp(argv[1], "SCHED_FIFO")){ policy = SCHED_FIFO; } else if(!strcmp(argv[1], "SCHED_RR")){ policy = SCHED_RR; } else{ fprintf(stderr, "Unhandeled scheduling policy\n"); exit(EXIT_FAILURE); } } if(argc > 2){ if(!strcmp(argv[2], "LOW")){ num_processes = LOW; } else if(!strcmp(argv[2], "MED")){ num_processes = MED; } else if(!strcmp(argv[2], "HI")){ num_processes = HI; } else{ fprintf(stderr, "Unhandeled number of processes\n"); exit(EXIT_FAILURE); } } param.sched_priority = sched_get_priority_max(policy); /* Set new scheduler policy */ fprintf(stdout, "Current Scheduling Policy: %d\n", sched_getscheduler(0)); fprintf(stdout, "Setting Scheduling Policy to: %d\n", policy); if(sched_setscheduler(0, policy, ¶m)){ perror("Error setting scheduler policy"); exit(EXIT_FAILURE); } fprintf(stdout, "New Scheduling Policy: %d\n", sched_getscheduler(0)); printf("# Forks%d \n", num_processes); for(i = 0; i < num_processes; i++){ if((pid = fork())==-1){ fprintf(stderr, "Error Forking Child Process"); exit(EXIT_FAILURE); /*Fork Failed*/ } if(pid == 0){ /* Child Process */ /* Calculate pi using statistical methode across all iterations*/ for(i=0; i<iterations; i++){ x = (random() % (RADIUS * 2)) - RADIUS; y = (random() % (RADIUS * 2)) - RADIUS; if(zeroDist(x,y) < RADIUS){ inCircle++; } inSquare++; } /* Finish calculation */ pCircle = inCircle/inSquare; piCalc = pCircle * 4.0; /* Print result */ fprintf(stdout, "pi = %f\n", piCalc); /* Confirm blocksize is multiple of and less than transfersize*/ if(blocksize > transfersize){ fprintf(stderr, "blocksize can not exceed transfersize\n"); exit(EXIT_FAILURE); } if(transfersize % blocksize){ fprintf(stderr, "blocksize must be multiple of transfersize\n"); exit(EXIT_FAILURE); } /* Allocate buffer space */ buffersize = blocksize; if(!(transferBuffer = malloc(buffersize*sizeof(*transferBuffer)))){ perror("Failed to allocate transfer buffer"); exit(EXIT_FAILURE); } /* Open Input File Descriptor in Read Only mode */ if((inputFD = open(inputFilename, O_RDONLY | O_SYNC)) < 0){ perror("Failed to open input file"); exit(EXIT_FAILURE); } /* Open Output File Descriptor in Write Only mode with standard permissions*/ rv = snprintf(outputFilename, MAXFILENAMELENGTH, "%s-%d", outputFilenameBase, getpid()); if(rv > MAXFILENAMELENGTH){ fprintf(stderr, "Output filenmae length exceeds limit of %d characters.\n", MAXFILENAMELENGTH); exit(EXIT_FAILURE); } else if(rv < 0){ perror("Failed to generate output filename"); exit(EXIT_FAILURE); } if((outputFD = open(outputFilename, O_WRONLY | O_CREAT | O_TRUNC | O_SYNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)) < 0){ perror("Failed to open output file"); exit(EXIT_FAILURE); } /* Print Status */ fprintf(stdout, "Reading from %s and writing to %s\n", inputFilename, outputFilename); /* Read from input file and write to output file*/ do{ /* Read transfersize bytes from input file*/ bytesRead = read(inputFD, transferBuffer, buffersize); if(bytesRead < 0){ perror("Error reading input file"); exit(EXIT_FAILURE); } else{ totalBytesRead += bytesRead; totalReads++; } /* If all bytes were read, write to output file*/ if(bytesRead == blocksize){ bytesWritten = write(outputFD, transferBuffer, bytesRead); if(bytesWritten < 0){ perror("Error writing output file"); exit(EXIT_FAILURE); } else{ totalBytesWritten += bytesWritten; totalWrites++; } } /* Otherwise assume we have reached the end of the input file and reset */ else{ if(lseek(inputFD, 0, SEEK_SET)){ perror("Error resetting to beginning of file"); exit(EXIT_FAILURE); } inputFileResets++; } }while(totalBytesWritten < transfersize); /* Output some possibly helpfull info to make it seem like we were doing stuff */ fprintf(stdout, "Read: %zd bytes in %d reads\n", totalBytesRead, totalReads); fprintf(stdout, "Written: %zd bytes in %d writes\n", totalBytesWritten, totalWrites); fprintf(stdout, "Read input file in %d pass%s\n", (inputFileResets + 1), (inputFileResets ? "es" : "")); fprintf(stdout, "Processed %zd bytes in blocks of %zd bytes\n", transfersize, blocksize); } } while((wpid = wait(&status)) > 0){ if(WIFEXITED(status)){ j++; } } printf("Total # forks terminated%d\n", j); return EXIT_SUCCESS; }
static int write_block(MtdWriteContext *ctx, const char *data) { const MtdPartition *partition = ctx->partition; int fd = ctx->fd; off_t pos = lseek(fd, 0, SEEK_CUR); if (pos == (off_t) -1) return 1; ssize_t size = partition->erase_size; while (pos + size <= (int) partition->size) { loff_t bpos = pos; if (ioctl(fd, MEMGETBADBLOCK, &bpos) > 0) { add_bad_block_offset(ctx, pos); fprintf(stderr, "mtd: not writing bad block at 0x%08lx\n", pos); pos += partition->erase_size; continue; // Don't try to erase known factory-bad blocks. } struct erase_info_user erase_info; erase_info.start = pos; erase_info.length = size; int retry; for (retry = 0; retry < 2; ++retry) { if (ioctl(fd, MEMERASE, &erase_info) < 0) { fprintf(stderr, "mtd: erase failure at 0x%08lx (%s)\n", pos, strerror(errno)); continue; } if (lseek(fd, pos, SEEK_SET) != pos || write(fd, data, size) != size) { fprintf(stderr, "mtd: write error at 0x%08lx (%s)\n", pos, strerror(errno)); } char verify[size]; if (lseek(fd, pos, SEEK_SET) != pos || read(fd, verify, size) != size) { fprintf(stderr, "mtd: re-read error at 0x%08lx (%s)\n", pos, strerror(errno)); continue; } if (memcmp(data, verify, size) != 0) { fprintf(stderr, "mtd: verification error at 0x%08lx (%s)\n", pos, strerror(errno)); continue; } if (retry > 0) { fprintf(stderr, "mtd: wrote block after %d retries\n", retry); } return 0; // Success! } // Try to erase it once more as we give up on this block add_bad_block_offset(ctx, pos); fprintf(stderr, "mtd: skipping write block at 0x%08lx\n", pos); ioctl(fd, MEMERASE, &erase_info); pos += partition->erase_size; } // Ran out of space on the device errno = ENOSPC; return -1; }
void TruncFile::seekCur(long offset) { if(lseek(fd_, offset, SEEK_CUR) == -1) LOG_SYSFATAL << "lseek error"; }
static ssize_t bml_over_mtd_write_block(int fd, ssize_t erase_size, char* data) { off_t pos = lseek(fd, 0, SEEK_CUR); if (pos == (off_t) -1) return -1; ssize_t size = erase_size; loff_t bpos = pos; int ret = ioctl(fd, MEMGETBADBLOCK, &bpos); if (ret != 0 && !(ret == -1 && errno == EOPNOTSUPP)) { fprintf(stderr, "Mapping failure: Trying to write bad block at 0x%08lx (ret %d errno %d)\n", pos, ret, errno); return -1; } struct erase_info_user erase_info; erase_info.start = pos; erase_info.length = size; int retry; for (retry = 0; retry < 2; ++retry) { #ifdef RK3X if (rk30_zero_out(fd, pos, size) < 0) { fprintf(stderr, "mtd: erase failure at 0x%08lx (%s)\n", pos, strerror(errno)); continue; } #else if (ioctl(fd, MEMERASE, &erase_info) < 0) { fprintf(stderr, "mtd: erase failure at 0x%08lx (%s)\n", pos, strerror(errno)); continue; } #endif if (lseek(fd, pos, SEEK_SET) != pos || write(fd, data, size) != size) { fprintf(stderr, "mtd: write error at 0x%08lx (%s)\n", pos, strerror(errno)); } char verify[size]; if (lseek(fd, pos, SEEK_SET) != pos || read(fd, verify, size) != size) { fprintf(stderr, "mtd: re-read error at 0x%08lx (%s)\n", pos, strerror(errno)); continue; } if (memcmp(data, verify, size) != 0) { fprintf(stderr, "mtd: verification error at 0x%08lx (%s)\n", pos, strerror(errno)); continue; } if (retry > 0) { fprintf(stderr, "mtd: wrote block after %d retries\n", retry); } fprintf(stderr, "mtd: successfully wrote block at %llx\n", pos); return size; // Success! } fprintf(stderr, "mtd: Block at %llx could not be properly written.\n", pos); // Ran out of space on the device errno = ENOSPC; return -1; }
unsigned long DIGCLIENT DIGCliSeek( dig_fhandle h, unsigned long p, dig_seek k ) /******************************************************************************/ { return( lseek( h, p, k ) ); }
int btFiles::ftruncate(int fd,size_t length) { char c = (char)0; if(lseek(fd,length - 1, SEEK_SET) < 0 ) return -1; return write(fd, &c, 1); }