PageRenderTime 61ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/qt/qtbase/src/corelib/kernel/qsharedmemory.cpp

https://gitlab.com/x33n/phantomjs
C++ | 602 lines | 234 code | 45 blank | 323 comment | 33 complexity | fb0002a6b8027351688bb9d805544237 MD5 | raw file
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
  4. ** Contact: http://www.qt-project.org/legal
  5. **
  6. ** This file is part of the QtCore module of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:LGPL$
  9. ** Commercial License Usage
  10. ** Licensees holding valid commercial Qt licenses may use this file in
  11. ** accordance with the commercial license agreement provided with the
  12. ** Software or, alternatively, in accordance with the terms contained in
  13. ** a written agreement between you and Digia. For licensing terms and
  14. ** conditions see http://qt.digia.com/licensing. For further information
  15. ** use the contact form at http://qt.digia.com/contact-us.
  16. **
  17. ** GNU Lesser General Public License Usage
  18. ** Alternatively, this file may be used under the terms of the GNU Lesser
  19. ** General Public License version 2.1 as published by the Free Software
  20. ** Foundation and appearing in the file LICENSE.LGPL included in the
  21. ** packaging of this file. Please review the following information to
  22. ** ensure the GNU Lesser General Public License version 2.1 requirements
  23. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  24. **
  25. ** In addition, as a special exception, Digia gives you certain additional
  26. ** rights. These rights are described in the Digia Qt LGPL Exception
  27. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  28. **
  29. ** GNU General Public License Usage
  30. ** Alternatively, this file may be used under the terms of the GNU
  31. ** General Public License version 3.0 as published by the Free Software
  32. ** Foundation and appearing in the file LICENSE.GPL included in the
  33. ** packaging of this file. Please review the following information to
  34. ** ensure the GNU General Public License version 3.0 requirements will be
  35. ** met: http://www.gnu.org/copyleft/gpl.html.
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. #include "qsharedmemory.h"
  42. #include "qsharedmemory_p.h"
  43. #include "qsystemsemaphore.h"
  44. #include <qdir.h>
  45. #include <qcryptographichash.h>
  46. #include <qdebug.h>
  47. #ifdef Q_OS_WIN
  48. # include <qt_windows.h>
  49. #endif
  50. QT_BEGIN_NAMESPACE
  51. #if !(defined(QT_NO_SHAREDMEMORY) && defined(QT_NO_SYSTEMSEMAPHORE))
  52. /*!
  53. \internal
  54. Generate a string from the key which can be any unicode string into
  55. the subset that the win/unix kernel allows.
  56. On Unix this will be a file name
  57. */
  58. QString
  59. QSharedMemoryPrivate::makePlatformSafeKey(const QString &key,
  60. const QString &prefix)
  61. {
  62. if (key.isEmpty())
  63. return QString();
  64. QString result = prefix;
  65. QString part1 = key;
  66. part1.replace(QRegExp(QLatin1String("[^A-Za-z]")), QString());
  67. result.append(part1);
  68. QByteArray hex = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Sha1).toHex();
  69. result.append(QLatin1String(hex));
  70. #ifdef Q_OS_WIN
  71. return result;
  72. #else
  73. return QDir::tempPath() + QLatin1Char('/') + result;
  74. #endif
  75. }
  76. #endif // QT_NO_SHAREDMEMORY && QT_NO_SHAREDMEMORY
  77. #ifndef QT_NO_SHAREDMEMORY
  78. /*!
  79. \class QSharedMemory
  80. \inmodule QtCore
  81. \since 4.4
  82. \brief The QSharedMemory class provides access to a shared memory segment.
  83. QSharedMemory provides access to a shared memory segment by multiple
  84. threads and processes. It also provides a way for a single thread or
  85. process to lock the memory for exclusive access.
  86. When using this class, be aware of the following platform
  87. differences:
  88. \list
  89. \li Windows: QSharedMemory does not "own" the shared memory segment.
  90. When all threads or processes that have an instance of QSharedMemory
  91. attached to a particular shared memory segment have either destroyed
  92. their instance of QSharedMemory or exited, the Windows kernel
  93. releases the shared memory segment automatically.
  94. \li Unix: QSharedMemory "owns" the shared memory segment. When the
  95. last thread or process that has an instance of QSharedMemory
  96. attached to a particular shared memory segment detaches from the
  97. segment by destroying its instance of QSharedMemory, the Unix kernel
  98. release the shared memory segment. But if that last thread or
  99. process crashes without running the QSharedMemory destructor, the
  100. shared memory segment survives the crash.
  101. \li HP-UX: Only one attach to a shared memory segment is allowed per
  102. process. This means that QSharedMemory should not be used across
  103. multiple threads in the same process in HP-UX.
  104. \endlist
  105. Remember to lock the shared memory with lock() before reading from
  106. or writing to the shared memory, and remember to release the lock
  107. with unlock() after you are done.
  108. Unlike QtSharedMemory, QSharedMemory automatically destroys the
  109. shared memory segment when the last instance of QSharedMemory is
  110. detached from the segment, and no references to the segment
  111. remain. Do not mix using QtSharedMemory and QSharedMemory. Port
  112. everything to QSharedMemory.
  113. \warning QSharedMemory changes the key in a Qt-specific way, unless otherwise
  114. specified. Interoperation with non-Qt applications is achieved by first creating
  115. a default shared memory with QSharedMemory() and then setting a native key with
  116. setNativeKey(). When using native keys, shared memory is not protected against
  117. multiple accesses on it (e.g. unable to lock()) and a user-defined mechanism
  118. should be used to achieve a such protection.
  119. */
  120. /*!
  121. \overload QSharedMemory()
  122. Constructs a shared memory object with the given \a parent. The
  123. shared memory object's key is not set by the constructor, so the
  124. shared memory object does not have an underlying shared memory
  125. segment attached. The key must be set with setKey() or setNativeKey()
  126. before create() or attach() can be used.
  127. \sa setKey()
  128. */
  129. QSharedMemory::QSharedMemory(QObject *parent)
  130. : QObject(*new QSharedMemoryPrivate, parent)
  131. {
  132. }
  133. /*!
  134. Constructs a shared memory object with the given \a parent and with
  135. its key set to \a key. Because its key is set, its create() and
  136. attach() functions can be called.
  137. \sa setKey(), create(), attach()
  138. */
  139. QSharedMemory::QSharedMemory(const QString &key, QObject *parent)
  140. : QObject(*new QSharedMemoryPrivate, parent)
  141. {
  142. setKey(key);
  143. }
  144. /*!
  145. The destructor clears the key, which forces the shared memory object
  146. to \l {detach()} {detach} from its underlying shared memory
  147. segment. If this shared memory object is the last one connected to
  148. the shared memory segment, the detach() operation destroys the
  149. shared memory segment.
  150. \sa detach(), isAttached()
  151. */
  152. QSharedMemory::~QSharedMemory()
  153. {
  154. setKey(QString());
  155. }
  156. /*!
  157. Sets the platform independent \a key for this shared memory object. If \a key
  158. is the same as the current key, the function returns without doing anything.
  159. You can call key() to retrieve the platform independent key. Internally,
  160. QSharedMemory converts this key into a platform specific key. If you instead
  161. call nativeKey(), you will get the platform specific, converted key.
  162. If the shared memory object is attached to an underlying shared memory
  163. segment, it will \l {detach()} {detach} from it before setting the new key.
  164. This function does not do an attach().
  165. \sa key(), nativeKey(), isAttached()
  166. */
  167. void QSharedMemory::setKey(const QString &key)
  168. {
  169. Q_D(QSharedMemory);
  170. if (key == d->key && d->makePlatformSafeKey(key) == d->nativeKey)
  171. return;
  172. if (isAttached())
  173. detach();
  174. d->cleanHandle();
  175. d->key = key;
  176. d->nativeKey = d->makePlatformSafeKey(key);
  177. }
  178. /*!
  179. \since 4.8
  180. Sets the native, platform specific, \a key for this shared memory object. If
  181. \a key is the same as the current native key, the function returns without
  182. doing anything. If all you want is to assign a key to a segment, you should
  183. call setKey() instead.
  184. You can call nativeKey() to retrieve the native key. If a native key has been
  185. assigned, calling key() will return a null string.
  186. If the shared memory object is attached to an underlying shared memory
  187. segment, it will \l {detach()} {detach} from it before setting the new key.
  188. This function does not do an attach().
  189. The application will not be portable if you set a native key.
  190. \sa nativeKey(), key(), isAttached()
  191. */
  192. void QSharedMemory::setNativeKey(const QString &key)
  193. {
  194. Q_D(QSharedMemory);
  195. if (key == d->nativeKey && d->key.isNull())
  196. return;
  197. if (isAttached())
  198. detach();
  199. d->cleanHandle();
  200. d->key = QString();
  201. d->nativeKey = key;
  202. }
  203. bool QSharedMemoryPrivate::initKey()
  204. {
  205. if (!cleanHandle())
  206. return false;
  207. #ifndef QT_NO_SYSTEMSEMAPHORE
  208. systemSemaphore.setKey(QString(), 1);
  209. systemSemaphore.setKey(key, 1);
  210. if (systemSemaphore.error() != QSystemSemaphore::NoError) {
  211. QString function = QLatin1String("QSharedMemoryPrivate::initKey");
  212. errorString = QSharedMemory::tr("%1: unable to set key on lock").arg(function);
  213. switch(systemSemaphore.error()) {
  214. case QSystemSemaphore::PermissionDenied:
  215. error = QSharedMemory::PermissionDenied;
  216. break;
  217. case QSystemSemaphore::KeyError:
  218. error = QSharedMemory::KeyError;
  219. break;
  220. case QSystemSemaphore::AlreadyExists:
  221. error = QSharedMemory::AlreadyExists;
  222. break;
  223. case QSystemSemaphore::NotFound:
  224. error = QSharedMemory::NotFound;
  225. break;
  226. case QSystemSemaphore::OutOfResources:
  227. error = QSharedMemory::OutOfResources;
  228. break;
  229. case QSystemSemaphore::UnknownError:
  230. default:
  231. error = QSharedMemory::UnknownError;
  232. break;
  233. }
  234. return false;
  235. }
  236. #endif
  237. errorString = QString();
  238. error = QSharedMemory::NoError;
  239. return true;
  240. }
  241. /*!
  242. Returns the key assigned with setKey() to this shared memory, or a null key
  243. if no key has been assigned, or if the segment is using a nativeKey(). The
  244. key is the identifier used by Qt applications to identify the shared memory
  245. segment.
  246. You can find the native, platform specific, key used by the operating system
  247. by calling nativeKey().
  248. \sa setKey(), setNativeKey()
  249. */
  250. QString QSharedMemory::key() const
  251. {
  252. Q_D(const QSharedMemory);
  253. return d->key;
  254. }
  255. /*!
  256. \since 4.8
  257. Returns the native, platform specific, key for this shared memory object. The
  258. native key is the identifier used by the operating system to identify the
  259. shared memory segment.
  260. You can use the native key to access shared memory segments that have not
  261. been created by Qt, or to grant shared memory access to non-Qt applications.
  262. \sa setKey(), setNativeKey()
  263. */
  264. QString QSharedMemory::nativeKey() const
  265. {
  266. Q_D(const QSharedMemory);
  267. return d->nativeKey;
  268. }
  269. /*!
  270. Creates a shared memory segment of \a size bytes with the key passed to the
  271. constructor, set with setKey() or set with setNativeKey(), then attaches to
  272. the new shared memory segment with the given access \a mode and returns
  273. \tt true. If a shared memory segment identified by the key already exists,
  274. the attach operation is not performed and \tt false is returned. When the
  275. return value is \tt false, call error() to determine which error occurred.
  276. \sa error()
  277. */
  278. bool QSharedMemory::create(int size, AccessMode mode)
  279. {
  280. Q_D(QSharedMemory);
  281. if (!d->initKey())
  282. return false;
  283. #ifndef QT_NO_SYSTEMSEMAPHORE
  284. #ifndef Q_OS_WIN
  285. // Take ownership and force set initialValue because the semaphore
  286. // might have already existed from a previous crash.
  287. d->systemSemaphore.setKey(d->key, 1, QSystemSemaphore::Create);
  288. #endif
  289. #endif
  290. QString function = QLatin1String("QSharedMemory::create");
  291. #ifndef QT_NO_SYSTEMSEMAPHORE
  292. QSharedMemoryLocker lock(this);
  293. if (!d->key.isNull() && !d->tryLocker(&lock, function))
  294. return false;
  295. #endif
  296. if (size <= 0) {
  297. d->error = QSharedMemory::InvalidSize;
  298. d->errorString =
  299. QSharedMemory::tr("%1: create size is less then 0").arg(function);
  300. return false;
  301. }
  302. if (!d->create(size))
  303. return false;
  304. return d->attach(mode);
  305. }
  306. /*!
  307. Returns the size of the attached shared memory segment. If no shared
  308. memory segment is attached, 0 is returned.
  309. \sa create(), attach()
  310. */
  311. int QSharedMemory::size() const
  312. {
  313. Q_D(const QSharedMemory);
  314. return d->size;
  315. }
  316. /*!
  317. \enum QSharedMemory::AccessMode
  318. \value ReadOnly The shared memory segment is read-only. Writing to
  319. the shared memory segment is not allowed. An attempt to write to a
  320. shared memory segment created with ReadOnly causes the program to
  321. abort.
  322. \value ReadWrite Reading and writing the shared memory segment are
  323. both allowed.
  324. */
  325. /*!
  326. Attempts to attach the process to the shared memory segment
  327. identified by the key that was passed to the constructor or to a
  328. call to setKey() or setNativeKey(). The access \a mode is \l {QSharedMemory::}
  329. {ReadWrite} by default. It can also be \l {QSharedMemory::}
  330. {ReadOnly}. Returns \c true if the attach operation is successful. If
  331. false is returned, call error() to determine which error occurred.
  332. After attaching the shared memory segment, a pointer to the shared
  333. memory can be obtained by calling data().
  334. \sa isAttached(), detach(), create()
  335. */
  336. bool QSharedMemory::attach(AccessMode mode)
  337. {
  338. Q_D(QSharedMemory);
  339. if (isAttached() || !d->initKey())
  340. return false;
  341. #ifndef QT_NO_SYSTEMSEMAPHORE
  342. QSharedMemoryLocker lock(this);
  343. if (!d->key.isNull() && !d->tryLocker(&lock, QLatin1String("QSharedMemory::attach")))
  344. return false;
  345. #endif
  346. if (isAttached() || !d->handle())
  347. return false;
  348. return d->attach(mode);
  349. }
  350. /*!
  351. Returns \c true if this process is attached to the shared memory
  352. segment.
  353. \sa attach(), detach()
  354. */
  355. bool QSharedMemory::isAttached() const
  356. {
  357. Q_D(const QSharedMemory);
  358. return (0 != d->memory);
  359. }
  360. /*!
  361. Detaches the process from the shared memory segment. If this was the
  362. last process attached to the shared memory segment, then the shared
  363. memory segment is released by the system, i.e., the contents are
  364. destroyed. The function returns \c true if it detaches the shared
  365. memory segment. If it returns \c false, it usually means the segment
  366. either isn't attached, or it is locked by another process.
  367. \sa attach(), isAttached()
  368. */
  369. bool QSharedMemory::detach()
  370. {
  371. Q_D(QSharedMemory);
  372. if (!isAttached())
  373. return false;
  374. #ifndef QT_NO_SYSTEMSEMAPHORE
  375. QSharedMemoryLocker lock(this);
  376. if (!d->key.isNull() && !d->tryLocker(&lock, QLatin1String("QSharedMemory::detach")))
  377. return false;
  378. #endif
  379. return d->detach();
  380. }
  381. /*!
  382. Returns a pointer to the contents of the shared memory segment, if
  383. one is attached. Otherwise it returns null. Remember to lock the
  384. shared memory with lock() before reading from or writing to the
  385. shared memory, and remember to release the lock with unlock() after
  386. you are done.
  387. \sa attach()
  388. */
  389. void *QSharedMemory::data()
  390. {
  391. Q_D(QSharedMemory);
  392. return d->memory;
  393. }
  394. /*!
  395. Returns a const pointer to the contents of the shared memory
  396. segment, if one is attached. Otherwise it returns null. Remember to
  397. lock the shared memory with lock() before reading from or writing to
  398. the shared memory, and remember to release the lock with unlock()
  399. after you are done.
  400. \sa attach(), create()
  401. */
  402. const void* QSharedMemory::constData() const
  403. {
  404. Q_D(const QSharedMemory);
  405. return d->memory;
  406. }
  407. /*!
  408. \overload data()
  409. */
  410. const void *QSharedMemory::data() const
  411. {
  412. Q_D(const QSharedMemory);
  413. return d->memory;
  414. }
  415. #ifndef QT_NO_SYSTEMSEMAPHORE
  416. /*!
  417. This is a semaphore that locks the shared memory segment for access
  418. by this process and returns \c true. If another process has locked the
  419. segment, this function blocks until the lock is released. Then it
  420. acquires the lock and returns \c true. If this function returns \c false,
  421. it means that you have ignored a false return from create() or attach(),
  422. that you have set the key with setNativeKey() or that
  423. QSystemSemaphore::acquire() failed due to an unknown system error.
  424. \sa unlock(), data(), QSystemSemaphore::acquire()
  425. */
  426. bool QSharedMemory::lock()
  427. {
  428. Q_D(QSharedMemory);
  429. if (d->lockedByMe) {
  430. qWarning("QSharedMemory::lock: already locked");
  431. return true;
  432. }
  433. if (d->systemSemaphore.acquire()) {
  434. d->lockedByMe = true;
  435. return true;
  436. }
  437. QString function = QLatin1String("QSharedMemory::lock");
  438. d->errorString = QSharedMemory::tr("%1: unable to lock").arg(function);
  439. d->error = QSharedMemory::LockError;
  440. return false;
  441. }
  442. /*!
  443. Releases the lock on the shared memory segment and returns \c true, if
  444. the lock is currently held by this process. If the segment is not
  445. locked, or if the lock is held by another process, nothing happens
  446. and false is returned.
  447. \sa lock()
  448. */
  449. bool QSharedMemory::unlock()
  450. {
  451. Q_D(QSharedMemory);
  452. if (!d->lockedByMe)
  453. return false;
  454. d->lockedByMe = false;
  455. if (d->systemSemaphore.release())
  456. return true;
  457. QString function = QLatin1String("QSharedMemory::unlock");
  458. d->errorString = QSharedMemory::tr("%1: unable to unlock").arg(function);
  459. d->error = QSharedMemory::LockError;
  460. return false;
  461. }
  462. #endif // QT_NO_SYSTEMSEMAPHORE
  463. /*!
  464. \enum QSharedMemory::SharedMemoryError
  465. \value NoError No error occurred.
  466. \value PermissionDenied The operation failed because the caller
  467. didn't have the required permissions.
  468. \value InvalidSize A create operation failed because the requested
  469. size was invalid.
  470. \value KeyError The operation failed because of an invalid key.
  471. \value AlreadyExists A create() operation failed because a shared
  472. memory segment with the specified key already existed.
  473. \value NotFound An attach() failed because a shared memory segment
  474. with the specified key could not be found.
  475. \value LockError The attempt to lock() the shared memory segment
  476. failed because create() or attach() failed and returned false, or
  477. because a system error occurred in QSystemSemaphore::acquire().
  478. \value OutOfResources A create() operation failed because there was
  479. not enough memory available to fill the request.
  480. \value UnknownError Something else happened and it was bad.
  481. */
  482. /*!
  483. Returns a value indicating whether an error occurred, and, if so,
  484. which error it was.
  485. \sa errorString()
  486. */
  487. QSharedMemory::SharedMemoryError QSharedMemory::error() const
  488. {
  489. Q_D(const QSharedMemory);
  490. return d->error;
  491. }
  492. /*!
  493. Returns a text description of the last error that occurred. If
  494. error() returns an \l {QSharedMemory::SharedMemoryError} {error
  495. value}, call this function to get a text string that describes the
  496. error.
  497. \sa error()
  498. */
  499. QString QSharedMemory::errorString() const
  500. {
  501. Q_D(const QSharedMemory);
  502. return d->errorString;
  503. }
  504. #endif // QT_NO_SHAREDMEMORY
  505. QT_END_NAMESPACE