int main(void) { const char *filename = "/tmp/file.txt"; char c; FILE *fp; fp = fopen(filename, "r"); if (fp == NULL) { perror("fopen() failed"); exit(EXIT_FAILURE); } else { printf("Displaying the contents of file...\n"); while((c = fgetc(fp)) != EOF) { fputc(c, stdout); } //diplay i/o information about the text file printf("\nFile descriptor is %d\n",getFileDescriptor(fp)); printf("File size is %d bytes\n", getFileSize(fp)); printf("Size of file is %d bytes\n", fileSize(fp)); printf("Size of buffer is %d bytes\n", getFileBufSize(fp)); getFileBufMode(fp); //display i/o information about stdout printf("\n"); //put a character to stdout printf("File descriptor is %d\n",getFileDescriptor(stdout)); printf("Size of buffer is %d bytes\n", getFileBufSize(stdout)); getFileBufMode(stdout); } fclose(fp); return EXIT_SUCCESS; }
int initConnexionHID(void *windowID) { getFileDescriptor(); if(fd < 0) { return 0; } return 1; }
/** * Remove a file from the system, and free allocated assets * (including assigned blocks which are returned for use by other files). * * @param filename null-terminated name of the file to remove. * @return MICROBIT_OK on success, MICROBIT_INVALID_PARAMETER if the given filename * does not exist, MICROBIT_CANCELLED if something went wrong. * * @code * MicroBitFileSystem f; * if(!f.remove("file.txt")) * print("file could not be removed") * @endcode */ int MicroBitFileSystem::remove(char const * filename) { int fd = open(filename, MB_READ); uint16_t block, nextBlock; uint16_t value; // If the file can't be opened, then it is impossible to delete. Pass through any error codes. if (fd < 0) return fd; FileDescriptor *file = getFileDescriptor(fd, true); // To erase a file, all we need to do is mark its directory entry and data blocks as INVALID. // First mark the file table block = file->dirent->first_block; while (block != MBFS_EOF) { nextBlock = fileSystemTable[block]; fileTableWrite(block, MBFS_DELETED); block = nextBlock; } // Mark the directory entry of this file as invalid. value = MBFS_DIRECTORY_ENTRY_DELETED; flash.flash_write(&file->dirent->flags, &value, 2); // release file metadata delete file; return MICROBIT_OK; }
void STORAGE::DynamicMemoryMappedFile::grow(size_t newSize) { // Increase the size by some amount size_t oldMapSize = mapSize; size_t amt = newSize - oldMapSize; if (amt <= 0) { return; } size_t test = (size_t)std::ceil(newSize * GROWTH_FACTOR); mapSize = align(test > maxSize ? maxSize : test); #if EXTRATESTING std::ostringstream os; os << mapSize; logEvent(EVENT, "Growing filesystem to " + os.str()); #endif int fd = getFileDescriptor(backingFilename); ftruncate(fd, mapSize); fs = (char*)mmap((void*)NULL, mapSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); _close(fd); if (fs == MAP_FAILED) { // Uhoh... logEvent(ERROR, "Could not remap backing file after growing"); shutdown(FAILURE); } }
/* * static void startMethodTracingFd(String traceFileName, FileDescriptor fd, * int bufferSize, int flags, boolean samplingEnabled, int intervalUs) * * Start method trace profiling, sending results to a file descriptor. */ static void Dalvik_dalvik_system_VMDebug_startMethodTracingFd(const u4* args, JValue* pResult) { StringObject* traceFileStr = (StringObject*) args[0]; Object* traceFd = (Object*) args[1]; int bufferSize = args[2]; int flags = args[3]; bool samplingEnabled = args[4]; int intervalUs = args[5]; int origFd = getFileDescriptor(traceFd); if (origFd < 0) RETURN_VOID(); int fd = dup(origFd); if (fd < 0) { dvmThrowExceptionFmt(gDvm.exRuntimeException, "dup(%d) failed: %s", origFd, strerror(errno)); RETURN_VOID(); } char* traceFileName = dvmCreateCstrFromString(traceFileStr); if (traceFileName == NULL) { RETURN_VOID(); } dvmMethodTraceStart(traceFileName, fd, bufferSize, flags, false, samplingEnabled, intervalUs); free(traceFileName); RETURN_VOID(); }
void executeSysCallOpen(MpsRequest * aReq, ClientConnection * conn){ char * vdaName = getVdaName(aReq->arg2); int * openingMode = aReq->arg1; //TODO: se comunica con el FSS para obtener el correspondiente //TODO: file descriptor int fd = getFileDescriptor(aReq); //TODO: se comunica con el FSS para obtener el correspondiente //TODO: file size int fz = getFileSize(aReq); //TODO: si no encuentra un archivo en la tabla hace esto //TODO: de lo contrario lo borra y lo abre denuevo TddRecord * record = createTddRecord(1 , vdaName , *openingMode , 512); record->fileSize = fz; addTddRecord(record); long idDescriptor = getIdDescriptor(aReq->idDescriptor); MpsMessage m = buildMessage( idDescriptor, SUCCESS_RESULT , itoa(fd) ); }
void DynamicResponseState::execveCgiProgram(){ char *emptylist[]={NULL}; if(_fork()==0){ setenv("QUERY_STRING",cgiArgs.c_str(),1); _dup2(getFileDescriptor(),STDOUT_FILENO); _execve(getFileName().c_str(),emptylist,environ); } _wait(NULL); }
unsigned short ZmqSocket::connect(const char* endpoint) { CHECK_RET_CODE(sock != 0, ERR_CLOSE); CHECK_API_RET(zmq_connect(sock, endpoint) != -1); // store file handle on base class onConnected(getFileDescriptor()); unsetNeedWrite(); // fd only work with read events fdCheckEvents(); // getting problems with this return NO_ERR; }
// This client connection is in use when it's file descriptor is set bool isInUse() const { bool inUse(mExit || isOpen()) ; std::stringstream ss ; ss << "ClientTty::isInUse(fd=" << getFileDescriptor() << ") @ " << this << " = " << inUse << " exit=" << mExit ; DEBUG_COMMS_COUT << ss.str() << std::endl ; return inUse ; }
ServerSocket::ServerSocket() { // TODO Auto-generated constructor stub _hostAddress= getAddress(); _hostFileDescripotr=getFileDescriptor(); //初始化Socket if ((_hostFileDescripotr = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("create socket error: %s(errno: %d)\n", strerror(errno), errno); } }
int sys_read(int fdesc,userptr_t ubuf,unsigned int nbytes,int *retval){ if (!ubuf){ return EFAULT; } struct filedescriptor* fDescriptor = getFileDescriptor(fdesc, curthread->t_fdManager); if (fDescriptor == NULL){ return EBADF; } switch (O_ACCMODE & fDescriptor->fdmode){ case O_RDONLY: break; case O_RDWR: break; default: return EBADF; } struct uio u; struct iovec iov; iov.iov_ubase = ubuf; iov.iov_len = nbytes; u.uio_iov = &iov; u.uio_iovcnt = 1; u.uio_offset = fDescriptor->fdoff; /* not needed for the console */ u.uio_resid = nbytes; u.uio_segflg = UIO_USERSPACE; u.uio_rw = UIO_READ; u.uio_space = curproc->p_addrspace; lock_acquire(fDescriptor->fdlock); int readSize = VOP_READ(fDescriptor->fdvnode, &u); lock_release(fDescriptor->fdlock); if(readSize){ return readSize; } readSize = nbytes - u.uio_resid; *retval = readSize; fDescriptor->fdoff += nbytes; return nbytes; }
l_off_t VfsSyscall::lseek(uint32 fd, l_off_t offset, uint8 origin) { FileDescriptor* file_descriptor = getFileDescriptor(fd); if (file_descriptor == 0) { debug(VFSSYSCALL, "(lseek) Error: the fd does not exist.\n"); return -1; } return file_descriptor->getFile()->lseek(offset, origin); }
uint32 VfsSyscall::getFileSize(uint32 fd) { FileDescriptor* file_descriptor = getFileDescriptor(fd); if (file_descriptor == 0) { debug(VFSSYSCALL, "(read) Error: the fd does not exist.\n"); return -1; } return file_descriptor->getFile()->getSize(); }
int32 VfsSyscall::close(uint32 fd) { FileDescriptor* file_descriptor = getFileDescriptor(fd); if (file_descriptor == 0) { debug(VFSSYSCALL, "(close) Error: the fd does not exist.\n"); return -1; } Inode* current_inode = file_descriptor->getFile()->getInode(); assert(current_inode->getSuperblock()->removeFd(current_inode, file_descriptor) == 0); return 0; }
/* * static void dumpHprofData(String fileName, FileDescriptor fd) * * Cause "hprof" data to be dumped. We can throw an IOException if an * error occurs during file handling. */ static void Dalvik_dalvik_system_VMDebug_dumpHprofData(const u4* args, JValue* pResult) { #ifdef WITH_HPROF StringObject* fileNameStr = (StringObject*) args[0]; Object* fileDescriptor = (Object*) args[1]; char* fileName; int result; /* * Only one of these may be NULL. */ if (fileNameStr == NULL && fileDescriptor == NULL) { dvmThrowException("Ljava/lang/NullPointerException;", NULL); RETURN_VOID(); } if (fileNameStr != NULL) { fileName = dvmCreateCstrFromString(fileNameStr); if (fileName == NULL) { /* unexpected -- malloc failure? */ dvmThrowException("Ljava/lang/RuntimeException;", "malloc failure?"); RETURN_VOID(); } } else { fileName = strdup("[fd]"); } int fd = -1; if (fileDescriptor != NULL) { fd = getFileDescriptor(fileDescriptor); if (fd < 0) RETURN_VOID(); } result = hprofDumpHeap(fileName, fd, false); free(fileName); if (result != 0) { /* ideally we'd throw something more specific based on actual failure */ dvmThrowException("Ljava/lang/RuntimeException;", "Failure during heap dump -- check log output for details"); RETURN_VOID(); } #else dvmThrowException("Ljava/lang/UnsupportedOperationException;", NULL); #endif RETURN_VOID(); }
int32 VfsSyscall::write(uint32 fd, const char *buffer, uint32 count) { FileDescriptor* file_descriptor = getFileDescriptor(fd); if (file_descriptor == 0) { debug(VFSSYSCALL, "(write) Error: the fd does not exist.\n"); return -1; } if (count == 0) return 0; return file_descriptor->getFile()->write(buffer, count, 0); }
int removeDescriptor(int index, struct fdManager * manager){ struct filedescriptor * descriptor = getFileDescriptor(index, manager); if (descriptor == NULL) { kprintf("remove Descriptor not initiailized\n"); return -1; } fddestroy(descriptor); array_set(manager->fdm_descriptors, index, NULL); if (index < manager->fdm_next) { manager->fdm_next = index; } return 0; }
/** * Close the specified file handle. * File handle resources are then made available for future open() calls. * * close() must be called at some point to ensure the filesize in the * FT is synced with the cached value in the FD. * * @warning if close() is not called, the FT may not be correct, * leading to data loss. * * @param fd file descriptor - obtained with open(). * @return MICROBIT_OK on success, MICROBIT_NOT_SUPPORTED if the file system has not * been initialised, MICROBIT_INVALID_PARAMETER if the given file handle * is invalid. * * @code * MicroBitFileSystem f(); * int fd = f.open("test.txt", MB_READ); * if(!f.close(fd)) * print("error closing file."); * @endcode */ int MicroBitFileSystem::close(int fd) { // Firstly, ensure all unwritten data is flushed. int r = flush(fd); // If the flush called failed on validation, pass the error code onto the caller. if (r != MICROBIT_OK) return r; // Remove the file descriptor from the list of open files, and free it. // n.b. we know this is safe, as flush() validates this. delete getFileDescriptor(fd, true); return MICROBIT_OK; }
/* thread for hash server */ void hashServer( xcVirtualPacket_t * pVPkt, responseStruct * pResponse ) { long rc; /* return code for various functions */ xcSHA1_RB_t sha1rb; /* sha request block */ hashHdr_t *hashHdrPtr = NULL; /* request header from host */ hashHdr_t hshReplyHdr; /* reply header to host */ pthread_t pid = pthread_self(); /* process id for this thread */ int dataLen; /* length of data to hash */ unsigned char *dataToHashPtr = NULL; /* pointer to data to be hashed */ /* initialize variables */ memset( &sha1rb, 0x00, sizeof( xcSHA1_RB_t ) ); memset( &hshReplyHdr, 0x00, sizeof( hashHdr_t ) ); /* extract what we need from pvpkt */ hashHdrPtr = (hashHdr_t*) &(pVPkt->data_start ); dataLen = hashHdrPtr->dataLen; /* cast to char * so sizeof's pointer math is correct */ dataToHashPtr = (unsigned char*)hashHdrPtr + sizeof( hashHdr_t ); /* source length is padded w/0's to a multiple of 8 */ /* on the host */ sha1rb.source_length = dataLen; sha1rb.options = SHA1_MSGPART_ONLY; sha1rb.source.data_ptr = (void*)dataToHashPtr; /* call sha1 service */ if( (rc = xcSha1( getFileDescriptor(FD_SHA), &sha1rb ) ) != 0 ) pResponse->status = HSH_SYS_ERROR; else pResponse->status = HSH_OK; /* time to send a message back to host, set up reply */ hshReplyHdr.dataLen = SHA1_PADDED_LEN;/* must be a multiple of 8 bytes */ hshReplyHdr.pid = pid; pResponse->headerLength = sizeof( hashHdr_t ); memcpy( pResponse->header, &hshReplyHdr, sizeof( hashHdr_t ) ); pResponse->dataLength = SHA1_PADDED_LEN;//must pass back a mult of 8 /* only copy the 20 bytes we need, rest of buffer padded with 0's in skelxc.c */ memcpy( pResponse->data, sha1rb.hash_value, SHA1_HASH_SIZE ); pResponse->userDef = 0; return; }
/** * Write data to the file. * * Write from buffer, len bytes to the current seek position. * On each invocation to write, the seek position of the file handle * is incremented atomically, by the number of bytes returned. * * The cached filesize in the FD is updated on this call. Also, the * FT file size is updated only if a new page(s) has been written too, * to reduce the number of FT writes. * * @param fd File handle * @param buffer the buffer from which to write data * @param len number of bytes to write * @return number of bytes written on success, MICROBIT_NO_RESOURCES if data did * not get written to flash or the file system has not been initialised, * or this file was not opened with the MB_WRITE flag set, MICROBIT_INVALID_PARAMETER * if the given file handle is invalid. * * @code * MicroBitFileSystem f(); * int fd = f.open("test.txt", MB_WRITE); * if(f.write(fd, "hello!", 7) != 7) * print("error writing"); * @endcode */ int MicroBitFileSystem::write(int fd, uint8_t* buffer, int size) { FileDescriptor *file; int bytesCopied = 0; int segmentSize; // Protect against accidental re-initialisation if ((status & MBFS_STATUS_INITIALISED) == 0) return MICROBIT_NOT_SUPPORTED; // Ensure the file is open. file = getFileDescriptor(fd); if (file == NULL || buffer == NULL || size == 0) return MICROBIT_INVALID_PARAMETER; // Determine how to handle the write. If the buffer size is less than our cache size, // write the data via the cache. Otherwise, a direct write through is likely more efficient. // This may take a few iterations if the cache is already quite full. if (size < MBFS_CACHE_SIZE) { while (bytesCopied < size) { segmentSize = min(size, MBFS_CACHE_SIZE - file->cacheLength); memcpy(&file->cache[file->cacheLength], buffer, segmentSize); file->cacheLength += segmentSize; bytesCopied += segmentSize; if (file->cacheLength == MBFS_CACHE_SIZE) writeBack(file); } return bytesCopied; } // If we have a relatively large block, then write it directly ( writeBack(file); return writeBuffer(file, buffer, size); }
/** * Writes back all state associated with the given file to FLASH memory, * leaving the file open. * * @param fd file descriptor - obtained with open(). * @return MICROBIT_OK on success, MICROBIT_NOT_SUPPORTED if the file system has not * been initialised, MICROBIT_INVALID_PARAMETER if the given file handle * is invalid. * * @code * MicroBitFileSystem f(); * int fd = f.open("test.txt", MB_READ); * * ... * * f.flush(fd); * @endcode */ int MicroBitFileSystem::flush(int fd) { // Protect against accidental re-initialisation if ((status & MBFS_STATUS_INITIALISED) == 0) return MICROBIT_NOT_SUPPORTED; FileDescriptor *file = getFileDescriptor(fd); // Ensure the file is open. if(file == NULL) return MICROBIT_INVALID_PARAMETER; // Flush any data in the writeback cache. writeBack(file); // If the file has changed size, create an updated directory entry for the file, reflecting it's new length. if (file->dirent->length != file->length) { DirectoryEntry d = *file->dirent; d.length = file->length; // Do some optimising to reduce FLASH churn if this is the first write to a file. No need then to create a new dirent... if (file->dirent->flags == MBFS_DIRECTORY_ENTRY_NEW) { d.flags = MBFS_DIRECTORY_ENTRY_VALID; flash.flash_write(file->dirent, &d, sizeof(DirectoryEntry)); } // Otherwise, replace the dirent with a freshly allocated one, and mark the other as INVALID. else { DirectoryEntry *newDirent; uint16_t value = MBFS_DELETED; // invalidate the old directory entry and create a new one with the updated data. flash.flash_write(&file->dirent->flags, &value, 2); newDirent = createDirectoryEntry(file->directory); flash.flash_write(newDirent, &d, sizeof(DirectoryEntry)); } } return MICROBIT_OK; }
int addDescriptor(struct fdManager *manager, struct filedescriptor *descriptor) { if(!manager->fdm_initialized) { initialize_fdManager(manager); } int mokval; if(manager->fdm_next >= getSize(manager)) { unsigned int *error; if (array_add(manager->fdm_descriptors, (void *) descriptor, error)) { kprintf("addDescriptor failed\n"); return -1; } mokval = manager->fdm_next; manager->fdm_next = getSize(manager); descriptor->fdopen = descriptor->fdopen + 1; } else { array_set(manager->fdm_descriptors, manager->fdm_next, (void *) descriptor); mokval = manager->fdm_next; int size = getSize(manager); int i = manager->fdm_next; while(i < size) { if(!getFileDescriptor(i, manager)) { manager->fdm_next = i; break; } manager->fdm_next = i + 1; i++; } descriptor->fdopen = descriptor->fdopen + 1; } return mokval; }
/* * static void startMethodTracingNative(String traceFileName, * FileDescriptor fd, int bufferSize, int flags) * * Start method trace profiling. * * If both "traceFileName" and "fd" are null, the result will be sent * directly to DDMS. (The non-DDMS versions of the calls are expected * to enforce non-NULL filenames.) */ static void Dalvik_dalvik_system_VMDebug_startMethodTracingNative(const u4* args, JValue* pResult) { StringObject* traceFileStr = (StringObject*) args[0]; Object* traceFd = (Object*) args[1]; int bufferSize = args[2]; int flags = args[3]; if (bufferSize == 0) { // Default to 8MB per the documentation. bufferSize = 8 * 1024 * 1024; } if (bufferSize < 1024) { dvmThrowException("Ljava/lang/IllegalArgumentException;", NULL); RETURN_VOID(); } char* traceFileName = NULL; if (traceFileStr != NULL) traceFileName = dvmCreateCstrFromString(traceFileStr); int fd = -1; if (traceFd != NULL) { int origFd = getFileDescriptor(traceFd); if (origFd < 0) RETURN_VOID(); fd = dup(origFd); if (fd < 0) { dvmThrowExceptionFmt("Ljava/lang/RuntimeException;", "dup(%d) failed: %s", origFd, strerror(errno)); RETURN_VOID(); } } dvmMethodTraceStart(traceFileName != NULL ? traceFileName : "[DDMS]", fd, bufferSize, flags, (traceFileName == NULL && fd == -1)); free(traceFileName); RETURN_VOID(); }
/** * Move the current position of a file handle, to be used for * subsequent read/write calls. * * The offset modifier can be: * - MB_SEEK_SET set the absolute seek position. * - MB_SEEK_CUR set the seek position based on the current offset. * - MB_SEEK_END set the seek position from the end of the file. * E.g. to seek to 2nd-to-last byte, use offset=-1. * * @param fd file handle, obtained with open() * @param offset new offset, can be positive/negative. * @param flags * @return new offset position on success, MICROBIT_NOT_SUPPORTED if the file system * is not intiialised, MICROBIT_INVALID_PARAMETER if the flag given is invalid * or the file handle is invalid. * * @code * MicroBitFileSystem f; * int fd = f.open("test.txt", MB_READ); * f.seek(fd, -100, MB_SEEK_END); //100 bytes before end of file. * @endcode */ int MicroBitFileSystem::seek(int fd, int offset, uint8_t flags) { FileDescriptor *file; int position; // Protect against accidental re-initialisation if ((status & MBFS_STATUS_INITIALISED) == 0) return MICROBIT_NOT_SUPPORTED; // Ensure the file is open. file = getFileDescriptor(fd); if (file == NULL) return MICROBIT_INVALID_PARAMETER; // Flush any data in the writeback cache. writeBack(file); position = file->seek; if(flags == MB_SEEK_SET) position = offset; if(flags == MB_SEEK_END) position = file->length + offset; if (flags == MB_SEEK_CUR) position = file->seek + offset; if (position < 0 || (uint32_t)position > file->length) return MICROBIT_INVALID_PARAMETER; file->seek = position; return position; }
struct fdManager * clone(struct fdManager *manager) { struct fdManager *clone; clone = make_fdManager(); if(clone == NULL) { kprintf("clone failed\n"); return NULL; } int size; size = getSize(manager); clone->fdm_initialized = 1; int i = 0; while(i<size){ clone->fdm_next = i; addDescriptor(clone, getFileDescriptor(i, manager)); i++; } clone->fdm_next = manager->fdm_next; return clone; }
void DynamicResponseState::doRespond(){ IoWrite writer(getFileDescriptor()); writer.writeString(buildRespondHeaders()); execveCgiProgram(); }
void limServer( xcVirtualPacket_t * pVPkt, responseStruct * pResponse ) { /* return code for various function calls */ int rc = 0; /* holds information about our large ints to work with */ xcModMath_Int_t ints[MODM_MAXBUFS]; /* pointer to lim request header sent from host */ limReqHdr_t *pLimReqHdr =NULL; /* information about reply, which is C */ limReply_t replyHeader; /* number of integers to work with, default to maximum allowed */ int numInts = MODM_MAXBUFS; /* command to issue */ int cmd = 0; /* result buffer */ unsigned char *C_buffer = NULL; /* process id for this function when called */ pthread_t pid = pthread_self( ); /* initialization section */ memset( &replyHeader, 0x00, sizeof( limReply_t ) ); replyHeader.pid = pid; /* allocate buffer, send back dummy response on malloc error */ C_buffer = (unsigned char *)malloc(MODM_MAXBYTES); if( C_buffer == NULL ) { createDummyResponse( pResponse, LIMSERV_BAD_MALLOC, pid ); return;//hopefully we'll be able to malloc next time } /* initialize buffers, etc */ memset( &ints, 0x00, sizeof( ints ) ); memset( C_buffer, 0x00, MODM_MAXBYTES ); /* C is result */ ints[MODM_C].bytesize = MODM_MAXBYTES; ints[MODM_C].bitsize = MODM_MAXBITS; ints[MODM_C].buffer = C_buffer; /* grab pointer to request header from host */ pLimReqHdr = (limReqHdr_t *)&(pVPkt->data_start); /* find out what user wants to do */ cmd = pLimReqHdr->cmd; /* if operation = C = A MOD N, we only have 3 ints */ if( cmd == MODM_MOD ) numInts = 3;/*don't need B*/ cmd |= MODM_BIG;/*numbers come from host as big endian numbers*/ /* Calculate sizes and buffer location for A */ ints[MODM_A].bytesize = pLimReqHdr->aBytes; ints[MODM_A].bitsize = pLimReqHdr->aBits; ints[MODM_A].buffer = (unsigned char*)(&pLimReqHdr->aBuff); /* Calculate sizes and buffer location for B */ /* if cmd == MODM_MOD, B is sent as an empty buffer, and never used */ ints[MODM_B].bytesize = pLimReqHdr->bBytes; ints[MODM_B].bitsize = pLimReqHdr->bBits; ints[MODM_B].buffer = (unsigned char *)(&pLimReqHdr->bBuff); /* Calculate sizes and buffer location for N */ ints[MODM_N].bytesize = pLimReqHdr->nBytes; ints[MODM_N].bitsize = pLimReqHdr->nBits; ints[MODM_N].buffer = (unsigned char *)(&pLimReqHdr->nBuff); /* call the xCrypto modular math PKA service */ rc = xcModMath( getFileDescriptor(FD_PKA), cmd, numInts, ints); /* see if command completed successfully */ if( rc ) pResponse->status = LIMSERV_MODMATH_FAILED; else pResponse->status = LIMSERV_OK; /* result ( which is always C ), goes back to host */ if( pResponse->status == LIMSERV_OK ) { replyHeader.cBytes = ints[MODM_C].bytesize; replyHeader.cBits = ints[MODM_C].bitsize; pResponse->headerLength = sizeof(limReply_t); memcpy(pResponse->header, &replyHeader, pResponse->headerLength ); pResponse->dataLength = replyHeader.cBytes;//should be a multiple of 8 memcpy( pResponse->data, ints[MODM_C].buffer, pResponse->dataLength ); pResponse->userDef = 0; } else { createDummyResponse( pResponse, pResponse->status, pid ); } /* free buffer allocated by this function */ if( C_buffer ) free( C_buffer ); return; }
/* * Constructor! */ STORAGE::DynamicMemoryMappedFile::DynamicMemoryMappedFile(const char* fname) : backingFilename(fname) { // If the backing file does not exist, we need to create it bool createInitial; bool exists = fileExists(backingFilename); fHandle = getFileDescriptor(backingFilename, !exists); fd = _open_osfhandle((intptr_t)fHandle, _O_WRONLY); isNewFile = !exists; createInitial = !exists; if (!exists) { createInitial = true; mapSize = INITIAL_SIZE; } else { // Read file size from the host filesystem mapSize = GetFileSize(fHandle, NULL); logEvent(EVENT, "Detected map size of " + toString(mapSize)); } fs = (char*)mmap((void*)NULL, mapSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (fs == MAP_FAILED) { logEvent(ERROR, "Could not map backing file"); shutdown(FAILURE); } if (createInitial) { logEvent(EVENT, "Creating initial file structure"); SetFilePointer(fHandle, mapSize, NULL, FILE_BEGIN); SetEndOfFile(fHandle); SetFilePointer(fHandle, 0, NULL, FILE_BEGIN); writeHeader(); } else { logEvent(EVENT, "Reading file structure"); // Read header, perform sanity check, remap. const char *header = readHeader(); if (!sanityCheck(header)) { // Uhoh... logEvent(ERROR, "Sanity check failed"); shutdown(FAILURE); } // Extract version and size. short recordedVersion; memcpy(&recordedVersion, header + sizeof(SANITY), sizeof(VERSION)); // If the version differs than there could be some compatibility issues... if (recordedVersion != VERSION) { // What do? logEvent(ERROR, "Version mismatch"); shutdown(FAILURE); } #if EXTRATESTING // Verify size matches recorded size from header. If mismatched then // potentially we lost data on the last write. size_t msize; memcpy(&msize, header + sizeof(SANITY) + sizeof(VERSION), sizeof(msize)); // mmap over the previous region if (msize != mapSize) { logEvent(EVENT, "File size mismatch, read " + toString(msize) + ", should be " + toString(mapSize)); } #endif // Cleanup free((void*)header); } }
int sys_write(int fdesc,userptr_t ubuf,unsigned int nbytes,int *retval) { struct iovec iov; struct uio u; struct filedescriptor *fDescriptor; int res; int bytesWrite; if(!ubuf){ return EFAULT; } fDescriptor = getFileDescriptor(fdesc, curthread->t_fdManager); if(fDescriptor == NULL){ return EBADF; } DEBUG(DB_SYSCALL,"Syscall: write(%d,%x,%d)\n",fdesc,(unsigned int)ubuf,nbytes); /* only stdout and stderr writes are currently implemented */ if (!((fdesc==STDOUT_FILENO)||(fdesc==STDERR_FILENO))) { return EUNIMP; } KASSERT(curproc != NULL); KASSERT(curproc->console != NULL); KASSERT(curproc->p_addrspace != NULL); /* set up a uio structure to refer to the user program's buffer (ubuf) */ iov.iov_ubase = ubuf; iov.iov_len = nbytes; u.uio_iov = &iov; u.uio_iovcnt = 1; u.uio_offset = fDescriptor->fdoff; /* not needed for the console */ u.uio_resid = nbytes; u.uio_segflg = UIO_USERSPACE; u.uio_rw = UIO_WRITE; u.uio_space = curproc->p_addrspace; bytesWrite = u.uio_resid; lock_acquire(fDescriptor->fdlock); res = VOP_WRITE(fDescriptor->fdvnode,&u); lock_release(fDescriptor->fdlock); bytesWrite = u.uio_resid; if(bytesWrite==0){ return 0; } if (res) { return res; } /* pass back the number of bytes actually written */ *retval = nbytes - u.uio_resid; KASSERT(*retval >= 0); fDescriptor->fdoff += nbytes; return 0; }
void ResponseState::RespondError(const std::string errNum, const std::string shortMsg,const std::string longMsg){ IoWrite(getFileDescriptor()).writeString(buildRespondErrorHeaders(errNum,shortMsg)+ buildRespondErrorBody(errNum,shortMsg,longMsg)); }