/*! \internal */ bool QFSFileEnginePrivate::closeFdFh() { Q_Q(QFSFileEngine); if (fd == -1 && !fh) return false; // Flush the file if it's buffered, and if the last flush didn't fail. bool flushed = !fh || (!lastFlushFailed && q->flush()); bool closed = true; tried_stat = 0; // Close the file if we created the handle. if (closeFileHandle) { int ret; do { if (fh) { // Close buffered file. ret = fclose(fh) != 0 ? -1 : 0; } else { // Close unbuffered file. ret = QT_CLOSE(fd); } } while (ret == -1 && errno == EINTR); // We must reset these guys regardless; calling close again after a // failed close causes crashes on some systems. fh = 0; fd = -1; closed = (ret == 0); } // Report errors. if (!flushed || !closed) { if (flushed) { // If not flushed, we want the flush error to fall through. q->setError(QFile::UnspecifiedError, qt_error_string(errno)); } return false; } return true; }
void SubjectMenu::setSubjectLocation(SubjectMenu::SubjectType subjectType, int id, int location) { QSqlQuery query; if(subjectType == User) { query.prepare("UPDATE Users set locationId=:locationid where userId=:subjectid"); } else { query.prepare("UPDATE Robot set locationId=:locationid where robotId=:subjectid"); } query.bindValue(":subjectid",id); query.bindValue(":locationid",location); if (!query.exec()) { qCritical("Cannot update: %s (%s)", DbSvc::getFactory()->getDb()->lastError().text().toLatin1().data(), qt_error_string().toLocal8Bit().data()); } }
/*! \internal */ bool QFSFileEnginePrivate::flushFh() { Q_Q(QFSFileEngine); // Never try to flush again if the last flush failed. Otherwise you can // get crashes on some systems (AIX). if (lastFlushFailed) return false; int ret = fflush(fh); lastFlushFailed = (ret != 0); lastIOCommand = QFSFileEnginePrivate::IOFlushCommand; if (ret != 0) { q->setError(errno == ENOSPC ? QFile::ResourceError : QFile::WriteError, qt_error_string(errno)); return false; } return true; }
QBluetoothSocketPrivate::QBluetoothSocketPrivate() : socket(-1), socketType(QBluetoothServiceInfo::UnknownProtocol), state(QBluetoothSocket::UnconnectedState), socketError(QBluetoothSocket::NoSocketError), readNotifier(0), connectWriteNotifier(0), connecting(false), discoveryAgent(0), isServerSocket(false) { #ifdef QT_QNX_BT_BLUETOOTH if (!initCounter && (bt_spp_init() == -1)) qCDebug(QT_BT_QNX) << "Could not initialize Bluetooth library. " << qt_error_string(errno); initCounter++; #else ppsRegisterControl(); #endif }
void QBluetoothSocketPrivate::_q_readNotify() { Q_Q(QBluetoothSocket); char *writePointer = buffer.reserve(QPRIVATELINEARBUFFER_BUFFERSIZE); int readFromDevice = ::read(socket, writePointer, QPRIVATELINEARBUFFER_BUFFERSIZE); if (readFromDevice <= 0){ int errsv = errno; readNotifier->setEnabled(false); connectWriteNotifier->setEnabled(false); qCWarning(QT_BT_QNX) << Q_FUNC_INFO << socket << " error:" << readFromDevice << errorString; //TODO Try if this actually works errorString = qt_error_string(errsv); q->setSocketError(QBluetoothSocket::UnknownSocketError); q->disconnectFromService(); q->setSocketState(QBluetoothSocket::UnconnectedState); } else { buffer.chop(QPRIVATELINEARBUFFER_BUFFERSIZE - (readFromDevice < 0 ? 0 : readFromDevice)); emit q->readyRead(); } }
/*! \internal */ qint64 QFSFileEnginePrivate::readLineFdFh(char *data, qint64 maxlen) { Q_Q(QFSFileEngine); if (!fh) return q->QAbstractFileEngine::readLine(data, maxlen); const QT_OFF_T oldPos = QT_FTELL(fh); // QIODevice::readLine() passes maxlen - 1 to QFile::readLineData() // because it has made space for the '\0' at the end of data. But fgets // does the same, so we'd get two '\0' at the end - passing maxlen + 1 // solves this. if (!fgets(data, int(maxlen + 1), fh)) { if (!feof(fh)) q->setError(QFile::ReadError, qt_error_string(int(errno))); return -1; // error } const qint64 lineLength = QT_FTELL(fh) - oldPos; return lineLength > 0 ? lineLength : qstrlen(data); }
/* This opens the specified library, mmaps it into memory, and searches for the QT_PLUGIN_VERIFICATION_DATA. The advantage of this approach is that we can get the verification data without have to actually load the library. This lets us detect mismatches more safely. Returns false if version information is not present, or if the information could not be read. Returns true if version information is present and successfully read. */ static bool qt_unix_query(const QString &library, uint *version, bool *debug, QLibraryPrivate *lib = 0) { QFile file(library); if (!file.open(QIODevice::ReadOnly)) { if (lib) lib->errorString = file.errorString(); if (qt_debug_component()) { qWarning("%s: %s", QFile::encodeName(library).data(), qPrintable(qt_error_string(errno))); } return false; } QByteArray data; const char *filedata = 0; ulong fdlen = file.size(); filedata = (char *) file.map(0, fdlen); if (filedata == 0) { // try reading the data into memory instead data = file.readAll(); filedata = data.constData(); fdlen = data.size(); } /* ELF binaries on GNU, have .qplugin sections. */ const char pattern[] = "pattern=QT_PLUGIN_VERIFICATION_DATA"; const ulong plen = qstrlen(pattern); const long pos = qt_find_pattern(filedata, fdlen, pattern, plen); bool ret = false; if (pos >= 0) ret = qt_parse_pattern(filedata + pos, version, debug); if (!ret && lib) lib->errorString = QLibrary::tr("Plugin verification data mismatch in '%1'").arg(library); file.close(); return ret; }
/*! Opens the file descriptor \a fd to the file engine, using the open mode \a flags. */ bool QFSFileEnginePrivate::openFd(QIODevice::OpenMode openMode, int fd) { Q_Q(QFSFileEngine); this->fd = fd; fh = 0; // Seek to the end when in Append mode. if (openMode & QFile::Append) { int ret; do { ret = QT_LSEEK(fd, 0, SEEK_END); } while (ret == -1 && errno == EINTR); if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); return false; } } return true; }
/* \internal */ qint64 QFSFileEnginePrivate::nativeWrite(const char *data, qint64 len) { Q_Q(QFSFileEngine); if (fh || fd != -1) { // stdio / stdlib mode. return writeFdFh(data, len); } // Windows native mode. if (fileHandle == INVALID_HANDLE_VALUE) return -1; qint64 bytesToWrite = len; // Writing on Windows fails with ERROR_NO_SYSTEM_RESOURCES when // the chunks are too large, so we limit the block size to 32MB. const DWORD blockSize = DWORD(qMin(bytesToWrite, qint64(32 * 1024 * 1024))); qint64 totalWritten = 0; do { DWORD bytesWritten; if (!WriteFile(fileHandle, data + totalWritten, blockSize, &bytesWritten, NULL)) { if (totalWritten == 0) { // Note: Only return error if the first WriteFile failed. q->setError(QFile::WriteError, qt_error_string()); return -1; } break; } if (bytesWritten == 0) break; totalWritten += bytesWritten; bytesToWrite -= bytesWritten; } while (totalWritten < len); return qint64(totalWritten); }
void QBluetoothSocketPrivate::_q_readNotify() { Q_Q(QBluetoothSocket); char *writePointer = buffer.reserve(QPRIVATELINEARBUFFER_BUFFERSIZE); // qint64 readFromDevice = q->readData(writePointer, QPRIVATELINEARBUFFER_BUFFERSIZE); int readFromDevice = ::read(socket, writePointer, QPRIVATELINEARBUFFER_BUFFERSIZE); buffer.chop(QPRIVATELINEARBUFFER_BUFFERSIZE - (readFromDevice < 0 ? 0 : readFromDevice)); if(readFromDevice <= 0){ int errsv = errno; readNotifier->setEnabled(false); connectWriteNotifier->setEnabled(false); errorString = qt_error_string(errsv); qCWarning(QT_BT_BLUEZ) << Q_FUNC_INFO << socket << "error:" << readFromDevice << errorString; if(errsv == EHOSTDOWN) q->setSocketError(QBluetoothSocket::HostNotFoundError); else q->setSocketError(QBluetoothSocket::UnknownSocketError); q->disconnectFromService(); } else { emit q->readyRead(); } }
/*! * Process all incoming HCI events. Function cannot process anything else but events. */ void HciManager::_q_readNotify() { unsigned char buffer[qMax<int>(HCI_MAX_EVENT_SIZE, sizeof(AclData))]; int size; size = ::read(hciSocket, buffer, sizeof(buffer)); if (size < 0) { if (errno != EAGAIN && errno != EINTR) qCWarning(QT_BT_BLUEZ) << "Failed reading HCI events:" << qt_error_string(errno); return; } switch (buffer[0]) { case HCI_EVENT_PKT: handleHciEventPacket(buffer + 1, size - 1); break; case HCI_ACL_PKT: handleHciAclPacket(buffer + 1, size - 1); break; default: qCWarning(QT_BT_BLUEZ) << "Ignoring unexpected HCI packet type" << buffer[0]; } }
/*! Begins execution of the thread by calling run(), which should be reimplemented in a QThread subclass to contain your code. The operating system will schedule the thread according to the \a priority parameter. If the thread is already running, this function does nothing. \sa run(), terminate() */ void QThread::start(Priority priority) { Q_D(QThread); QMutexLocker locker(&d->mutex); if (d->running) return; d->running = true; d->finished = false; d->terminated = false; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); d->priority = priority; #if defined(Q_OS_DARWIN) || !defined(Q_OS_OPENBSD) && defined(_POSIX_THREAD_PRIORITY_SCHEDULING) && (_POSIX_THREAD_PRIORITY_SCHEDULING-0 >= 0) switch (priority) { case InheritPriority: { pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED); break; } default: { int sched_policy; if (pthread_attr_getschedpolicy(&attr, &sched_policy) != 0) { // failed to get the scheduling policy, don't bother // setting the priority qWarning("QThread::start: Cannot determine default scheduler policy"); break; } int prio_min = sched_get_priority_min(sched_policy); int prio_max = sched_get_priority_max(sched_policy); if (prio_min == -1 || prio_max == -1) { // failed to get the scheduling parameters, don't // bother setting the priority qWarning("QThread::start: Cannot determine scheduler priority range"); break; } int prio; switch (priority) { case IdlePriority: prio = prio_min; break; case TimeCriticalPriority: prio = prio_max; break; default: // crudely scale our priority enum values to the prio_min/prio_max prio = (((prio_max - prio_min) / TimeCriticalPriority) * priority) + prio_min; prio = qMax(prio_min, qMin(prio_max, prio)); break; } sched_param sp; sp.sched_priority = prio; if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) != 0 || pthread_attr_setschedpolicy(&attr, sched_policy) != 0 || pthread_attr_setschedparam(&attr, &sp) != 0) { // could not set scheduling hints, fallback to inheriting them pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED); } break; } } #endif // _POSIX_THREAD_PRIORITY_SCHEDULING if (d->stackSize > 0) { #if defined(_POSIX_THREAD_ATTR_STACKSIZE) && (_POSIX_THREAD_ATTR_STACKSIZE-0 > 0) int code = pthread_attr_setstacksize(&attr, d->stackSize); #else int code = ENOSYS; // stack size not supported, automatically fail #endif // _POSIX_THREAD_ATTR_STACKSIZE if (code) { qWarning("QThread::start: Thread stack size error: %s", qPrintable(qt_error_string(code))); // we failed to set the stacksize, and as the documentation states, // the thread will fail to run... d->running = false; d->finished = false; return; } } int code = pthread_create(&d->thread_id, &attr, QThreadPrivate::start, this); if (code == EPERM) { // caller does not have permission to set the scheduling // parameters/policy pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED); code = pthread_create(&d->thread_id, &attr, QThreadPrivate::start, this); } pthread_attr_destroy(&attr); if (code) { qWarning("QThread::start: Thread creation error: %s", qPrintable(qt_error_string(code))); d->running = false; d->finished = false; d->thread_id = 0; } }
void tst_QMimeDatabase::initTestCase() { QVERIFY2(m_temporaryDir.isValid(), qPrintable(m_temporaryDir.errorString())); QStandardPaths::setTestModeEnabled(true); m_localMimeDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/mime"; if (QDir(m_localMimeDir).exists()) { QVERIFY2(QDir(m_localMimeDir).removeRecursively(), qPrintable(m_localMimeDir + ": " + qt_error_string())); } QString errorMessage; #ifdef USE_XDG_DATA_DIRS // Create a temporary "global" XDG data dir for later use // It will initially contain a copy of freedesktop.org.xml QVERIFY2(m_temporaryDir.isValid(), ("Could not create temporary subdir: " + m_temporaryDir.errorString()).toUtf8()); const QDir here = QDir(m_temporaryDir.path()); m_globalXdgDir = m_temporaryDir.path() + QStringLiteral("/global"); const QString globalPackageDir = m_globalXdgDir + QStringLiteral("/mime/packages"); QVERIFY(here.mkpath(globalPackageDir)); qputenv("XDG_DATA_DIRS", QFile::encodeName(m_globalXdgDir)); qDebug() << "\nGlobal XDG_DATA_DIRS: " << m_globalXdgDir; const QString freeDesktopXml = QStringLiteral("freedesktop.org.xml"); const QString xmlFileName = QLatin1String(RESOURCE_PREFIX) + freeDesktopXml; const QString xmlTargetFileName = globalPackageDir + QLatin1Char('/') + freeDesktopXml; QVERIFY2(copyResourceFile(xmlFileName, xmlTargetFileName, &errorMessage), qPrintable(errorMessage)); #endif m_testSuite = QFINDTESTDATA("testfiles"); if (m_testSuite.isEmpty()) qWarning("%s", qPrintable(testSuiteWarning())); errorMessage = QString::fromLatin1("Cannot find '%1'"); for (uint i = 0; i < sizeof additionalMimeFiles / sizeof additionalMimeFiles[0] - 1; i++) { const QString resourceFilePath = QString::fromLatin1(RESOURCE_PREFIX) + QLatin1String(additionalMimeFiles[i]); QVERIFY2(QFile::exists(resourceFilePath), qPrintable(errorMessage.arg(resourceFilePath))); m_additionalMimeFileNames.append(QLatin1String(additionalMimeFiles[i])); m_additionalMimeFilePaths.append(resourceFilePath); } initTestCaseInternal(); m_isUsingCacheProvider = !qEnvironmentVariableIsSet("QT_NO_MIME_CACHE"); }
/*! \internal */ qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len) { Q_Q(QFSFileEngine); #ifdef Q_OS_SYMBIAN if (symbianFile.SubSessionHandle()) { if(len > KMaxTInt) { //this check is more likely to catch a corrupt length, since it isn't possible to allocate 2GB buffers (yet..) q->setError(QFile::ReadError, QLatin1String("Maximum 2GB in single read on this platform")); return -1; } TPtr8 ptr(reinterpret_cast<TUint8*>(data), static_cast<TInt>(len)); TInt r = symbianFile.Read(symbianFilePos, ptr); if (r != KErrNone) { q->setError(QFile::ReadError, QSystemError(r, QSystemError::NativeError).toString()); return -1; } symbianFilePos += ptr.Length(); return qint64(ptr.Length()); } #endif if (fh && nativeIsSequential()) { size_t readBytes = 0; int oldFlags = fcntl(QT_FILENO(fh), F_GETFL); for (int i = 0; i < 2; ++i) { // Unix: Make the underlying file descriptor non-blocking if ((oldFlags & O_NONBLOCK) == 0) fcntl(QT_FILENO(fh), F_SETFL, oldFlags | O_NONBLOCK); // Cross platform stdlib read size_t read = 0; do { read = fread(data + readBytes, 1, size_t(len - readBytes), fh); } while (read == 0 && !feof(fh) && errno == EINTR); if (read > 0) { readBytes += read; break; } else { if (readBytes) break; readBytes = read; } // Unix: Restore the blocking state of the underlying socket if ((oldFlags & O_NONBLOCK) == 0) { fcntl(QT_FILENO(fh), F_SETFL, oldFlags); if (readBytes == 0) { int readByte = 0; do { readByte = fgetc(fh); } while (readByte == -1 && errno == EINTR); if (readByte != -1) { *data = uchar(readByte); readBytes += 1; } else { break; } } } } // Unix: Restore the blocking state of the underlying socket if ((oldFlags & O_NONBLOCK) == 0) { fcntl(QT_FILENO(fh), F_SETFL, oldFlags); } if (readBytes == 0 && !feof(fh)) { // if we didn't read anything and we're not at EOF, it must be an error q->setError(QFile::ReadError, qt_error_string(int(errno))); return -1; } return readBytes; } return readFdFh(data, len); }
/*! \internal */ bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode) { Q_Q(QFSFileEngine); if (openMode & QIODevice::Unbuffered) { int flags = openModeToOpenFlags(openMode); // Try to open the file in unbuffered mode. do { fd = QT_OPEN(fileEntry.nativeFilePath().constData(), flags, 0666); } while (fd == -1 && errno == EINTR); // On failure, return and report the error. if (fd == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(errno)); return false; } if (!(openMode & QIODevice::WriteOnly)) { // we don't need this check if we tried to open for writing because then // we had received EISDIR anyway. if (QFileSystemEngine::fillMetaData(fd, metaData) && metaData.isDirectory()) { q->setError(QFile::OpenError, QLatin1String("file to open is a directory")); QT_CLOSE(fd); return false; } } // Seek to the end when in Append mode. if (flags & QFile::Append) { int ret; do { ret = QT_LSEEK(fd, 0, SEEK_END); } while (ret == -1 && errno == EINTR); if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); return false; } } fh = 0; } else { QByteArray fopenMode = openModeToFopenMode(openMode, fileEntry, metaData); // Try to open the file in buffered mode. do { fh = QT_FOPEN(fileEntry.nativeFilePath().constData(), fopenMode.constData()); } while (!fh && errno == EINTR); // On failure, return and report the error. if (!fh) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); return false; } if (!(openMode & QIODevice::WriteOnly)) { // we don't need this check if we tried to open for writing because then // we had received EISDIR anyway. if (QFileSystemEngine::fillMetaData(QT_FILENO(fh), metaData) && metaData.isDirectory()) { q->setError(QFile::OpenError, QLatin1String("file to open is a directory")); fclose(fh); return false; } } setCloseOnExec(fileno(fh)); // ignore failure // Seek to the end when in Append mode. if (openMode & QIODevice::Append) { int ret; do { ret = QT_FSEEK(fh, 0, SEEK_END); } while (ret == -1 && errno == EINTR); if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); return false; } } fd = -1; } closeFileHandle = true; return true; }
uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size, QFile::MemoryMapFlags flags) { Q_Q(QFSFileEngine); Q_UNUSED(flags); if (openMode == QIODevice::NotOpen) { q->setError(QFile::PermissionsError, qt_error_string(int(EACCES))); return 0; } if (offset < 0 || offset != qint64(QT_OFF_T(offset)) || size < 0 || quint64(size) > quint64(size_t(-1))) { q->setError(QFile::UnspecifiedError, qt_error_string(int(EINVAL))); return 0; } // If we know the mapping will extend beyond EOF, fail early to avoid // undefined behavior. Otherwise, let mmap have its say. if (doStat(QFileSystemMetaData::SizeAttribute) && (QT_OFF_T(size) > metaData.size() - QT_OFF_T(offset))) qWarning("QFSFileEngine::map: Mapping a file beyond its size is not portable"); int access = 0; if (openMode & QIODevice::ReadOnly) access |= PROT_READ; if (openMode & QIODevice::WriteOnly) access |= PROT_WRITE; #if defined(Q_OS_INTEGRITY) int pageSize = sysconf(_SC_PAGESIZE); #else int pageSize = getpagesize(); #endif int extra = offset % pageSize; if (quint64(size + extra) > quint64((size_t)-1)) { q->setError(QFile::UnspecifiedError, qt_error_string(int(EINVAL))); return 0; } size_t realSize = (size_t)size + extra; QT_OFF_T realOffset = QT_OFF_T(offset); realOffset &= ~(QT_OFF_T(pageSize - 1)); #ifdef QT_SYMBIAN_USE_NATIVE_FILEMAP TInt nativeMapError = KErrNone; RFileMap mapping; TUint mode(EFileMapRemovableMedia); TUint64 nativeOffset = offset & ~(mapping.PageSizeInBytes() - 1); //If the file was opened for write or read/write, then open the map for read/write if (openMode & QIODevice::WriteOnly) mode |= EFileMapWrite; if (symbianFile.SubSessionHandle()) { nativeMapError = mapping.Open(symbianFile, nativeOffset, size, mode); } else { //map file by name if we don't have a native handle QString fn = QFileSystemEngine::absoluteName(fileEntry).nativeFilePath(); TUint filemode = EFileShareReadersOrWriters | EFileRead; if (openMode & QIODevice::WriteOnly) filemode |= EFileWrite; nativeMapError = mapping.Open(qt_s60GetRFs(), qt_QString2TPtrC(fn), filemode, nativeOffset, size, mode); } if (nativeMapError == KErrNone) { QScopedResource<RFileMap> ptr(mapping); //will call Close if adding to mapping throws an exception uchar *address = mapping.Base() + (offset - nativeOffset); maps[address] = mapping; ptr.take(); return address; } QFile::FileError reportedError = QFile::UnspecifiedError; switch (nativeMapError) { case KErrAccessDenied: case KErrPermissionDenied: reportedError = QFile::PermissionsError; break; case KErrNoMemory: reportedError = QFile::ResourceError; break; } q->setError(reportedError, QSystemError(nativeMapError, QSystemError::NativeError).toString()); return 0; #else #ifdef Q_OS_SYMBIAN //older phones & emulator don't support native mapping, so need to keep the open C way around for those. void *mapAddress; TRAPD(err, mapAddress = QT_MMAP((void*)0, realSize, access, MAP_SHARED, getMapHandle(), realOffset)); if (err != KErrNone) { qWarning("OpenC bug: leave from mmap %d", err); mapAddress = MAP_FAILED; errno = EINVAL; } #else void *mapAddress = QT_MMAP((void*)0, realSize, access, MAP_SHARED, nativeHandle(), realOffset); #endif if (MAP_FAILED != mapAddress) { uchar *address = extra + static_cast<uchar*>(mapAddress); maps[address] = QPair<int,size_t>(extra, realSize); return address; } switch(errno) { case EBADF: q->setError(QFile::PermissionsError, qt_error_string(int(EACCES))); break; case ENFILE: case ENOMEM: q->setError(QFile::ResourceError, qt_error_string(int(errno))); break; case EINVAL: // size are out of bounds default: q->setError(QFile::UnspecifiedError, qt_error_string(int(errno))); break; } return 0; #endif }
// TODO: This looks like should be ported to C code. or a big part of it. bool DivelogsDeWebServices::prepare_dives_for_divelogs(const QString &tempfile, const bool selected) { static const char errPrefix[] = "divelog.de-upload:"; if (!amount_selected) { report_error(tr("no dives were selected").toUtf8()); return false; } xsltStylesheetPtr xslt = NULL; struct zip *zip; xslt = get_stylesheet("divelogs-export.xslt"); if (!xslt) { qDebug() << errPrefix << "missing stylesheet"; return false; } int error_code; zip = zip_open(QFile::encodeName(tempfile), ZIP_CREATE, &error_code); if (!zip) { char buffer[1024]; zip_error_to_str(buffer, sizeof buffer, error_code, errno); report_error(tr("failed to create zip file for upload: %s").toUtf8(), buffer); return false; } /* walk the dive list in chronological order */ int i; struct dive *dive; for_each_dive (i, dive) { FILE *f; char filename[PATH_MAX]; int streamsize; char *membuf; xmlDoc *transformed; struct zip_source *s; /* * Get the i'th dive in XML format so we can process it. * We need to save to a file before we can reload it back into memory... */ if (selected && !dive->selected) continue; f = tmpfile(); if (!f) { report_error(tr("cannot create temporary file: %s").toUtf8(), qt_error_string().toUtf8().data()); goto error_close_zip; } save_dive(f, dive); fseek(f, 0, SEEK_END); streamsize = ftell(f); rewind(f); membuf = (char *)malloc(streamsize + 1); if (!membuf || (streamsize = fread(membuf, 1, streamsize, f)) == 0) { report_error(tr("internal error: %s").toUtf8(), qt_error_string().toUtf8().data()); fclose(f); free((void *)membuf); goto error_close_zip; } membuf[streamsize] = 0; fclose(f); /* * Parse the memory buffer into XML document and * transform it to divelogs.de format, finally dumping * the XML into a character buffer. */ xmlDoc *doc = xmlReadMemory(membuf, streamsize, "divelog", NULL, 0); if (!doc) { qWarning() << errPrefix << "could not parse back into memory the XML file we've just created!"; report_error(tr("internal error").toUtf8()); free((void *)membuf); goto error_close_zip; } free((void *)membuf); transformed = xsltApplyStylesheet(xslt, doc, NULL); xmlDocDumpMemory(transformed, (xmlChar **)&membuf, &streamsize); xmlFreeDoc(doc); xmlFreeDoc(transformed); /* * Save the XML document into a zip file. */ snprintf(filename, PATH_MAX, "%d.xml", i + 1); s = zip_source_buffer(zip, membuf, streamsize, 1); if (s) { int64_t ret = zip_add(zip, filename, s); if (ret == -1) qDebug() << errPrefix << "failed to include dive:" << i; } }
void QBluetoothSocketPrivate::connectToService(const QBluetoothAddress &address, quint16 port, QIODevice::OpenMode openMode) { Q_Q(QBluetoothSocket); int result = -1; if (socket == -1 && !ensureNativeSocket(socketType)) { errorString = QBluetoothSocket::tr("Unknown socket error"); q->setSocketError(QBluetoothSocket::UnknownSocketError); return; } if (socketType == QBluetoothServiceInfo::RfcommProtocol) { sockaddr_rc addr; memset(&addr, 0, sizeof(addr)); addr.rc_family = AF_BLUETOOTH; addr.rc_channel = port; convertAddress(address.toUInt64(), addr.rc_bdaddr.b); connectWriteNotifier->setEnabled(true); readNotifier->setEnabled(true);QString(); result = ::connect(socket, (sockaddr *)&addr, sizeof(addr)); } else if (socketType == QBluetoothServiceInfo::L2capProtocol) { sockaddr_l2 addr; memset(&addr, 0, sizeof(addr)); addr.l2_family = AF_BLUETOOTH; // This is an ugly hack but the socket class does what's needed already. // For L2CP GATT we need a channel rather than a socket and the LE address type // We don't want to make this public API offering for now especially since // only Linux (of all platforms supported by this library) supports this type // of socket. #if defined(QT_BLUEZ_BLUETOOTH) && !defined(QT_BLUEZ_NO_BTLE) if (lowEnergySocketType) { addr.l2_cid = htobs(port); addr.l2_bdaddr_type = lowEnergySocketType; } else { addr.l2_psm = htobs(port); } #else addr.l2_psm = htobs(port); #endif convertAddress(address.toUInt64(), addr.l2_bdaddr.b); connectWriteNotifier->setEnabled(true); readNotifier->setEnabled(true); result = ::connect(socket, (sockaddr *)&addr, sizeof(addr)); } if (result >= 0 || (result == -1 && errno == EINPROGRESS)) { connecting = true; q->setSocketState(QBluetoothSocket::ConnectingState); q->setOpenMode(openMode); } else { errorString = qt_error_string(errno); q->setSocketError(QBluetoothSocket::UnknownSocketError); } }
QString QStandardPaths::writableLocation(StandardLocation type) { switch (type) { case HomeLocation: return QDir::homePath(); case TempLocation: return QDir::tempPath(); case CacheLocation: case GenericCacheLocation: { // http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html QString xdgCacheHome = QFile::decodeName(qgetenv("XDG_CACHE_HOME")); if (isTestModeEnabled()) xdgCacheHome = QDir::homePath() + QLatin1String("/.qttest/cache"); if (xdgCacheHome.isEmpty()) xdgCacheHome = QDir::homePath() + QLatin1String("/.cache"); if (type == QStandardPaths::CacheLocation) appendOrganizationAndApp(xdgCacheHome); return xdgCacheHome; } case DataLocation: case GenericDataLocation: { QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME")); if (isTestModeEnabled()) xdgDataHome = QDir::homePath() + QLatin1String("/.qttest/share"); if (xdgDataHome.isEmpty()) xdgDataHome = QDir::homePath() + QLatin1String("/.local/share"); if (type == QStandardPaths::DataLocation) appendOrganizationAndApp(xdgDataHome); return xdgDataHome; } case ConfigLocation: { // http://standards.freedesktop.org/basedir-spec/latest/ QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); if (isTestModeEnabled()) xdgConfigHome = QDir::homePath() + QLatin1String("/.qttest/config"); if (xdgConfigHome.isEmpty()) xdgConfigHome = QDir::homePath() + QLatin1String("/.config"); return xdgConfigHome; } case RuntimeLocation: { const uid_t myUid = geteuid(); // http://standards.freedesktop.org/basedir-spec/latest/ QString xdgRuntimeDir = QFile::decodeName(qgetenv("XDG_RUNTIME_DIR")); if (xdgRuntimeDir.isEmpty()) { const QString userName = QFileSystemEngine::resolveUserName(myUid); xdgRuntimeDir = QDir::tempPath() + QLatin1String("/runtime-") + userName; QDir dir(xdgRuntimeDir); if (!dir.exists()) { if (!QDir().mkdir(xdgRuntimeDir)) { qWarning("QStandardPaths: error creating runtime directory %s: %s", qPrintable(xdgRuntimeDir), qPrintable(qt_error_string(errno))); return QString(); } } qWarning("QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '%s'", qPrintable(xdgRuntimeDir)); } // "The directory MUST be owned by the user" QFileInfo fileInfo(xdgRuntimeDir); if (fileInfo.ownerId() != myUid) { qWarning("QStandardPaths: wrong ownership on runtime directory %s, %d instead of %d", qPrintable(xdgRuntimeDir), fileInfo.ownerId(), myUid); return QString(); } // "and he MUST be the only one having read and write access to it. Its Unix access mode MUST be 0700." QFile file(xdgRuntimeDir); const QFile::Permissions wantedPerms = QFile::ReadUser | QFile::WriteUser | QFile::ExeUser; if (file.permissions() != wantedPerms && !file.setPermissions(wantedPerms)) { qWarning("QStandardPaths: wrong permissions on runtime directory %s", qPrintable(xdgRuntimeDir)); return QString(); } return xdgRuntimeDir; } default: break; } #ifndef QT_BOOTSTRAPPED // http://www.freedesktop.org/wiki/Software/xdg-user-dirs QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); if (xdgConfigHome.isEmpty()) xdgConfigHome = QDir::homePath() + QLatin1String("/.config"); QFile file(xdgConfigHome + QLatin1String("/user-dirs.dirs")); if (!isTestModeEnabled() && file.open(QIODevice::ReadOnly)) { QHash<QString, QString> lines; QTextStream stream(&file); // Only look for lines like: XDG_DESKTOP_DIR="$HOME/Desktop" QRegExp exp(QLatin1String("^XDG_(.*)_DIR=(.*)$")); while (!stream.atEnd()) { const QString &line = stream.readLine(); if (exp.indexIn(line) != -1) { const QStringList lst = exp.capturedTexts(); const QString key = lst.at(1); QString value = lst.at(2); if (value.length() > 2 && value.startsWith(QLatin1Char('\"')) && value.endsWith(QLatin1Char('\"'))) value = value.mid(1, value.length() - 2); // Store the key and value: "DESKTOP", "$HOME/Desktop" lines[key] = value; } } QString key; switch (type) { case DesktopLocation: key = QLatin1String("DESKTOP"); break; case DocumentsLocation: key = QLatin1String("DOCUMENTS"); break; case PicturesLocation: key = QLatin1String("PICTURES"); break; case MusicLocation: key = QLatin1String("MUSIC"); break; case MoviesLocation: key = QLatin1String("VIDEOS"); break; case DownloadLocation: key = QLatin1String("DOWNLOAD"); break; default: break; } if (!key.isEmpty()) { QString value = lines.value(key); if (!value.isEmpty()) { // value can start with $HOME if (value.startsWith(QLatin1String("$HOME"))) value = QDir::homePath() + value.mid(5); return value; } } } #endif QString path; switch (type) { case DesktopLocation: path = QDir::homePath() + QLatin1String("/Desktop"); break; case DocumentsLocation: path = QDir::homePath() + QLatin1String("/Documents"); break; case PicturesLocation: path = QDir::homePath() + QLatin1String("/Pictures"); break; case FontsLocation: path = QDir::homePath() + QLatin1String("/.fonts"); break; case MusicLocation: path = QDir::homePath() + QLatin1String("/Music"); break; case MoviesLocation: path = QDir::homePath() + QLatin1String("/Videos"); break; case DownloadLocation: path = QDir::homePath() + QLatin1String("/Downloads"); break; case ApplicationsLocation: path = writableLocation(GenericDataLocation) + QLatin1String("/applications"); break; default: break; } return path; }
bool FileSystem::openAndSeekFileSharedRead(QFile* file, QString* errorOrNull, qint64 seek) { QString errorDummy; // avoid many if (errorOrNull) later. QString& error = errorOrNull ? *errorOrNull : errorDummy; error.clear(); #ifdef Q_OS_WIN // // The following code is adapted from Qt's QFSFileEnginePrivate::nativeOpen() // by including the FILE_SHARE_DELETE share mode. // // Enable full sharing. DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; int accessRights = GENERIC_READ; DWORD creationDisp = OPEN_EXISTING; // Create the file handle. SECURITY_ATTRIBUTES securityAtts = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE }; QString fName = longWinPath(file->fileName()); HANDLE fileHandle = CreateFileW( (const wchar_t*)fName.utf16(), accessRights, shareMode, &securityAtts, creationDisp, FILE_ATTRIBUTE_NORMAL, NULL); // Bail out on error. if (fileHandle == INVALID_HANDLE_VALUE) { error = qt_error_string(); return false; } // Convert the HANDLE to an fd and pass it to QFile's foreign-open // function. The fd owns the handle, so when QFile later closes // the fd the handle will be closed too. int fd = _open_osfhandle((intptr_t)fileHandle, _O_RDONLY); if (fd == -1) { error = "could not make fd from handle"; return false; } if (!file->open(fd, QIODevice::ReadOnly, QFile::AutoCloseHandle)) { error = file->errorString(); return false; } // Seek to the right spot LARGE_INTEGER *li = reinterpret_cast<LARGE_INTEGER*>(&seek); DWORD newFilePointer = SetFilePointer(fileHandle, li->LowPart, &li->HighPart, FILE_BEGIN); if (newFilePointer == 0xFFFFFFFF && GetLastError() != NO_ERROR) { error = qt_error_string(); return false; } return true; #else if (!file->open(QFile::ReadOnly)) { error = file->errorString(); return false; } if (!file->seek(seek)) { error = file->errorString(); return false; } return true; #endif }
void QProcessPrivate::startProcess() { Q_Q(QProcess); bool success = false; if (pid) { CloseHandle(pid->hThread); CloseHandle(pid->hProcess); delete pid; pid = 0; } pid = new PROCESS_INFORMATION; memset(pid, 0, sizeof(PROCESS_INFORMATION)); q->setProcessState(QProcess::Starting); if (!createChannel(stdinChannel) || !createChannel(stdoutChannel) || !createChannel(stderrChannel)) return; QString args = qt_create_commandline(program, arguments); QByteArray envlist; if (environment.d.constData()) envlist = qt_create_environment(environment.d.constData()->hash); if (!nativeArguments.isEmpty()) { if (!args.isEmpty()) args += QLatin1Char(' '); args += nativeArguments; } #if defined QPROCESS_DEBUG qDebug("Creating process"); qDebug(" program : [%s]", program.toLatin1().constData()); qDebug(" args : %s", args.toLatin1().constData()); qDebug(" pass environment : %s", environment.isEmpty() ? "no" : "yes"); #endif // Forwarded channels must not set the CREATE_NO_WINDOW flag because this // will render the stdout/stderr handles we're passing useless. DWORD dwCreationFlags = (processChannelMode == QProcess::ForwardedChannels ? 0 : CREATE_NO_WINDOW); dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT; STARTUPINFOW startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, 0, 0, 0, STARTF_USESTDHANDLES, 0, 0, 0, stdinChannel.pipe[0], stdoutChannel.pipe[1], stderrChannel.pipe[1] }; success = CreateProcess(0, (wchar_t*)args.utf16(), 0, 0, TRUE, dwCreationFlags, environment.isEmpty() ? 0 : envlist.data(), workingDirectory.isEmpty() ? 0 : (wchar_t*)QDir::toNativeSeparators(workingDirectory).utf16(), &startupInfo, pid); if (!success) { // Capture the error string before we do CloseHandle below q->setErrorString(QProcess::tr("Process failed to start: %1").arg(qt_error_string())); } if (stdinChannel.pipe[0] != INVALID_Q_PIPE) { CloseHandle(stdinChannel.pipe[0]); stdinChannel.pipe[0] = INVALID_Q_PIPE; } if (stdoutChannel.pipe[1] != INVALID_Q_PIPE) { CloseHandle(stdoutChannel.pipe[1]); stdoutChannel.pipe[1] = INVALID_Q_PIPE; } if (stderrChannel.pipe[1] != INVALID_Q_PIPE) { CloseHandle(stderrChannel.pipe[1]); stderrChannel.pipe[1] = INVALID_Q_PIPE; } if (!success) { cleanup(); processError = QProcess::FailedToStart; emit q->error(processError); q->setProcessState(QProcess::NotRunning); return; } q->setProcessState(QProcess::Running); // User can call kill()/terminate() from the stateChanged() slot // so check before proceeding if (!pid) return; if (threadData->eventDispatcher) { processFinishedNotifier = new QWinEventNotifier(pid->hProcess, q); QObject::connect(processFinishedNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_processDied())); processFinishedNotifier->setEnabled(true); notifier = new QTimer(q); QObject::connect(notifier, SIGNAL(timeout()), q, SLOT(_q_notified())); notifier->start(NOTIFYTIMEOUT); } _q_startupNotification(); }
void QFileDevicePrivate::setError(QFileDevice::FileError err, int errNum) { error = err; errorString = qt_error_string(errNum); }
bool MainWindow::openDatabase() { bool ok; QString host, user, pw, dBase; QFile file("../UHCore/Core/config/database.yaml"); if (!file.exists()) { qDebug()<<"No database config found!!"; } if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { closeDownRequest = true; return false; } QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); if (line.startsWith("mysql_log_user")) { user = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_password")) { pw = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_server")) { host = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_db")) { dBase = line.section(":",1,1).trimmed(); } } if (param != "BATCH") { user = QInputDialog::getText ( this, "Accompany DB", "User:"******"Accompany DB", "Password:"******"Accompany DB", "Host:",QLineEdit::Normal, host, &ok); if (!ok) { closeDownRequest = true; return false; }; dBase = QInputDialog::getText ( this, "Accompany DB", "Database:",QLineEdit::Normal, dBase, &ok); if (!ok) { closeDownRequest = true; return false; }; } QString dbUser = "******" + user + ":" + host + ":" + dBase; db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName(host); db.setDatabaseName(dBase); db.setUserName(user); db.setPassword(pw); dbOpen = db.open(); if (!dbOpen) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Critical); msgBox.setText("Database error - login problem - see console log!"); msgBox.exec(); qCritical("Cannot open database: %s (%s)", db.lastError().text().toLatin1().data(), qt_error_string().toLocal8Bit().data()); return false; } qDebug() << "Database Opened"; QSqlQuery query("SELECT ExperimentalLocationId, SessionUser FROM SessionControl WHERE SessionId = 1 LIMIT 1"); if (query.next()) { experimentLocation = query.value(0).toInt(); expLocation.setNum(experimentLocation); defaultUser = query.value(1).toString(); QSqlQuery locn("select location from ExperimentalLocation where id = '" + expLocation + "' LIMIT 1"); locn.next(); dbUser += " :: Location: " + locn.value(0).toString(); QSqlQuery user("select nickname from Users where userId = '" + defaultUser + "' LIMIT 1"); user.next(); dbUser += " :: User: "******"Can find session control table!"); msgBox.exec(); closeDownRequest = true; return false; } ui->dbLabel->setText(dbUser); return true; }
static void report_error(int code, const char *where, const char *what) { if (code != 0) qWarning("%s: %s failure: %s", where, what, qPrintable(qt_error_string(code))); }
/*! \internal */ bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode) { Q_Q(QFSFileEngine); if (openMode & QIODevice::Unbuffered) { int flags = openModeToOpenFlags(openMode); // Try to open the file in unbuffered mode. do { fd = QT_OPEN(nativeFilePath.constData(), flags, 0666); } while (fd == -1 && errno == EINTR); // On failure, return and report the error. if (fd == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(errno)); return false; } #ifndef O_CLOEXEC // not needed on Linux >= 2.6.23 setCloseOnExec(fd); // ignore failure #endif // Seek to the end when in Append mode. if (flags & QFile::Append) { int ret; do { ret = QT_LSEEK(fd, 0, SEEK_END); } while (ret == -1 && errno == EINTR); if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); return false; } } fh = 0; } else { QByteArray fopenMode = openModeToFopenMode(openMode, filePath); // Try to open the file in buffered mode. do { fh = QT_FOPEN(nativeFilePath.constData(), fopenMode.constData()); } while (!fh && errno == EINTR); // On failure, return and report the error. if (!fh) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); return false; } setCloseOnExec(fileno(fh)); // ignore failure // Seek to the end when in Append mode. if (openMode & QIODevice::Append) { int ret; do { ret = QT_FSEEK(fh, 0, SEEK_END); } while (ret == -1 && errno == EINTR); if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); return false; } } fd = -1; } closeFileHandle = true; return true; }
/* This opens the specified library, mmaps it into memory, and searches for the QT_PLUGIN_VERIFICATION_DATA. The advantage of this approach is that we can get the verification data without have to actually load the library. This lets us detect mismatches more safely. Returns false if version/key information is not present, or if the information could not be read. Returns true if version/key information is present and successfully read. */ static bool qt_unix_query(const QString &library, uint *version, bool *debug, QByteArray *key, QLibraryPrivate *lib = 0) { QFile file(library); if (!file.open(QIODevice::ReadOnly)) { if (lib) lib->errorString = file.errorString(); if (qt_debug_component()) { qWarning("%s: %s", (const char*) QFile::encodeName(library), qPrintable(qt_error_string(errno))); } return false; } QByteArray data; const char *filedata = 0; ulong fdlen = file.size(); filedata = (char *) file.map(0, fdlen); if (filedata == 0) { // try reading the data into memory instead data = file.readAll(); filedata = data.constData(); fdlen = data.size(); } /* ELF binaries on GNU, have .qplugin sections. */ long pos = 0; const char pattern[] = "pattern=QT_PLUGIN_VERIFICATION_DATA"; const ulong plen = qstrlen(pattern); #if defined (Q_OF_ELF) && defined(Q_CC_GNU) int r = QElfParser().parse(filedata, fdlen, library, lib, &pos, &fdlen); if (r == QElfParser::NoQtSection) { if (pos > 0) { // find inside .rodata long rel = qt_find_pattern(filedata + pos, fdlen, pattern, plen); if (rel < 0) { pos = -1; } else { pos += rel; } } else { pos = qt_find_pattern(filedata, fdlen, pattern, plen); } } else if (r != QElfParser::Ok) { if (lib && qt_debug_component()) { qWarning("QElfParser: %s",qPrintable(lib->errorString)); } return false; } #else pos = qt_find_pattern(filedata, fdlen, pattern, plen); #endif // defined(Q_OF_ELF) && defined(Q_CC_GNU) bool ret = false; if (pos >= 0) ret = qt_parse_pattern(filedata + pos, version, debug, key); if (!ret && lib) lib->errorString = QLibrary::tr("Plugin verification data mismatch in '%1'").arg(library); file.close(); return ret; }
uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size, QFile::MemoryMapFlags flags) { #ifndef Q_OS_WINPHONE Q_Q(QFSFileEngine); Q_UNUSED(flags); if (openMode == QFile::NotOpen) { q->setError(QFile::PermissionsError, qt_error_string(ERROR_ACCESS_DENIED)); return 0; } if (offset == 0 && size == 0) { q->setError(QFile::UnspecifiedError, qt_error_string(ERROR_INVALID_PARAMETER)); return 0; } // check/setup args to map DWORD access = 0; if (flags & QFileDevice::MapPrivateOption) { #ifdef FILE_MAP_COPY access = FILE_MAP_COPY; #else q->setError(QFile::UnspecifiedError, "MapPrivateOption unsupported"); return 0; #endif } else if (openMode & QIODevice::WriteOnly) { access = FILE_MAP_WRITE; } else if (openMode & QIODevice::ReadOnly) { access = FILE_MAP_READ; } if (mapHandle == NULL) { // get handle to the file HANDLE handle = fileHandle; #ifndef Q_OS_WINCE if (handle == INVALID_HANDLE_VALUE && fh) handle = (HANDLE)::_get_osfhandle(QT_FILENO(fh)); #endif #ifdef Q_USE_DEPRECATED_MAP_API nativeClose(); // handle automatically closed by kernel with mapHandle (below). handle = ::CreateFileForMapping((const wchar_t*)fileEntry.nativeFilePath().utf16(), GENERIC_READ | (openMode & QIODevice::WriteOnly ? GENERIC_WRITE : 0), 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); // Since this is a special case, we check if the return value was NULL and if so // we change it to INVALID_HANDLE_VALUE to follow the logic inside this function. if(0 == handle) handle = INVALID_HANDLE_VALUE; #endif if (handle == INVALID_HANDLE_VALUE) { q->setError(QFile::PermissionsError, qt_error_string(ERROR_ACCESS_DENIED)); return 0; } // first create the file mapping handle DWORD protection = (openMode & QIODevice::WriteOnly) ? PAGE_READWRITE : PAGE_READONLY; #ifndef Q_OS_WINRT mapHandle = ::CreateFileMapping(handle, 0, protection, 0, 0, 0); #else mapHandle = ::CreateFileMappingFromApp(handle, 0, protection, 0, 0); #endif if (mapHandle == NULL) { q->setError(QFile::PermissionsError, qt_error_string()); #ifdef Q_USE_DEPRECATED_MAP_API ::CloseHandle(handle); #endif return 0; } } DWORD offsetHi = offset >> 32; DWORD offsetLo = offset & Q_UINT64_C(0xffffffff); SYSTEM_INFO sysinfo; #ifndef Q_OS_WINRT ::GetSystemInfo(&sysinfo); #else ::GetNativeSystemInfo(&sysinfo); #endif DWORD mask = sysinfo.dwAllocationGranularity - 1; DWORD extra = offset & mask; if (extra) offsetLo &= ~mask; // attempt to create the map #ifndef Q_OS_WINRT LPVOID mapAddress = ::MapViewOfFile(mapHandle, access, offsetHi, offsetLo, size + extra); #else LPVOID mapAddress = ::MapViewOfFileFromApp(mapHandle, access, (ULONG64(offsetHi) << 32) + offsetLo, size + extra); #endif if (mapAddress) { uchar *address = extra + static_cast<uchar*>(mapAddress); maps[address] = extra; return address; } switch(GetLastError()) { case ERROR_ACCESS_DENIED: q->setError(QFile::PermissionsError, qt_error_string()); break; case ERROR_INVALID_PARAMETER: // size are out of bounds default: q->setError(QFile::UnspecifiedError, qt_error_string()); } ::CloseHandle(mapHandle); mapHandle = NULL; #else // !Q_OS_WINPHONE Q_UNUSED(offset); Q_UNUSED(size); Q_UNUSED(flags); Q_UNIMPLEMENTED(); #endif // Q_OS_WINPHONE return 0; }
void MainWindow::setup() { bool ok; QString host, user, pw, dBase; QFile file("../UHCore/Core/config/database.yaml"); if (!file.exists()) { qDebug()<<"No database config found!!"; } if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { closeDownRequest = true; return; } QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); if (line.startsWith("mysql_log_user")) { user = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_password")) { pw = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_server")) { host = line.section(":",1,1).trimmed(); } if (line.startsWith("mysql_log_db")) { dBase = line.section(":",1,1).trimmed(); } } user = QInputDialog::getText ( this, "Accompany DB", "User:"******"Accompany DB", "Password:"******"Accompany DB", "Host:",QLineEdit::Normal, host, &ok); if (!ok) { closeDownRequest = true; return; }; dBase = QInputDialog::getText ( this, "Accompany DB", "Database:",QLineEdit::Normal, dBase, &ok); if (!ok) { closeDownRequest = true; return; }; ui->locnLabel->setText(lv + ":" + user + ":" + host + ":" + dBase); db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName(host); db.setDatabaseName(dBase); db.setUserName(user); db.setPassword(pw); dbOpen = db.open(); if (!dbOpen) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Critical); msgBox.setText("Database error - login problem - see console log!"); msgBox.exec(); qCritical("Cannot open database: %s (%s)", db.lastError().text().toLatin1().data(), qt_error_string().toLocal8Bit().data()); closeDownRequest = true; return; } else { qDebug() << "Database Opened"; } // get experimental location QSqlQuery query("SELECT ExperimentalLocationId FROM SessionControl WHERE SessionId = 1 LIMIT 1"); if (query.next()) { experimentLocation = query.value(0).toString(); } else { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Critical); msgBox.setText("Can find session control table!"); msgBox.exec(); closeDownRequest = true; return; } fillLanguageCombo(); fillSensorCombo(); }
/*! \internal */ bool QFSFileEnginePrivate::closeFdFh() { Q_Q(QFSFileEngine); if (fd == -1 && !fh #ifdef Q_OS_SYMBIAN && !symbianFile.SubSessionHandle() #ifndef QT_SYMBIAN_USE_NATIVE_FILEMAP && fileHandleForMaps == -1 #endif #endif ) return false; // Flush the file if it's buffered, and if the last flush didn't fail. bool flushed = !fh || (!lastFlushFailed && q->flush()); bool closed = true; tried_stat = 0; #if defined(Q_OS_SYMBIAN) && !defined(QT_SYMBIAN_USE_NATIVE_FILEMAP) // Map handle is always owned by us so always close it if (fileHandleForMaps >= 0) { QT_CLOSE(fileHandleForMaps); fileHandleForMaps = -1; } #endif // Close the file if we created the handle. if (closeFileHandle) { int ret; do { #ifdef Q_OS_SYMBIAN if (symbianFile.SubSessionHandle()) { symbianFile.Close(); ret = 0; } else #endif if (fh) { // Close buffered file. ret = fclose(fh) != 0 ? -1 : 0; } else { // Close unbuffered file. ret = QT_CLOSE(fd); } } while (ret == -1 && errno == EINTR); // We must reset these guys regardless; calling close again after a // failed close causes crashes on some systems. fh = 0; fd = -1; closed = (ret == 0); } // Report errors. if (!flushed || !closed) { if (flushed) { // If not flushed, we want the flush error to fall through. q->setError(QFile::UnspecifiedError, qt_error_string(errno)); } return false; } return true; }
void QLocalServerPrivate::setError(const QString &function) { int windowsError = GetLastError(); errorString = QString::fromLatin1("%1: %2").arg(function).arg(qt_error_string(windowsError)); error = QAbstractSocket::UnknownSocketError; }