Пример #1
0
bool ibanBicStoragePlugin::setupDatabase(QSqlDatabase connection)
{
  // Get current version
  QSqlQuery query = QSqlQuery(connection);
  query.prepare("SELECT versionMajor FROM kmmPluginInfo WHERE iid = ?");
  query.bindValue(0, iid());
  if (!query.exec()) {
    qWarning("Could not execute query for ibanBicStoragePlugin: %s", qPrintable(query.lastError().text()));
    return false;
  }

  int currentVersion = 0;
  if (query.next())
    currentVersion = query.value(0).toInt();

  // Create database in it's most recent version if version is 0
  // (version 0 means the database was not installed)
  if (currentVersion == 0) {
    // If the database is recreated the table may be still there. So drop it if needed. No error handling needed
    // as this step is not necessary - only the creation is important.
    query.exec("DROP TABLE IF EXISTS kmmIbanBic;");

    if (!query.exec(
          "CREATE TABLE kmmIbanBic ("
          "  id varchar(32) NOT NULL PRIMARY KEY REFERENCES kmmPayeeIdentifier( id ) ON DELETE CASCADE ON UPDATE CASCADE,"
          "  iban varchar(32),"
          "  bic char(11) CHECK(length(bic) = 11 OR bic IS NULL),"
          "  name text"
          " );"
        )) {
      qWarning("Could not create table for ibanBicStoragePlugin: %s", qPrintable(query.lastError().text()));
      return false;
    }

    query.prepare("INSERT INTO kmmPluginInfo (iid, versionMajor, versionMinor, uninstallQuery) VALUES(?, ?, ?, ?)");
    query.bindValue(0, iid());
    query.bindValue(1, 1);
    query.bindValue(2, 0);
    query.bindValue(3, "DROP TABLE kmmIbanBic;");
    if (query.exec())
      return true;
    qWarning("Could not save plugin info for ibanBicStoragePlugin (%s): %s", qPrintable(iid()), qPrintable(query.lastError().text()));
    return false;
  }

  // Check if version is valid with this plugin
  switch (currentVersion) {
    case 1: return true;
  }

  return false;
}
Пример #2
0
JNIEXPORT jlong JNICALL Java_com4j_Native_getErrorInfo(
	JNIEnv* env, jclass __unused__, jlong pComObject, jlong iid1, jlong iid2) {

	MyGUID iid(iid1,iid2);

  try {
	  ISupportErrorInfoPtr p(reinterpret_cast<IUnknown*>(pComObject));
	  if(p==NULL)
		  return 0;	// not supported

	  HRESULT hr = p->InterfaceSupportsErrorInfo(iid);
	  if(FAILED(hr)) {
		  error(env,__FILE__,__LINE__,hr,"ISupportErrorInfo::InterfaceSupportsErrorInfo failed");
		  return 0;
	  }

	  if(hr!=S_OK)	return 0; // not supported

	  IErrorInfo* pError;
	  hr = GetErrorInfo(0,&pError);
	  if(FAILED(hr)) {
		  error(env,__FILE__,__LINE__,hr,"GetErrorInfo failed");
		  return 0;
	  }

	  // return the pointer
	  return reinterpret_cast<jlong>(pError);
  } catch (...) {
    // an exception occured. This might happen, if the automation server is not available due to a crash.
    return 0;
  }
  return 0;
}
Пример #3
0
static PyObject *PyCurrentItem(PyObject *self, PyObject *args)
{
	PyObject *obIID = NULL;
	if (!PyArg_ParseTuple(args, "|O:CurrentItem", &obIID))
		return NULL;

	nsIID iid(NS_GET_IID(nsISupports));
	if (obIID != NULL && !Py_nsIID::IIDFromPyObject(obIID, &iid))
		return NULL;
	nsIEnumerator *pI = GetI(self);
	if (pI==NULL)
		return NULL;

	nsISupports *pRet = nsnull;
	nsresult r;
	Py_BEGIN_ALLOW_THREADS;
	r = pI->CurrentItem(&pRet);
	Py_END_ALLOW_THREADS;
	if ( NS_FAILED(r) )
		return PyXPCOM_BuildPyException(r);
	if (obIID) {
		nsISupports *temp;
		Py_BEGIN_ALLOW_THREADS;
		r = pRet->QueryInterface(iid, (void **)&temp);
		pRet->Release();
		Py_END_ALLOW_THREADS;
		if ( NS_FAILED(r) ) {
			return PyXPCOM_BuildPyException(r);
		}
		pRet = temp;
	}
	return Py_nsISupports::PyObjectFromInterface(pRet, iid, PR_FALSE);
}
Пример #4
0
// Also saves sample information
void writeMDS(const std::string& file_name, const std::vector<Sample>& sample_names, const arma::mat& MDS)
{
   if (MDS.n_rows == sample_names.size())
   {
      MDS.save(file_name, arma::hdf5_binary);

      std::string sample_file_name = file_name + sample_suffix;
      std::ofstream sample_names_file(sample_file_name.c_str());

      // Write out the sample name order
      if (!sample_names_file)
      {
         std::cerr << "Could not write used sample names to " << sample_file_name << std::endl;
      }
      else
      {
         for (auto sample_it = sample_names.begin(); sample_it != sample_names.end(); ++sample_it)
         {
            sample_names_file << sample_it->iid() << std::endl;
         }
      }
   }
   else
   {
      throw std::logic_error("When writing matrix to " + file_name + " the number samples in the .pheno file did not match the number of columns or rows");
   }

}
SeasideCache::CacheItem *SeasideCache::itemById(const QContactId &id, bool)
{
    quint32 iid(internalId(id));
    if (instancePtr->m_cacheIndices.contains(iid)) {
        return &instancePtr->m_cache[instancePtr->m_cacheIndices[iid]];
    }
    return 0;
}
QContact SeasideCache::contactById(const ContactIdType &id)
{
#ifdef USING_QTPIM
    quint32 iid(internalId(id));
    return instancePtr->m_cache[instancePtr->m_cacheIndices[iid]].contact;
#else
    return instancePtr->m_cache[id - 1].contact;
#endif
}
Пример #7
0
void SthenoCore::createLocalServiceReplica(
        UUIDPtr& sid,
        ServiceParamsPtr& params,
        ServiceAbstractPtr& sPtr) throw (RuntimeException&, ServiceException&) {
    if (!isValid()) {
        throw RuntimeException(RuntimeException::INVALID_RUNTIME);
    }
    FaultTolerancePtr ftToleranceSvc;
    try {
        m_overlay->getFaultTolerance(ftToleranceSvc);
    } catch (OverlayException& ex) {
        throw RuntimeException(RuntimeException::INVALID_OVERLAY);
    }
    UUIDPtr iid(UUID::generateUUID());
    createServiceInstance(sid, iid, sPtr);
    //QoSResources* qos = sPtr->calculateQoSResources(params);    

    printf("INFO: createLocalServiceReplica() - SID=%s before open service!\n", sid->toString().c_str());
    QoSManagerInterface* qosManager = 0;
    if (m_reservationFlag) {
        UUIDPtr serviceCgroupUUID(UUID::generateUUID());
        String path = "service_" + sid->toString() + "_" + serviceCgroupUUID->toString();

        qosManager = m_serviceQosManager->createSubDomainQoSManager(path, 200, m_runtimePeriod);
        //String ftPath = "/FT";
        String ftPath = Cgroup::getSep();
        ftPath += "FT";
        //HierarchicalPath::appendPaths(path, "/FT");
        QoSManagerInterface* qosFTManager = 0;
        qosFTManager = qosManager->createSubDomainQoSManager(ftPath, 100, m_runtimePeriod);

        String servicePath = Cgroup::getSep();
        servicePath += "service";
        //HierarchicalPath::appendPaths(path, "/service");
        QoSManagerInterface* qosServiceManager = 0;
        qosServiceManager = qosManager->createSubDomainQoSManager(servicePath, 100, m_runtimePeriod);

        //String path = "service_" + sid->toString() + "_" + serviceCgroupUUID->toString();
        //qosManager = m_serviceQosManager->createSubDomainQoSManager(path, 10000, QoSManagerInterface::DEFAULT_PERIOD);
    }
    sPtr->open(params, ServiceAbstract::FT_REPLICA, qosManager);
    printf("INFO: createLocalServiceReplica() SID=%s after open service!\n", sid->toString().c_str());

    ServiceInstanceInfoPtr info;
    //UUIDPtr iid = sPtr->getIID();
    this->getInstanceOfService(sid, iid, info);
    MeshPtr meshPtr;
    try {
        getOverlay()->getMesh(meshPtr);
    } catch (OverlayException& ex) {
        throw RuntimeException(RuntimeException::INVALID_OVERLAY);
    }
    meshPtr->onServiceCreation(info);

}
Пример #8
0
JNIEXPORT jlong JNICALL Java_com4j_Native_queryInterface( JNIEnv* env, jclass __unused__,
	jlong pComObject, jlong iid1, jlong iid2 ) {
	
	MyGUID iid(iid1,iid2);
	void* p;

	HRESULT hr = toComObject(pComObject)->QueryInterface(iid,&p);
	if(FAILED(hr)) {
		return 0;
	}
	return reinterpret_cast<jlong>(p);
}
SeasideCache::CacheItem *SeasideCache::itemById(const ContactIdType &id, bool)
{
#ifdef USING_QTPIM
    quint32 iid(internalId(id));
    if (instancePtr->m_cacheIndices.contains(iid)) {
        return &instancePtr->m_cache[instancePtr->m_cacheIndices[iid]];
    }
#else
    if (id != 0 && id <= instancePtr->m_cache.count()) {
        return &instancePtr->m_cache[id - 1];
    }
#endif
    return 0;
}
Пример #10
0
JNIEXPORT jlong JNICALL Java_com4j_Native_createInstance(
	JNIEnv* env, jclass __unused__, jstring _progId, jint clsctx, jlong iid1, jlong iid2 ) {
	
	MyGUID iid(iid1,iid2);
	CLSID clsid;
	HRESULT hr;
	JString progId(env,_progId);

	hr = CLSIDFromProgID(progId,&clsid);
	if(FAILED(hr)) {
		if(FAILED(CLSIDFromString( const_cast<LPOLESTR>(LPCOLESTR(progId)),&clsid))) {
			error(env,__FILE__,__LINE__,hr,"Unrecognized CLSID");
			return 0;
		}
	}

	void* p;

	if(clsctx&(CLSCTX_LOCAL_SERVER|CLSCTX_REMOTE_SERVER)) {
		IUnknown* pUnk = NULL;
		hr = CoCreateInstance(clsid,NULL,clsctx,__uuidof(IUnknown),(void**)&pUnk);
		if(FAILED(hr)) {
			error(env,__FILE__,__LINE__,hr,"CoCreateInstance failed");
			return 0;
		}
		hr = OleRun(pUnk);
		if(FAILED(hr)) {
			pUnk->Release();
			error(env,__FILE__,__LINE__,hr,"OleRun failed");
			return 0;
		}
		hr = pUnk->QueryInterface(iid,&p);
		pUnk->Release();

		if(FAILED(hr)) {
			error(env,__FILE__,__LINE__,hr,"QueryInterface failed");
			return 0;
		}

	} else {
		// just the plain CoCreateInstance
		hr = CoCreateInstance(clsid,NULL,clsctx,iid,&p);
		if(FAILED(hr)) {
			error(env,__FILE__,__LINE__,hr,"CoCreateInstance failed");
			return 0;
		}
	}
	return reinterpret_cast<jlong>(p);
}
Пример #11
0
void SthenoCore::createReplicationGroup(
        OverlayPeerInfoPtr& primary,
        list<OverlayPeerInfoPtr>& replicas,
        UUIDPtr& rgid,
        UUIDPtr& sid,
        ServiceParamsPtr& params
        ) throw (ServiceException&) {

    if (!isValid()) {
        throw RuntimeException(RuntimeException::INVALID_RUNTIME);
    }
    ServiceAbstractPtr sPtr;
    FaultTolerancePtr ftToleranceSvc;
    try {
        m_overlay->getFaultTolerance(ftToleranceSvc);
    } catch (OverlayException& ex) {
        throw RuntimeException(RuntimeException::INVALID_OVERLAY);
    }
    printf("==========================> SID=%s FT params=%p %p\n", sid->toString().c_str(), params->getFTParams().get(), params->getQuerySpecializationBlob());
    if (!params->getFTParams().null()) {
        UUIDPtr iid(UUID::generateUUID());
        createServiceInstance(sid, iid, sPtr);

        UInt serviceOverallQoS = SERVICE_DEFAULT_QOS * 2; //5000;
        //UInt serviceFTQoS = 50000; //50000;
        //UInt serviceQoS = 50000; //50000;
        //total=31K
        //+1 = 46K
        //QoS        
        UUIDPtr serviceCgroupUUID(UUID::generateUUID());
        String path = "service_" + sid->toString() + "_" + serviceCgroupUUID->toString();
        QoSManagerInterface* qosManager = 0;
        if (m_reservationFlag) {
            //qosManager = m_serviceQosManager->createSubDomainQoSManager(path, serviceOverallQoS, m_runtimePeriod);
            qosManager = m_runtimeQoSManager;
        }
        QoSManagerInterface* qosFTManager = qosManager;
        /*String ftPath = Cgroup::getSep();
        ftPath += "FT";
        //HierarchicalPath::appendPaths(path, "/FT");        
        if (m_reservationFlag) {
            qosFTManager = qosManager->createSubDomainQoSManager(ftPath, serviceFTQoS, m_runtimePeriod);
        }*/
        QoSManagerInterface* qosServiceManager = qosManager;
        /*String servicePath = Cgroup::getSep();
        servicePath += "service";
        //HierarchicalPath::appendPaths(path, "/service");        
        if (m_reservationFlag) {
            qosServiceManager = qosManager->createSubDomainQoSManager(servicePath, serviceQoS, m_runtimePeriod);
        }*/
        ftToleranceSvc->createReplicationGroup(sPtr, params, rgid, primary, replicas, qosFTManager);
        sPtr->open(params, ServiceAbstract::FT_REPLICA, qosServiceManager);
        //free meta qos manager
        /*if (qosManager != 0) {
            delete qosManager;
        }*/
        ServiceInstanceInfoPtr info;
        //UUIDPtr iid = sPtr->getIID();
        this->getInstanceOfService(sid, iid, info);
        MeshPtr meshPtr;
        try {
            getOverlay()->getMesh(meshPtr);
        } catch (OverlayException& ex) {
            throw RuntimeException(RuntimeException::INVALID_OVERLAY);
        }
        meshPtr->onServiceCreation(info);
    } else {
        throw ServiceException(ServiceException::INVALID_FT_PARAMS);
    }

}
Пример #12
0
// A method added for Python performance if you really need
// it.  Allows you to fetch a block of objects in one
// hit, allowing the loop to remain implemented in C.
static PyObject *PyFetchBlock(PyObject *self, PyObject *args)
{
	PyObject *obIID = NULL;
	int n_wanted;
	int n_fetched = 0;
	if (!PyArg_ParseTuple(args, "i|O:FetchBlock", &n_wanted, &obIID))
		return NULL;

	nsIID iid(NS_GET_IID(nsISupports));
	if (obIID != NULL && !Py_nsIID::IIDFromPyObject(obIID, &iid))
		return NULL;
	nsIEnumerator *pI = GetI(self);
	if (pI==NULL)
		return NULL;

	// We want to fetch with the thread-lock released,
	// but this means we can not append to the PyList
	nsISupports **fetched = new nsISupports*[n_wanted];
	if (fetched==nsnull) {
		PyErr_NoMemory();
		return NULL;
	}
	memset(fetched, 0, sizeof(nsISupports *) * n_wanted);
	nsresult r = NS_OK;
	Py_BEGIN_ALLOW_THREADS;
	for (;n_fetched<n_wanted;) {
		nsISupports *pNew;
		r = pI->CurrentItem(&pNew);
		if (NS_FAILED(r)) {
			r = 0; // Normal enum end
			break;
		}
		if (obIID) {
			nsISupports *temp;
			r = pNew->QueryInterface(iid, (void **)&temp);
			pNew->Release();
			if ( NS_FAILED(r) ) {
				break;
			}
			pNew = temp;
		}
		fetched[n_fetched] = pNew;
		n_fetched++; // must increment before breaking out.
		if (NS_FAILED(pI->Next()))
			break; // not an error condition.
	}
	Py_END_ALLOW_THREADS;
	PyObject *ret;
	if (NS_SUCCEEDED(r)) {
		ret = PyList_New(n_fetched);
		if (ret)
			for (int i=0;i<n_fetched;i++) {
				PyObject *new_ob = Py_nsISupports::PyObjectFromInterface(fetched[i], iid, PR_FALSE);
				PyList_SET_ITEM(ret, i, new_ob);
			}
	} else
		ret = PyXPCOM_BuildPyException(r);

	if ( ret == NULL ) {
		// Free the objects we consumed.
		for (int i=0;i<n_fetched;i++)
			fetched[i]->Release();

	}
	delete [] fetched;
	return ret;
}
QContact SeasideCache::contactById(const QContactId &id)
{
    quint32 iid(internalId(id));
    return instancePtr->m_cache[instancePtr->m_cacheIndices[iid]].contact;
}
Пример #14
0
		bool CalendarTemplateElement::loadFromRecord( const Record& record, util::Env& env )
		{
			bool result(false);

			if(record.isDefined(TABLE_COL_ID))
			{
				RegistryKeyType value(record.getDefault<RegistryKeyType>(TABLE_COL_ID, 0));
				if(value != getKey())
				{
					result = true;
					setKey(value);
				}
			}

			// Rank
			if(record.isDefined(CalendarTemplateElementTableSync::COL_RANK))
			{
				size_t value(
					record.getDefault<size_t>(CalendarTemplateElementTableSync::COL_RANK, 0)
				);
				if(value != getRank())
				{
					result = true;
					setRank(value);
				}
			}

			// Min date
			if(record.isDefined(CalendarTemplateElementTableSync::COL_MIN_DATE))
			{
				date value(neg_infin);
				if(!record.get<string>(CalendarTemplateElementTableSync::COL_MIN_DATE).empty())
				{
					try
					{
						value = from_string(record.get<string>(CalendarTemplateElementTableSync::COL_MIN_DATE));
					}
					catch(...)
					{
					}
				}
				if(value != getMinDate())
				{
					result = true;
					setMinDate(value);
				}
			}

			// Max date
			if(record.isDefined(CalendarTemplateElementTableSync::COL_MAX_DATE))
			{
				date value(pos_infin);
				if(!record.get<string>(CalendarTemplateElementTableSync::COL_MAX_DATE).empty())
				{
					try
					{
						value = from_string(record.get<string>(CalendarTemplateElementTableSync::COL_MAX_DATE));
					}
					catch(...)
					{
					}
				}
				if(value != getMaxDate())
				{
					result = true;
					setMaxDate(value);
				}
			}

			// Days modulo
			if(record.isDefined(CalendarTemplateElementTableSync::COL_INTERVAL))
			{
				days value(
					record.getDefault<long>(CalendarTemplateElementTableSync::COL_INTERVAL, 0)
				);
				if(value != getStep())
				{
					result = true;
					setStep(value);
				}
			}

			// Operation
			if(record.isDefined(CalendarTemplateElementTableSync::COL_POSITIVE))
			{
				Operation value(
					static_cast<Operation>(
						record.getDefault<int>(CalendarTemplateElementTableSync::COL_POSITIVE, 0)
				)	);
				if(value != getOperation())
				{
					result = true;
					setOperation(value);
				}
			}

			// Included calendar
//			if(linkLevel > FIELDS_ONLY_LOAD_LEVEL)
			{
				if(record.isDefined(CalendarTemplateElementTableSync::COL_INCLUDE_ID))
				{
					CalendarTemplate* value(NULL);
					RegistryKeyType iid(
						record.getDefault<RegistryKeyType>(
							CalendarTemplateElementTableSync::COL_INCLUDE_ID,
							0
					)	);
					if(iid > 0)	try
					{
						value = CalendarTemplateTableSync::GetEditable(iid, env).get();
					}
					catch (ObjectNotFoundException<CalendarTemplate> e)
					{
						Log::GetInstance().warn("Data corrupted in " + CalendarTemplateElementTableSync::TABLE.NAME + "/" + CalendarTemplateElementTableSync::COL_INCLUDE_ID, e);
					}
					if(value != getInclude())
					{
						result = true;
						setInclude(value);
					}
				}
			}

			// Link with calendar template
//			if(linkLevel == UP_LINKS_LOAD_LEVEL || linkLevel == UP_DOWN_LINKS_LOAD_LEVEL || linkLevel == ALGORITHMS_OPTIMIZATION_LOAD_LEVEL)
			{
				if(record.isDefined(CalendarTemplateElementTableSync::COL_CALENDAR_ID))
				{
					CalendarTemplate* value(NULL);
					RegistryKeyType id(
						record.getDefault<RegistryKeyType>(
							CalendarTemplateElementTableSync::COL_CALENDAR_ID,
							0
					)	);
					if(id > 0) try
					{
						value = CalendarTemplateTableSync::GetEditable(id, env).get();
					}
					catch (ObjectNotFoundException<CalendarTemplate> e)
					{
						Log::GetInstance().warn("Data corrupted in " + CalendarTemplateElementTableSync::TABLE.NAME + "/" + CalendarTemplateElementTableSync::COL_CALENDAR_ID, e);
					}
					if(value != getCalendar())
					{
						result = true;
						setCalendar(value);
					}
				}
			}

			return result;
		}
