예제 #1
0
inline
pipe::pipe(void)
{
    file_handle::handle_type hs[2];

#if defined(BOOST_PROCESS_WIN32_API)
    SECURITY_ATTRIBUTES sa;
    ZeroMemory(&sa, sizeof(sa));
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = FALSE;

    if (!::CreatePipe(&hs[0], &hs[1], &sa, 0))
        boost::throw_exception
            (system_error("boost::process::detail::pipe::pipe",
                          "CreatePipe failed", ::GetLastError()));
#else
    if (::pipe(hs) == -1)
        boost::throw_exception
            (system_error("boost::process::detail::pipe::pipe",
                          "pipe(2) failed", errno));
#endif

    m_read_end = file_handle(hs[0]);
    m_write_end = file_handle(hs[1]);
}
예제 #2
0
    /** 
     * Creates a new %pipe. 
     * 
     * The default pipe constructor allocates a new anonymous %pipe 
     * and assigns its ownership to the created pipe object. On Windows 
     * when the macro BOOST_PROCESS_WINDOWS_USE_NAMED_PIPE is defined 
     * a named pipe is created. This is required if asynchronous I/O 
     * should be used as asynchronous I/O is only supported by named 
     * pipes on Windows. 
     * 
     * \throw boost::system::system_error If the anonymous %pipe 
     *        creation fails. 
     */ 
    pipe() 
    { 
        file_handle::handle_type hs[2]; 

#if defined(BOOST_POSIX_API) 
        if (::pipe(hs) == -1) 
            boost::throw_exception(boost::system::system_error(boost::system::error_code(errno, boost::system::get_system_category()), "boost::process::detail::pipe::pipe: pipe(2) failed")); 
#elif defined(BOOST_WINDOWS_API) 
        SECURITY_ATTRIBUTES sa; 
        ZeroMemory(&sa, sizeof(sa)); 
        sa.nLength = sizeof(sa); 
        sa.lpSecurityDescriptor = NULL; 
        sa.bInheritHandle = FALSE; 

#  if defined(BOOST_PROCESS_WINDOWS_USE_NAMED_PIPE) 
        static unsigned int nextid = 0; 
        std::string pipe = "\\\\.\\pipe\\boost_process_" + boost::lexical_cast<std::string>(::GetCurrentProcessId()) + "_" + boost::lexical_cast<std::string>(nextid++); 
        hs[0] = ::CreateNamedPipeA(pipe.c_str(), PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, 0, 1, 8192, 8192, 0, &sa); 
        if (hs[0] == INVALID_HANDLE_VALUE) 
            boost::throw_exception(boost::system::system_error(::GetLastError(), boost::system::system_category(), "boost::process::detail::pipe::pipe: CreateNamedPipe failed")); 
        hs[1] = ::CreateFileA(pipe.c_str(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); 
        if (hs[1] == INVALID_HANDLE_VALUE) 
            boost::throw_exception(boost::system::system_error(::GetLastError(), boost::system::system_category(), "boost::process::detail::pipe::pipe: CreateFile failed")); 

        OVERLAPPED overlapped; 
        ZeroMemory(&overlapped, sizeof(overlapped)); 
        overlapped.hEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); 
        if (!overlapped.hEvent) 
            boost::throw_exception(boost::system::system_error(::GetLastError(), boost::system::system_category(), "boost::process::detail::pipe::pipe: CreateEvent failed")); 
        BOOL b = ::ConnectNamedPipe(hs[0], &overlapped); 
        if (!b) 
        { 
            if (::GetLastError() == ERROR_IO_PENDING) 
            { 
                if (::WaitForSingleObject(overlapped.hEvent, INFINITE) == WAIT_FAILED) 
                { 
                    ::CloseHandle(overlapped.hEvent); 
                    boost::throw_exception(boost::system::system_error(::GetLastError(), boost::system::system_category(), "boost::process::detail::pipe::pipe: WaitForSingleObject failed")); 
                } 
            } 
            else if (::GetLastError() != ERROR_PIPE_CONNECTED) 
            { 
                ::CloseHandle(overlapped.hEvent); 
                boost::throw_exception(boost::system::system_error(::GetLastError(), boost::system::system_category(), "boost::process::detail::pipe::pipe: ConnectNamedPipe failed")); 
            } 
        } 
        ::CloseHandle(overlapped.hEvent); 
#  else 
        if (!::CreatePipe(&hs[0], &hs[1], &sa, 0)) 
            boost::throw_exception(boost::system::system_error(::GetLastError(), boost::system::system_category(), "boost::process::detail::pipe::pipe: CreatePipe failed")); 
#  endif 
#endif 

        read_end_ = file_handle(hs[0]); 
        write_end_ = file_handle(hs[1]); 
    } 