Пример #15
0
bool PE::_parse_imports()
{
	if (!_ioh || _file_handle == nullptr) { // Image Optional Header wasn't parsed successfully.
		return false;
	}
	if (!_reach_directory(IMAGE_DIRECTORY_ENTRY_IMPORT))	{ // No imports
		return true;
	}

	while (true) // We stop at the first NULL IMAGE_IMPORT_DESCRIPTOR.
	{
		pimage_import_descriptor iid(new image_import_descriptor);
		memset(iid.get(), 0, 5*sizeof(boost::uint32_t)); // Don't overwrite the last member (a string)

		if (20 != fread(iid.get(), 1, 20, _file_handle.get()))
		{
			PRINT_ERROR << "Could not read the IMAGE_IMPORT_DESCRIPTOR." << std::endl;
			return true; // Don't give up on the rest of the parsing.
		}

		// Exit condition
		if (iid->OriginalFirstThunk == 0 && iid->FirstThunk == 0) {
			break;
		}

		// Non-standard parsing. The Name RVA is translated to an actual string here.
		auto offset = _rva_to_offset(iid->Name);
		if (!offset) { // Try to use the RVA as a direct address if the imports are outside of a section.
			offset = iid->Name;
		}
		std::string library_name;
		if (!utils::read_string_at_offset(_file_handle.get(), offset, library_name))
		{
			// It seems that the Windows loader doesn't give up if such a thing happens.
			if (_imports.size() > 0)
			{
				PRINT_WARNING << "Could not read an import's name." << std::endl;
				break; // Try to continue the parsing with the available imports.
			}

			PRINT_ERROR << "Could not read an import's name." << std::endl;
			return true;
		}

		pImportedLibrary library = pImportedLibrary(new ImportedLibrary(library_name, iid));
		_imports.push_back(library);
	}

	// Parse the IMPORT_LOOKUP_TABLE for each imported library
	for (auto it = _imports.begin() ; it != _imports.end() ; ++it)
	{
		int ilt_offset;
		auto descriptor = (*it)->get_image_import_descriptor();
		if (descriptor == nullptr)
		{
			// Should never happen, standard (as opposed to delay-loaded) imports all have image import descriptors.
			PRINT_WARNING << "Tried to parse imported functions, but no image import descriptor was given!" << DEBUG_INFO_INSIDEPE << std::endl;
			continue;
		}

		if (descriptor->OriginalFirstThunk != 0) {
			ilt_offset = _rva_to_offset(descriptor->OriginalFirstThunk);
		}
		else { // Some packed executables use FirstThunk and set OriginalFirstThunk to 0.
			ilt_offset = _rva_to_offset(descriptor->FirstThunk);
		}

		if (!_parse_import_lookup_table(ilt_offset, *it))
		{
			// Non fatal. Stop trying to parse imports, but the ones already read will still be available.
			if ((*it)->get_name() != nullptr) {
				PRINT_WARNING << "An error occurred while trying to read functions imported by " << *(*it)->get_name()
							  << "." << DEBUG_INFO_INSIDEPE << std::endl;
			}
			return true;
		}
	}

	return true;
}
Пример #16
0
bool PE::_parse_imports(FILE* f)
{
	if (!_ioh) { // Image Optional Header wasn't parsed successfully.
		return false;
	}
	if (!_reach_directory(f, IMAGE_DIRECTORY_ENTRY_IMPORT))	{ // No imports
		return true;
	}

	while (true) // We stop at the first NULL IMAGE_IMPORT_DESCRIPTOR.
	{
		pimage_import_descriptor iid(new image_import_descriptor);
		memset(iid.get(), 0, 5*sizeof(boost::uint32_t)); // Don't overwrite the last member (a string)

		if (20 != fread(iid.get(), 1, 20, f))
		{
			PRINT_ERROR << "Could not read the IMAGE_IMPORT_DESCRIPTOR." << std::endl;
			return true; // Don't give up on the rest of the parsing.
		}

		// Exit condition
		if (iid->OriginalFirstThunk == 0 && iid->FirstThunk == 0) {
			break;
		}

		// Non-standard parsing. The Name RVA is translated to an actual string here.
		auto offset = _rva_to_offset(iid->Name);
		if (!offset) { // Try to use the RVA as a direct address if the imports are outside of a section.
			offset = iid->Name;
		}
		if (!utils::read_string_at_offset(f, offset, iid->NameStr))
		{
			// It seems that the Windows loader doesn't give up if such a thing happens.
			if (_imports.size() > 0)
			{
				PRINT_WARNING << "Could not read an import's name." << std::endl;
				break; // Try to continue the parsing with the available imports.
			}

			PRINT_ERROR << "Could not read an import's name." << std::endl;
			return true;
		}

		pimage_library_descriptor library = boost::make_shared<image_library_descriptor>(iid, std::vector<pimport_lookup_table>());
		_imports.push_back(library);
	}

	// Parse the IMPORT_LOOKUP_TABLE for each imported library
	for (auto it = _imports.begin() ; it != _imports.end() ; ++it)
	{
		int ilt_offset;
		if ((*it)->first->OriginalFirstThunk != 0) {
			ilt_offset = _rva_to_offset((*it)->first->OriginalFirstThunk);
		}
		else { // Some packed executables use FirstThunk and set OriginalFirstThunk to 0.
			ilt_offset = _rva_to_offset((*it)->first->FirstThunk);
		}
		if (!ilt_offset || fseek(f, ilt_offset, SEEK_SET))
		{
			PRINT_ERROR << "Could not reach an IMPORT_LOOKUP_TABLE." << std::endl;
			return true;
		}

		while (true) // We stop at the first NULL IMPORT_LOOKUP_TABLE
		{
			pimport_lookup_table import = boost::make_shared<import_lookup_table>();
			import->AddressOfData = 0;
			import->Hint = 0;

			// The field has a size of 8 for x64 PEs
			int size_to_read = (_ioh->Magic == nt::IMAGE_OPTIONAL_HEADER_MAGIC.at("PE32+") ? 8 : 4);
			if (size_to_read != fread(&(import->AddressOfData), 1, size_to_read, f))
			{
				PRINT_ERROR << "Could not read the IMPORT_LOOKUP_TABLE." << std::endl;
				return true;
			}

			// Exit condition
			if (import->AddressOfData == 0) {
				break;
			}

			// Read the HINT/NAME TABLE if applicable. Check the most significant byte of AddressOfData to
			// see if the import is by name or ordinal. For PE32+, AddressOfData is a uint64.
			boost::uint64_t mask = (size_to_read == 8 ? 0x8000000000000000 : 0x80000000);
			if (!(import->AddressOfData & mask))
			{
				// Import by name. Read the HINT/NAME table. For both PE32 and PE32+, its RVA is stored
				// in bits 30-0 of AddressOfData.
				unsigned int table_offset = _rva_to_offset(import->AddressOfData & 0x7FFFFFFF);
				if (table_offset == 0)
				{
					PRINT_ERROR << "Could not reach the HINT/NAME table." << std::endl;
					return true;
				}

				unsigned int saved_offset = ftell(f);
				if (saved_offset == -1 || fseek(f, table_offset, SEEK_SET) || 2 != fread(&(import->Hint), 1, 2, f))
				{
					PRINT_ERROR << "Could not read a HINT/NAME hint." << std::endl;
					return true;
				}
				import->Name = utils::read_ascii_string(f);

				//TODO: Demangle the import name

				// Go back to the import lookup table.
				if (fseek(f, saved_offset, SEEK_SET)) {
					return true;
				}
			}

			(*it)->second.push_back(import);
		}
	}

	return true;
}