예제 #3
0
	file_view file_view_pool::open_file(storage_index_t st, std::string const& p
		, file_index_t const file_index, file_storage const& fs
		, open_mode_t const m)
	{
		// potentially used to hold a reference to a file object that's
		// about to be destructed. If we have such object we assign it to
		// this member to be destructed after we release the std::mutex. On some
		// operating systems (such as OSX) closing a file may take a long
		// time. We don't want to hold the std::mutex for that.
		std::shared_ptr<file_mapping> defer_destruction;

		std::unique_lock<std::mutex> l(m_mutex);

		TORRENT_ASSERT(is_complete(p));
		auto& key_view = m_files.get<0>();
		auto const i = key_view.find(file_id{st, file_index});
		if (i != key_view.end())
		{
			key_view.modify(i, [&](file_entry& e)
			{
				e.last_use = aux::time_now();

				// make sure the write bit is set if we asked for it
				// it's OK to use a read-write file if we just asked for read. But if
				// we asked for write, the file we serve back must be opened in write
				// mode
				if (!(e.mode & open_mode::write) && (m & open_mode::write))
				{
					defer_destruction = std::move(e.mapping);
					e.mapping = std::make_shared<file_mapping>(
						file_handle(fs.file_path(file_index, p)
							, fs.file_size(file_index), m), m
						, fs.file_size(file_index));
					e.mode = m;
				}
			});

			auto& lru_view = m_files.get<1>();
			lru_view.relocate(m_files.project<1>(i), lru_view.begin());

			return i->mapping->view();
		}

		if (int(m_files.size()) >= m_size - 1)
		{
			// the file cache is at its maximum size, close
			// the least recently used file
			remove_oldest(l);
		}

		l.unlock();
		file_entry e({st, file_index}, fs.file_path(file_index, p), m
			, fs.file_size(file_index));
		auto ret = e.mapping->view();

		l.lock();
		auto& key_view2 = m_files.get<0>();
		key_view2.insert(std::move(e));
		return ret;
	}
예제 #4
0
/**
 * @brief	boost::shared_ptr 로 HANDLE 처리하기 #1 (이렇게 사용하면 안됨!!)
 * @param	
 * @see		
 * @remarks	
 * @code		
 * @endcode	
 * @return	
**/
bool boost_shared_ptr_handle_01()
{	
	boost::shared_ptr< boost::remove_pointer<HANDLE>::type > file_handle(
		open_file_to_read(L"c:\\windows\\system32\\drivers\\etc\\hosts"), 
		CloseHandle
		);
	if (INVALID_HANDLE_VALUE == file_handle.get()) 
	{
		return false;
	}
	
	DWORD bytes_read=0;
	unsigned char buffer[128]={0};
	if (!ReadFile(file_handle.get(), buffer, 128, &bytes_read, NULL)) return false;
	log_msg "ReadFile, buffer = %S", buffer log_end

	file_handle.reset();	//!

	//> CloseHandle() 이 호출되었을테니... ReadFile() 은 실패해야 하고, 
	//> GetLastError() == ERROR_INVALID_HANDLE 이어야 함
	if (TRUE == ReadFile(file_handle.get(), buffer, 128, &bytes_read, NULL)) return false;
	if (ERROR_INVALID_HANDLE != GetLastError()) return false;
	
	return true;
}
예제 #5
0
    /** 
     * Duplicates an open native file handle. 
     * 
     * Given a native file handle \a h1, this routine duplicates it so 
     * that it ends up being identified by the native file handle \a h2 
     * and returns a new \a file_handle owning \a h2. 
     * 
     * This operation is only available in POSIX systems. 
     * 
     * \pre The native file handle \a h1 is open. 
     * \pre The native file handle \a h2 is valid (non-negative). 
     * \post The native file handle \a h1 is closed. 
     * \post The native file handle \a h2 is the same as the old \a h1 
     *       from the operating system's point of view. 
     * \return A new \a file_handle object that owns \a h2. 
     * \throw boost::system::system_error If dup2() fails. 
     */ 
    static file_handle posix_dup(int h1, int h2) 
    { 
        if (::dup2(h1, h2) == -1) 
            boost::throw_exception(boost::system::system_error(boost::system::error_code(errno, boost::system::get_system_category()), "boost::process::detail::file_handle::posix_dup: dup2(2) failed")); 

        return file_handle(h2); 
    } 
예제 #6
0
static int file_lock(lua_State *L,
                     FILE *f, const char *mode, long offset, long length)
{
  static const ULARGE_INTEGER zero_len;
  static const OVERLAPPED zero_ov;
  HANDLE h = file_handle(f);
  ULARGE_INTEGER len = zero_len;
  OVERLAPPED ov = zero_ov;
  DWORD flags = 0;
  BOOL ret;
  if (length) len.LowPart = length;
  else len.LowPart = len.HighPart = -1;
  ov.Offset = offset;
  switch (*mode) {
    case 'w':
      flags = LOCKFILE_EXCLUSIVE_LOCK;
      /*FALLTHRU*/
    case 'r':
      flags |= LOCKFILE_FAIL_IMMEDIATELY;
      ret = LockFileEx(h, flags, 0, len.LowPart, len.HighPart, &ov);
      break;
    case 'u':
      ret = UnlockFileEx(h, 0, len.LowPart, len.HighPart, &ov);
      break;
    default:
      return luaL_error(L, "invalid mode");
  }
  if (!ret)
    return push_error(L);
  /* return the file */
  lua_settop(L, 1);
  return 1;
}
bool ofxCameraSequenceRecorder::createNewTimeStampDirectory(){

	ofSetDataPathRoot("./data/"); // relative to data

    folder_name =
    "capture-"+ofToString(ofGetYear())
    +ofToString(ofGetMonth())
    +ofToString(ofGetDay())+"-"
    +ofToString(ofGetHours())
    +ofToString(ofGetMinutes())
    +ofToString(ofGetSeconds());

   string dir = ofToDataPath(folder_name);
   cout << "\n\nCreating new directory for capture: " << dir << endl;

   File file_handle(dir);
   bool success = false;
   try{
      success = file_handle.createDirectory();
   }catch( Poco::Exception &except ){
      ofLog(OF_LOG_ERROR, "Could not make directory");
      return false;
   }

   if(success==false)ofLog(OF_LOG_WARNING, "Could not make directory because it already exists");
   return success;

}
예제 #8
0
    /** 
     * Duplicates the \a h native file handle. 
     * 
     * Given a native file handle \a h, this routine constructs a new 
     * \a file_handle object that owns a new duplicate of \a h. The 
     * duplicate's inheritable flag is set to the value of \a inheritable. 
     * 
     * This operation is only available in Windows systems. 
     * 
     * \pre The native file handle \a h is valid. 
     * \return A file handle owning a duplicate of \a h. 
     * \throw boost::system::system_error If DuplicateHandle() fails. 
     */ 
    static file_handle win32_dup(HANDLE h, bool inheritable) 
    { 
        HANDLE h2; 
        if (!::DuplicateHandle(::GetCurrentProcess(), h, ::GetCurrentProcess(), &h2, 0, inheritable ? TRUE : FALSE, DUPLICATE_SAME_ACCESS)) 
            boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::file_handle::win32_dup: DuplicateHandle failed")); 

        return file_handle(h2); 
    } 
예제 #9
0
static void get_redirect(lua_State *L,
                         int idx, const char *stdname, struct spawn_params *p)
{
  lua_getfield(L, idx, stdname);
  if (!lua_isnil(L, -1))
    spawn_param_redirect(p, stdname, file_handle(check_file(L, -1, stdname)));
  lua_pop(L, 1);
}
예제 #10
0
int FileDecoder::get_bytes_raw(address dest_address, int count) {
  OsFile_Handle handle = file_handle();
  GUARANTEE(handle != NULL, "What are we reading from?");

  int pos = file_pos();
  OsFile_seek(handle, pos, SEEK_SET);
  int bytes_read = OsFile_read(handle, dest_address, 1, count);
  set_file_pos(pos + bytes_read);
  return bytes_read;
}
예제 #11
0
inline
file_handle
file_handle::posix_dup(int h1, int h2)
{
    if (::dup2(h1, h2) == -1)
        boost::throw_exception
            (system_error("boost::process::detail::file_handle::posix_dup",
                          "dup2(2) failed", errno));

    return file_handle(h2);
}
예제 #12
0
ReturnOop FileDecoder::read_completely(JVM_SINGLE_ARG_TRAPS) {
  // try ...
  ReturnOop result = read_completely0(JVM_SINGLE_ARG_NO_CHECK);

  // finally ...
  if (flags() & MUST_CLOSE_FILE) {
    OsFile_close(file_handle());
  }

  // return
  return result;
}
예제 #13
0
 void PcxFontInfo::initWidths(const std::string& binPath, int textureWidth)
 {
     FAIO::FAFileObject file_handle(binPath);
     std::vector<unsigned char> buf(file_handle.FAsize());
     file_handle.FAfread(buf.data(), 1, buf.size());
     for (int i = 0; i < charCount; ++i)
     {
         widthPx[i] = buf[i + 2];
         uvWidth[i] = (widthPx[i] + 0.0) / textureWidth;
     }
     widthPx[' '] = buf[0];
 }
예제 #14
0
inline
file_handle
file_handle::win32_dup(HANDLE h, bool inheritable)
{
    HANDLE h2;
    if (::DuplicateHandle(::GetCurrentProcess(), h,
                          ::GetCurrentProcess(), &h2,
                          0, inheritable ? TRUE : FALSE,
                          DUPLICATE_SAME_ACCESS) == 0)
        boost::throw_exception
            (system_error("boost::process::detail::file_handle::win32_dup",
                          "DuplicateHandle failed", ::GetLastError()));

    return file_handle(h2);
}
예제 #15
0
/**
 * @brief	boost::shared_ptr 로 HANDLE 처리하기 #3
 * @brief	file_hanele 이 NULL 인 경우에 대한 처리
 * @param	
 * @see		
 * @remarks	
 * @code		
 * @endcode	
 * @return	
**/
bool boost_shared_ptr_handle_03()
{
	typedef boost::shared_ptr< boost::remove_pointer<HANDLE>::type > shared_handle;
	shared_handle file_handle (
		open_file_to_read(L"c:\\windows\\system32\\drivers\\etc\\hosts\\file_doesnot_exists"), 
		MyCloseHandle
		);
	if (INVALID_HANDLE_VALUE == file_handle.get()) 
	{
		file_handle.reset();
		return true;
	}

	return false;	// never reach here
}
예제 #16
0
파일: penult.c 프로젝트: nbaer/challenges
int main(int argc, char *argv[])
{
	int ret;

	if(argc == 2) {
		ret = file_handle(argv[1]);
		return ret;
	} else if(argc > 2) {
		printf("Too many arguments.\n");
		return 1;
	} else {
		printf("Not enough arguments.\n");
		return 1;
	}
}
예제 #17
0
/* pathname/file [entry] -- entry */
static int ex_dirent(lua_State *L)
{
  int isdir;
  lua_Number size;
  DWORD attr;
  switch (lua_type(L, 1)) {
  default: return luaL_typerror(L, 1, "file or pathname");
  case LUA_TSTRING: {
    const char *name = lua_tostring(L, 1);
    attr = GetFileAttributes(name);
    if (attr == (DWORD)-1)
      return push_error(L);
    isdir = attr & FILE_ATTRIBUTE_DIRECTORY;
    if (isdir)
      size = 0;
    else
      size = get_file_size(name);
    } break;
  case LUA_TUSERDATA: {
    FILE *f = check_file(L, 1, NULL);
    BY_HANDLE_FILE_INFORMATION info;
    if (!GetFileInformationByHandle(file_handle(f), &info))
      return push_error(L);
    attr = info.dwFileAttributes;
    isdir = attr & FILE_ATTRIBUTE_DIRECTORY;
    size = qword_to_number(info.nFileSizeHigh, info.nFileSizeLow);
    } break;
  }
  if (lua_type(L, 2) != LUA_TTABLE) {
    lua_settop(L, 1);
    new_dirent(L);
  }
  else {
    lua_settop(L, 2);
  }
  if (isdir)
    lua_pushliteral(L, "directory");
  else
    lua_pushliteral(L, "file");
  lua_setfield(L, 2, "type");
  lua_pushnumber(L, size);
  lua_setfield(L, 2, "size");
  return 1;
}
예제 #18
0
파일: retro.c 프로젝트: crcx/retroforth
void vm_process(VM *vm) {
  int a, b, opcode;
  opcode = vm->image[vm->ip];

  switch(opcode) {
    case VM_NOP:
         break;
    case VM_LIT:
         vm->sp++;
         vm->ip++;
         TOS = vm->image[vm->ip];
         break;
    case VM_DUP:
         vm->sp++;
         vm->data[vm->sp] = NOS;
         break;
    case VM_DROP:
         DROP
         break;
    case VM_SWAP:
         a = TOS;
         TOS = NOS;
         NOS = a;
         break;
    case VM_PUSH:
         vm->rsp++;
         TORS = TOS;
         DROP
         break;
    case VM_POP:
         vm->sp++;
         TOS = TORS;
         vm->rsp--;
         break;
    case VM_CALL:
         vm->ip++;
         vm->rsp++;
         TORS = vm->ip;
         vm->ip = vm->image[vm->ip] - 1;
         if (vm->ip < 0)
           vm->ip = IMAGE_SIZE;
         else {
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
         }
         break;
    case VM_JUMP:
         vm->ip++;
         vm->ip = vm->image[vm->ip] - 1;
         if (vm->ip < 0)
           vm->ip = IMAGE_SIZE;
         else {
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
         }
         break;
    case VM_RETURN:
         vm->ip = TORS;
         vm->rsp--;
         break;
    case VM_GT_JUMP:
         vm->ip++;
         if(NOS > TOS)
           vm->ip = vm->image[vm->ip] - 1;
         DROP DROP
         break;
    case VM_LT_JUMP:
         vm->ip++;
         if(NOS < TOS)
           vm->ip = vm->image[vm->ip] - 1;
         DROP DROP
         break;
    case VM_NE_JUMP:
         vm->ip++;
         if(TOS != NOS)
           vm->ip = vm->image[vm->ip] - 1;
         DROP DROP
         break;
    case VM_EQ_JUMP:
         vm->ip++;
         if(TOS == NOS)
           vm->ip = vm->image[vm->ip] - 1;
         DROP DROP
         break;
    case VM_FETCH:
         TOS = vm->image[TOS];
         break;
    case VM_STORE:
         vm->image[TOS] = NOS;
         DROP DROP
         break;
    case VM_ADD:
         NOS += TOS;
         DROP
         break;
    case VM_SUB:
         NOS -= TOS;
         DROP
         break;
    case VM_MUL:
         NOS *= TOS;
         DROP
         break;
    case VM_DIVMOD:
         a = TOS;
         b = NOS;
         TOS = b / a;
         NOS = b % a;
         break;
    case VM_AND:
         a = TOS;
         b = NOS;
         DROP
         TOS = a & b;
         break;
    case VM_OR:
         a = TOS;
         b = NOS;
         DROP
         TOS = a | b;
         break;
    case VM_XOR:
         a = TOS;
         b = NOS;
         DROP
         TOS = a ^ b;
         break;
    case VM_SHL:
         a = TOS;
         b = NOS;
         DROP
         TOS = b << a;
         break;
    case VM_SHR:
         a = TOS;
         b = NOS;
         DROP
         TOS = b >>= a;
         break;
    case VM_ZERO_EXIT:
         if (TOS == 0) {
           DROP
           vm->ip = TORS;
           vm->rsp--;
         }
         break;
    case VM_INC:
         TOS += 1;
         break;
    case VM_DEC:
         TOS -= 1;
         break;
    case VM_IN:
         a = TOS;
         TOS = vm->ports[a];
         vm->ports[a] = 0;
         break;
    case VM_OUT:
         vm->ports[0] = 0;
         vm->ports[TOS] = NOS;
         DROP DROP
         break;
    case VM_WAIT:
         if (vm->ports[0] == 1)
           break;

         /* Input */
         if (vm->ports[0] == 0 && vm->ports[1] == 1) {
           vm->ports[1] = dev_getch();
           vm->ports[0] = 1;
         }

         /* Output (character generator) */
         if (vm->ports[2] == 1) {
           dev_putch(TOS); DROP
           vm->ports[2] = 0;
           vm->ports[0] = 1;
         }

         if (vm->ports[4] != 0) {
           vm->ports[0] = 1;
           switch (vm->ports[4]) {
             case  1: vm_save_image(vm, vm->filename);
                      vm->ports[4] = 0;
                      break;
             case  2: file_add(vm);
                      vm->ports[4] = 0;
                      break;
             case -1: vm->ports[4] = file_handle(vm);
                      break;
             case -2: vm->ports[4] = file_readc(vm);
                      break;
             case -3: vm->ports[4] = file_writec(vm);
                      break;
             case -4: vm->ports[4] = file_closehandle(vm);
                      break;
             case -5: vm->ports[4] = file_getpos(vm);
                      break;
             case -6: vm->ports[4] = file_seek(vm);
                      break;
             case -7: vm->ports[4] = file_size(vm);
                      break;
             default: vm->ports[4] = 0;
           }
         }

         /* Capabilities */
         if (vm->ports[5] != 0) {
           vm->ports[0] = 1;
           switch(vm->ports[5]) {
             case -1:  vm->ports[5] = IMAGE_SIZE;
                       break;
             case -2:  vm->ports[5] = 0;
                       break;
             case -3:  vm->ports[5] = 0;
                       break;
             case -4:  vm->ports[5] = 0;
                       break;
             case -5:  vm->ports[5] = vm->sp;
                       break;
             case -6:  vm->ports[5] = vm->rsp;
                       break;
             case -7:  vm->ports[5] = 0;
                       break;
             case -8:  vm->ports[5] = time(NULL);
                       break;
             case -9:  vm->ports[5] = 0;
                       vm->ip = IMAGE_SIZE;
                       break;
             default:  vm->ports[5] = 0;
           }
         }

         if (vm->ports[8] != 0) {
           vm->ports[0] = 1;
           switch (vm->ports[8]) {
             case -1: rsocket(vm);
                      vm->ports[8] = 0;
                      break;
             case -2: rbind(vm);
                      vm->ports[8] = 0;
                      break;
             case -3: rlisten(vm);
                      vm->ports[8] = 0;
                      break;
             case -4: raccept(vm);
                      vm->ports[8] = 0;
                      break;
             case -5: rclose(vm);
                      vm->ports[8] = 0;
                      break;
             case -6: rsend(vm);
                      vm->ports[8] = 0;
                      break;
             case -7: rrecv(vm);
                      vm->ports[8] = 0;
                      break;
             case -8: rconnect(vm);
                      vm->ports[8] = 0;
                      break;
             default: vm->ports[8] = 0;
           }
           vm->ports[8] = 0;
         }
         break;
    default:
         vm->rsp++;
         TORS = vm->ip;
         vm->ip = vm->image[vm->ip] - 1;

         if (vm->ip < 0)
           vm->ip = IMAGE_SIZE;
         else {
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
         }
         break;
  }
  vm->ports[3] = 1;
}
예제 #19
0
	file_handle file_pool::open_file(storage_index_t st, std::string const& p
		, file_index_t const file_index, file_storage const& fs, int m, error_code& ec)
	{
		// potentially used to hold a reference to a file object that's
		// about to be destructed. If we have such object we assign it to
		// this member to be destructed after we release the std::mutex. On some
		// operating systems (such as OSX) closing a file may take a long
		// time. We don't want to hold the std::mutex for that.
		file_handle defer_destruction;

		std::unique_lock<std::mutex> l(m_mutex);

#if TORRENT_USE_ASSERTS
		// we're not allowed to open a file
		// from a deleted storage!
		TORRENT_ASSERT(std::find(m_deleted_storages.begin(), m_deleted_storages.end()
			, std::make_pair(fs.name(), static_cast<void const*>(&fs)))
			== m_deleted_storages.end());
#endif

		TORRENT_ASSERT(is_complete(p));
		TORRENT_ASSERT((m & file::rw_mask) == file::read_only
			|| (m & file::rw_mask) == file::read_write);
		auto const i = m_files.find(std::make_pair(st, file_index));
		if (i != m_files.end())
		{
			lru_file_entry& e = i->second;
			e.last_use = aux::time_now();

			// if we asked for a file in write mode,
			// and the cached file is is not opened in
			// write mode, re-open it
			if ((((e.mode & file::rw_mask) != file::read_write)
				&& ((m & file::rw_mask) == file::read_write))
				|| (e.mode & file::random_access) != (m & file::random_access))
			{
				file_handle new_file = std::make_shared<file>();

				std::string full_path = fs.file_path(file_index, p);
				if (!new_file->open(full_path, m, ec))
					return file_handle();
#ifdef TORRENT_WINDOWS
				if (m_low_prio_io)
					set_low_priority(new_file);
#endif

				TORRENT_ASSERT(new_file->is_open());
				defer_destruction = std::move(e.file_ptr);
				e.file_ptr = std::move(new_file);
				e.mode = m;
			}
			return e.file_ptr;
		}

		lru_file_entry e;
		e.file_ptr = std::make_shared<file>();
		if (!e.file_ptr)
		{
			ec = error_code(boost::system::errc::not_enough_memory, generic_category());
			return file_handle();
		}
		std::string full_path = fs.file_path(file_index, p);
		if (!e.file_ptr->open(full_path, m, ec))
			return file_handle();
#ifdef TORRENT_WINDOWS
		if (m_low_prio_io)
			set_low_priority(e.file_ptr);
#endif
		e.mode = m;
		file_handle file_ptr = e.file_ptr;
		m_files.insert(std::make_pair(std::make_pair(st, file_index), e));
		TORRENT_ASSERT(file_ptr->is_open());

		if (int(m_files.size()) >= m_size)
		{
			// the file cache is at its maximum size, close
			// the least recently used (lru) file from it
			remove_oldest(l);
		}
		return file_ptr;
	}
예제 #20
0
inline PROCESS_INFORMATION win32_start(const Executable &exe, const Arguments &args, const environment &env, stream_info &infoin, stream_info &infoout, stream_info &infoerr, const win32_setup &setup) 
{ 
    file_handle chin, chout, cherr; 

    BOOST_ASSERT(setup.startupinfo->cb >= sizeof(STARTUPINFOA)); 
    BOOST_ASSERT(!(setup.startupinfo->dwFlags & STARTF_USESTDHANDLES)); 

    boost::scoped_ptr<STARTUPINFOA> si(new STARTUPINFOA); 
    ::CopyMemory(si.get(), setup.startupinfo, sizeof(*setup.startupinfo)); 
    si->dwFlags |= STARTF_USESTDHANDLES; 

    switch (infoin.type_) 
    { 
    case stream_info::close: 
        { 
            break; 
        } 
    case stream_info::inherit: 
        { 
            chin = file_handle::win32_std(STD_INPUT_HANDLE, true); 
            break; 
        } 
    case stream_info::use_file: 
        { 
            HANDLE h = ::CreateFileA(infoin.file_.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
            if (h == INVALID_HANDLE_VALUE) 
                boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::win32_start: CreateFile failed")); 
            chin = file_handle(h); 
            break; 
        } 
    case stream_info::use_handle: 
        { 
            chin = infoin.handle_; 
            chin.win32_set_inheritable(true); 
            break; 
        } 
    case stream_info::use_pipe: 
        { 
            infoin.pipe_->rend().win32_set_inheritable(true); 
            chin = infoin.pipe_->rend(); 
            break; 
        } 
    default: 
        { 
            BOOST_ASSERT(false); 
            break; 
        } 
    } 

    si->hStdInput = chin.valid() ? chin.get() : INVALID_HANDLE_VALUE; 

    switch (infoout.type_) 
    { 
    case stream_info::close: 
        { 
            break; 
        } 
    case stream_info::inherit: 
        { 
            chout = file_handle::win32_std(STD_OUTPUT_HANDLE, true); 
            break; 
        } 
    case stream_info::use_file: 
        { 
            HANDLE h = ::CreateFileA(infoout.file_.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 
            if (h == INVALID_HANDLE_VALUE) 
                boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::win32_start: CreateFile failed")); 
            chout = file_handle(h); 
            break; 
        } 
    case stream_info::use_handle: 
        { 
            chout = infoout.handle_; 
            chout.win32_set_inheritable(true); 
            break; 
        } 
    case stream_info::use_pipe: 
        { 
            infoout.pipe_->wend().win32_set_inheritable(true); 
            chout = infoout.pipe_->wend(); 
            break; 
        } 
    default: 
        { 
            BOOST_ASSERT(false); 
            break; 
        } 
    } 

    si->hStdOutput = chout.valid() ? chout.get() : INVALID_HANDLE_VALUE; 

    switch (infoerr.type_) 
    { 
    case stream_info::close: 
        { 
            break; 
        } 
    case stream_info::inherit: 
        { 
            cherr = file_handle::win32_std(STD_ERROR_HANDLE, true); 
            break; 
        } 
    case stream_info::redirect: 
        { 
            BOOST_ASSERT(infoerr.desc_to_ == 1); 
            BOOST_ASSERT(chout.valid()); 
            cherr = file_handle::win32_dup(chout.get(), true); 
            break; 
        } 
    case stream_info::use_file: 
        { 
            HANDLE h = ::CreateFileA(infoerr.file_.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 
            if (h == INVALID_HANDLE_VALUE) 
                boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::win32_start: CreateFile failed")); 
            cherr = file_handle(h); 
            break; 
        } 
    case stream_info::use_handle: 
        { 
            cherr = infoerr.handle_; 
            cherr.win32_set_inheritable(true); 
            break; 
        } 
    case stream_info::use_pipe: 
        { 
            infoerr.pipe_->wend().win32_set_inheritable(true); 
            cherr = infoerr.pipe_->wend(); 
            break; 
        } 
    default: 
        { 
            BOOST_ASSERT(false); 
            break; 
        } 
    } 

    si->hStdError = cherr.valid() ? cherr.get() : INVALID_HANDLE_VALUE; 

    PROCESS_INFORMATION pi; 
    ::ZeroMemory(&pi, sizeof(pi)); 

    boost::shared_array<char> cmdline;

    boost::scoped_array<char> executable;
    // exe could be "", in which case call CreateProcess with NULL first argument
    if (exe.size()) {
        executable.reset(new char[exe.size() + 1]);
#if defined(__CYGWIN__) || defined(_SCL_SECURE_NO_DEPRECATE)
        ::strcpy(executable.get(), exe.c_str());
#else
        ::strcpy_s(executable.get(), exe.size() + 1, exe.c_str());
#endif
        cmdline = collection_to_win32_cmdline(args);
    }
    else if (args.size() == 1) {
        // No exe and just a single argument. Dont escape anything - pass it through unchanged.
        std::string const &c = args.front();
        cmdline.reset(new char[c.size() + 1]);
#if defined(__CYGWIN__) || defined(_SCL_SECURE_NO_DEPRECATE) 
        ::strcpy(cmdline.get(), c.c_str());
#else 
        ::strcpy_s(cmdline.get(), c.size() + 1, c.c_str());
#endif 
    }
    else {
        cmdline = collection_to_win32_cmdline(args);
    }

    boost::scoped_array<char> workdir(new char[setup.work_directory.size() + 1]); 
#if defined(__CYGWIN__) || defined(_SCL_SECURE_NO_DEPRECATE) 
    ::strcpy(workdir.get(), setup.work_directory.c_str()); 
#else 
    ::strcpy_s(workdir.get(), setup.work_directory.size() + 1, setup.work_directory.c_str()); 
#endif 

    boost::shared_array<char> envstrs = environment_to_win32_strings(env); 

    if (!::CreateProcessA(executable.get(), cmdline.get(), NULL, NULL, TRUE, 0, envstrs.get(), workdir.get(), si.get(), &pi)) 
        boost::throw_exception(boost::system::system_error(boost::system::error_code(::GetLastError(), boost::system::get_system_category()), "boost::process::detail::win32_start: CreateProcess failed")); 

    return pi; 
} 
예제 #21
0
	file_handle file_pool::open_file(void* st, std::string const& p
		, int file_index, file_storage const& fs, int m, error_code& ec)
	{
		// potentially used to hold a reference to a file object that's
		// about to be destructed. If we have such object we assign it to
		// this member to be destructed after we release the mutex. On some
		// operating systems (such as OSX) closing a file may take a long
		// time. We don't want to hold the mutex for that.
		file_handle defer_destruction;

		mutex::scoped_lock l(m_mutex);

#if TORRENT_USE_ASSERTS
		// we're not allowed to open a file
		// from a deleted storage!
		TORRENT_ASSERT(std::find(m_deleted_storages.begin(), m_deleted_storages.end(), std::make_pair(fs.name(), (void const*)&fs))
			== m_deleted_storages.end());
#endif

		TORRENT_ASSERT(st != 0);
		TORRENT_ASSERT(is_complete(p));
		TORRENT_ASSERT((m & file::rw_mask) == file::read_only
			|| (m & file::rw_mask) == file::read_write);
		file_set::iterator i = m_files.find(std::make_pair(st, file_index));
		if (i != m_files.end())
		{
			lru_file_entry& e = i->second;
			e.last_use = aux::time_now();

			if (e.key != st && ((e.mode & file::rw_mask) != file::read_only
				|| (m & file::rw_mask) != file::read_only))
			{
				// this means that another instance of the storage
				// is using the exact same file.
				ec = errors::file_collision;
				return file_handle();
			}

			e.key = st;
			// if we asked for a file in write mode,
			// and the cached file is is not opened in
			// write mode, re-open it
			if ((((e.mode & file::rw_mask) != file::read_write)
				&& ((m & file::rw_mask) == file::read_write))
				|| (e.mode & file::random_access) != (m & file::random_access))
			{
				// close the file before we open it with
				// the new read/write privilages, since windows may
				// file opening a file twice. However, since there may
				// be outstanding operations on it, we can't close the
				// file, we can only delete our reference to it.
				// if this is the only reference to the file, it will be closed
				defer_destruction = e.file_ptr;
				e.file_ptr = boost::make_shared<file>();

				std::string full_path = fs.file_path(file_index, p);
				if (!e.file_ptr->open(full_path, m, ec))
				{
					m_files.erase(i);
					return file_handle();
				}
#ifdef TORRENT_WINDOWS
				if (m_low_prio_io)
					set_low_priority(e.file_ptr);
#endif

				TORRENT_ASSERT(e.file_ptr->is_open());
				e.mode = m;
			}
			return e.file_ptr;
		}

		lru_file_entry e;
		e.file_ptr = boost::make_shared<file>();
		if (!e.file_ptr)
		{
			ec = error_code(ENOMEM, get_posix_category());
			return e.file_ptr;
		}
		std::string full_path = fs.file_path(file_index, p);
		if (!e.file_ptr->open(full_path, m, ec))
			return file_handle();
#ifdef TORRENT_WINDOWS
		if (m_low_prio_io)
			set_low_priority(e.file_ptr);
#endif
		e.mode = m;
		e.key = st;
		m_files.insert(std::make_pair(std::make_pair(st, file_index), e));
		TORRENT_ASSERT(e.file_ptr->is_open());

		file_handle file_ptr = e.file_ptr;

		// the file is not in our cache
		if ((int)m_files.size() >= m_size)
		{
			// the file cache is at its maximum size, close
			// the least recently used (lru) file from it
			remove_oldest(l);
		}
		return file_ptr;
	}
예제 #22
0
void populate_trouble_codes_list()
{
   char character;
   int i, j, min;
   char temp_buf[1024];
   TROUBLE_CODE *trouble_code;
   int count = get_number_of_codes();
   PACKFILE *code_def_file;

   if (count == 0)
      return;

   for (i = 0; i < count; i++)    // sort codes in ascending order
   {
      min = i;

      for (j = i+1; j < count; j++)
         if(strcmp(get_trouble_code(j)->code, get_trouble_code(min)->code) < 0)
            min = j;

      swap_codes(get_trouble_code(i), get_trouble_code(min));
   }
   
   for (trouble_code = trouble_codes; trouble_code; trouble_code = trouble_code->next)   // search for descriptions and solutions
   {
      // pass the letter (B, C, P, or U) to file_handle, which returns the file handle
      // if we reached EOF, or the file does not exist, go to the next DTC
      if ((code_def_file = file_handle(trouble_code->code[0])) == NULL)
         continue;

      while (TRUE)
      {
         j = 0;

         // copy DTC from file to temp_buf
         while (((character = pack_getc(code_def_file)) != FIELD_DELIMITER) && (character != RECORD_DELIMITER) && (character != EOF))
         {
            temp_buf[j] = character;
            j++;
         }
         temp_buf[j] = '\0';

         if (character == EOF) // reached end of file, break out of while()
            break;             // advance to next code

         if (strncmp(trouble_code->code, temp_buf, 5) == 0) // if we found the code,
         {
            if (character == RECORD_DELIMITER)  // reached end of record, no description or solution,
               break;                        // break out of while(), advance to next code

            j = 0;

            //copy description from file to temp_buf
            while (((character = pack_getc(code_def_file)) != FIELD_DELIMITER) && (character != RECORD_DELIMITER) && (character != EOF))
            {
               temp_buf[j] = character;
               j++;
            }
            temp_buf[j] = '\0';  // terminate string
            if (j > 0)
            {
               if (!(trouble_code->description = (char *)malloc(sizeof(char)*(j + 1 + ((trouble_code->pending) ? 10 : 0)))))
               {
                  sprintf(temp_error_buf, "Could not allocate enough memory for trouble code description [%i]", count);
                  fatal_error(temp_error_buf);
               }
               if (trouble_code->pending)
               {
                  strcpy(trouble_code->description, "[Pending]\n");
                  strcpy(trouble_code->description + 10, temp_buf);  // copy description from temp_buf
               }
               else
                  strcpy(trouble_code->description, temp_buf);  // copy description from temp_buf
            }

            if (character == FIELD_DELIMITER)   // if we have solution,
            {
               j = 0;

               // copy solution from file to temp_buf
               while (((character = pack_getc(code_def_file)) != RECORD_DELIMITER) && (character != EOF))
               {
                  temp_buf[j] = character;
                  j++;
               }
               temp_buf[j] = '\0';   // terminate string
               if (j > 0)
               {
                  if (!(trouble_code->solution = (char *)malloc(sizeof(char)*(j+1))))
                  {
                     sprintf(temp_error_buf, "Could not allocate enough memory for trouble code solution [%i]", count);
                     fatal_error(temp_error_buf);
                  }
                  strcpy(trouble_code->solution, temp_buf);  // copy solution from temp_buf
               }
            }
            break;  // break out of while(TRUE)
         }
         else
         {
            // skip to next record
            while (((character = pack_getc(code_def_file)) != RECORD_DELIMITER) && (character != EOF));

            if (character == EOF)
               break;   // break out of while(TRUE), advance to next code
         }
      } // end of while(TRUE)
   } // end of for() loop
   file_handle(0); // close the code definition file if it's still open
}
예제 #23
0
/// @brief 
bool 
FileInfoCache::file_util_get_hash(
	_In_ const wchar_t* file_path, 
	_Out_ std::string& md5, 
	_Out_ std::string& sha2)
{
	handle_ptr file_handle(
		CreateFileW(file_path,
					GENERIC_READ,
					FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
					NULL,
					OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL,
					NULL),
		[](HANDLE h) 
		{
			if (INVALID_HANDLE_VALUE != h)
			{
				CloseHandle(h);
			}
		});

    if (INVALID_HANDLE_VALUE == file_handle.get())
    {
        log_err
            "CreateFileW() failed. path=%ws, gle = %u",
            file_path, 
			GetLastError()
            log_end;
        return false; 
    }
    
    if (INVALID_SET_FILE_POINTER == SetFilePointer(file_handle.get(), 
												   0, 
												   NULL, 
												   FILE_BEGIN))
    {
        log_err
            "SetFilePointer() failed. path=%ws, gle = %u", 
			file_path, 
			GetLastError()
            log_end;
        return false;
    }

    uint8_t sha2_buf[32];
    MD5_CTX ctx_md5;
    sha256_ctx ctx_sha2;
    MD5Init(&ctx_md5, 0);
    sha256_begin(&ctx_sha2);

    const uint32_t read_buffer_size = 4096;
    uint8_t read_buffer[read_buffer_size];
    DWORD read = read_buffer_size;

    while (read_buffer_size == read)
    {
		if (FALSE == ::ReadFile(file_handle.get(),
								read_buffer,
								read_buffer_size,
								&read,
								NULL))
        {
            log_err
                "ReadFile() failed. path=%ws, gle = %u",
                file_path,
                GetLastError()
                log_end;
            return false;
        }

        if (0 != read)
        {
            MD5Update(&ctx_md5, read_buffer, read);
            sha256_hash(read_buffer, read, &ctx_sha2);
        }
    }

    MD5Final(&ctx_md5);
    sha256_end(sha2_buf, &ctx_sha2);

	//
	//	Hash 바이너리 버퍼를 hex 문자열로 변환
	//
	if (true != bin_to_hexa_fast(sizeof(ctx_md5.digest),
								 ctx_md5.digest,
								 false,
								 md5))
	{
		log_err "bin_to_hexa_fast() failed. " log_end;
		return false;
	}

	if (true != bin_to_hexa_fast(sizeof(sha2_buf), 
								 sha2_buf, 
								 false, 
								 sha2))
	{
		log_err "bin_to_hexa_fast() failed. " log_end;
		return false;
	}
    return true;
}