summaryrefslogtreecommitdiffstats
path: root/src/publishsubscribe/qsystemreadwritelock_unix.cpp
blob: 7221c02741788fdd1c6cf9c86e920b01704fbf0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsystemreadwritelock_p.h"
#include <QFile>
#include <sys/sem.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <QRegExp>
#include <QCryptographicHash>
#include <QDir>

QTM_BEGIN_NAMESPACE

class QSystemReadWriteLockPrivate
{
public:
    enum SemIndex {
        ActiveReaders = 0,
        TotalWriters,
        ActiveWriterSem,
        NumInstances
    };

    QSystemReadWriteLockPrivate():id(-1),semId(-1),
                    key(QString()),keyFileName(QString()),
                    error(QSystemReadWriteLock::NoError),
                    errorString(QString()){};
    void setError(const QString &errorString);

    key_t id;
    int semId;
    QString key;
    QString keyFileName;

    QSystemReadWriteLock::SystemReadWriteLockError error;
    QString errorString;
};

void QSystemReadWriteLockPrivate::setError(const QString &_errorString)
{
    errorString = _errorString;
    switch (errno) {
        case EPERM:
        case EACCES:
            error = QSystemReadWriteLock::PermissionDenied;
            break;
        case ERANGE:
        case ENOMEM:
        case ENOSPC:
            error = QSystemReadWriteLock::OutOfResources;
            break;
        case EIDRM:
            error = QSystemReadWriteLock::NotFound;
            break;
        default:
            error = QSystemReadWriteLock::UnknownError;
     }
}

/*
    This function is taken from qcore_unix_p.h(qt_safe_open)
    If/when QSystemReadWriteLock is integrated into Qt,
    this function defintion may replaced by the sharedmemory
    definition.
 */
static inline int safe_open(const char *pathname, int flags, mode_t mode = 0777)
{
#ifdef O_CLOEXEC
    flags |= O_CLOEXEC;
#endif
    register int fd;

    do {
        fd = ::open(pathname, flags, mode);
    } while (fd == -1 && errno == EINTR);

    // unknown flags are ignored, so we have no way of verifying if
    // O_CLOEXEC was accepted
    if (fd != -1)
        ::fcntl(fd, F_SETFD, FD_CLOEXEC);
    return fd;
}

/*
    This function is taken from qsharedmemory_unix.cpp.
    If/when QSystemReadWriteLock is integrated into Qt,
    this function defintion may replaced by the sharedmemory
    definition.
 */
int createUnixKeyFile(const QString &fileName)
{
    if (QFile::exists(fileName)) {
        return 0;
    }

    int fd = safe_open(QFile::encodeName(fileName).constData(),
            O_EXCL | O_CREAT | O_RDWR, 0640);

    if (-1 == fd) {
        if (errno == EEXIST)
            return 0;
        return -1;
    } else {
        close(fd);
    }
    return 1;
}

/*
    This function is taken from qsharedmemory_unix.cpp.
    If/when QSystemReadWriteLock is integrated into Qt,
    the function definition may replaced by the sharedmemory
    definition.
 */
QString makePlatformSafeKey(const QString &key,
        const QString &prefix)
{
    if (key.isEmpty())
        return QString();

    QString result = prefix;

    QString part1 = key;
    part1.remove(QRegExp(QLatin1String("[^A-Za-z]")));
    result.append(part1);

    QByteArray hex = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Sha1).toHex();
    result.append(QLatin1String(hex));
    return QDir::tempPath() + QLatin1Char('/') + result;
}

/*
   \class QSystemReadWriteLock

   \brief The QSystemReadWriteLock class provides read-write locking between
   processes.

   A read-write lock is a synchronization tool for protecting resources that can
   be accessed for reading and writing. This type of lock is useful if you want
   to allow multiple processes/threads to have simultaneous read-only access, but as soon
   as one thread wants to write to the resource, all other threads must be
   blocked until the writing is complete.

   QSystemReadWriteLock behaves much like the QReadWriteLock class, but it also
   works across multiple processes (although it also works perfectly well,
   albeit slightly less efficiently, in a single process).  The system
   resources are cleaned up when the last QSystemReadWriteLock instance
   is destroyed.

   The behaviour of QSystemReadWriteLock is such that writers will
   take precedence over readers.  When writers are waiting, any new
   readers must wait until all writers complete.  That is, writers
   can starve readers.
 */

/*
   Implementation Details:

   The QSystemReadWriteLock class uses Linux kernel semaphores to synchronize
   access between readers and writers.

   4 semaphores are used in total.
   activeReaders - number of active readers
   TotalWriters - number of active and pending writers

   ActiveWriterSem - indicates whether a writer is active

   NumInstances - counts the number of instances of QSystemReadWriteLock
                  objects there for a given key.  This is needed
                  to determine whether system resources are
                  safe to clean up during an instance's destruction.

  activeReaders, TotalWriters and NumInstance are used as counters and
  not in the way typical semaphores are used.  e.g.a value of 5 for
  activeReaders indicates that there are currently 5 readers.

  ActiveWriterSem is used as a typical semaphore.  A value of 1
  means there's an free slot for a writer to become active.
 */

/*
  Construct a system read write lock from the provided \a key.

  The \a mode parameter is only used in Unix systems to handle the case
  where underlying system resources such as semaphores survive a process
  crash.  In this case, the next process to instatiate a lock will
  get the resources that survived the crash, and unless \mode is
  Create, the resources will not be reset.
 */
QSystemReadWriteLock::QSystemReadWriteLock(const QString &key, AccessMode mode)
{
    d = new QSystemReadWriteLockPrivate;
    d->key = key;
    d->keyFileName = makePlatformSafeKey(key, QLatin1String("qipc_systemsem_"));

    int built = createUnixKeyFile(d->keyFileName);
    if (built == -1) {
        d->setError(QObject::tr("QSystemReadWriteLock::QSystemReadWriteLock: "
                    "unable to make key file for key: %1(%2)")
                    .arg(key).arg(QString::fromLatin1(strerror(errno))));
        return;
    }

    // Get the unix key for the created file
    d->id = ftok(QFile::encodeName(d->keyFileName).constData(), 'Q');
    if (d->id == -1) {
        d->setError(QObject::tr("QSystemReadWriteLock::QSystemReadWriteLock: "
                        "ftok failed for key %1(%2)")
                    .arg(key).arg(QString::fromLatin1(strerror(errno))));
        return;
    }

    d->semId = ::semget(d->id, 4, IPC_CREAT | IPC_EXCL | 0666);
    bool created = false;
    if (d->semId == -1) {
        if (errno == EEXIST) {
            d->semId = ::semget(d->id, 4,
                    (mode == QSystemReadWriteLock::Create)?IPC_CREAT|0666:0);
            if (d->semId == -1) {
                d->setError(QObject::tr("QSystemReadWriteLock::QSystemReadWriteLock: "
                                    "Unable to access semaphore set for key %1(%2)")
                            .arg(key).arg(QString::fromLatin1(strerror(errno))));
                return;
            }
        } else {
            d->setError(QObject::tr("QSystemReadWriteLock:QSystemReadWriteLock: "
                        "Unable to access semaphore set for key %1(%2)")
                        .arg(key).arg(QString::fromLatin1(strerror(errno))));
            return;
        }
    } else {
        created = true;
    }

    Q_ASSERT(d->semId != -1);
    if (created || mode == QSystemReadWriteLock::Create) {
        typedef union {
            int val;
            struct semid_ds *buf;
            ushort *array;
        }semun;

        semun counterInitVal; //initial value for a "counter" semaphores
        counterInitVal.val = 0;

        semun activeWriterInitVal;//initial value for the "active writer" semaphore
        activeWriterInitVal.val = 1;

        if (-1 == ::semctl(d->semId, QSystemReadWriteLockPrivate::ActiveReaders,
                    SETVAL, counterInitVal) ||
                -1 == ::semctl(d->semId, QSystemReadWriteLockPrivate::TotalWriters,
                    SETVAL, counterInitVal) ||
                -1 == ::semctl(d->semId, QSystemReadWriteLockPrivate::ActiveWriterSem,
                    SETVAL, activeWriterInitVal) ||
                -1 == ::semctl(d->semId, QSystemReadWriteLockPrivate::NumInstances,
                    SETVAL, counterInitVal))
        {
            d->setError(QObject::tr("QSystemReadWriteLock::QSystemReadWriteLock: "
                        "Unable to reset semaphore set for key %1(%2)")
                        .arg(key).arg(QString::fromLatin1(strerror(errno))));
            QFile::remove(d->keyFileName);
            ::semctl(d->semId, 0, IPC_RMID);
            d->semId = -1;
            return;
        }
    }

    struct sembuf op;
    op.sem_num = QSystemReadWriteLockPrivate::NumInstances;
    op.sem_op = 1;
    op.sem_flg = SEM_UNDO;
    int semoprv = ::semop(d->semId, &op, 1);
    if (semoprv == -1) {
        d->setError(QObject::tr("QSystemReadWriteLock::QSystemReadWriteLock: "
                            "Unable to increment NumInstances semaphore "
                            "for key%1(%2)").arg(key).arg(QString::fromLatin1(strerror(errno))));
        d->semId = -1;
        return;
    }
}

/*
  Destroy the lock instance.  The last QSystemReadWriteLock instance
  for a particular key will destroy the underlying system resources.
 */
QSystemReadWriteLock::~QSystemReadWriteLock()
{
    if (d->semId != -1) {
        //decrement and check that there are 0 instances
        //be aware these 2 operations occur together atomically
        struct sembuf ops[2];
        ops[0].sem_num = QSystemReadWriteLockPrivate::NumInstances;
        ops[0].sem_op = -1;
        ops[0].sem_flg = SEM_UNDO | IPC_NOWAIT;

        ops[1].sem_num = QSystemReadWriteLockPrivate::NumInstances;
        ops[1].sem_op = 0;
        ops[1].sem_flg = IPC_NOWAIT;

        //if successful, then delete the semaphore set
        int semoprv  = ::semop(d->semId, ops, 2);
        if (semoprv == 0) {
            if(::semctl(d->semId, 0, IPC_RMID) == -1) {
                qWarning("QSystemReadWriteLock::~QSystemReadWriteLock: "
                         "Unable to remove semaphore %s(%s)",
                         d->key.toLocal8Bit().constData(), strerror(errno));
            }
            QFile::remove(d->keyFileName);
        } else {
            if (errno == EAGAIN) {
                //wasn't 0 instances so just decrement the NumInstances semaphore
                if (::semop(d->semId, ops, 1) == -1) {
                    qWarning("QSystemReadWriteLock::~QSystemReadWriteLock: "
                             "Unable to decrement NumInstances semaphore for key %s(%s)",
                             d->key.toLocal8Bit().constData(), strerror(errno));
                }
            } else {
                qWarning("QSystemReadWriteLock::~QSystemReadWriteLock: "
                         "Unable to decrement and check NumInstances semaphore for key %s(%s)",
                         d->key.toLocal8Bit().constData(), strerror(errno));
                ::semop(d->semId, ops, 1);//try decrement anyway
            }
        }

    }

    Q_ASSERT(d);
    delete d;
    d = 0;
}

/*
  Return the key of the lock as passed to the constructor.
 */
QString QSystemReadWriteLock::key() const
{
    return d->key;
}

/*
  Locks the lock for reading.  The function will block if any thread/process
  has locked for writing.
 */
bool QSystemReadWriteLock::lockForRead()
{
    if (d->semId == -1) {
        d->errorString = QObject::tr("QSystemReadWriteLock::lockForRead: "
                                     "Unable to lock for read for key %1"
                                     "(Lock had not been correctly initialized)").arg(d->key);
        d->error = UnknownError;
        return false;
    }

    struct sembuf ops[2];

    ops[0].sem_num = QSystemReadWriteLockPrivate::ActiveReaders;
    ops[0].sem_op = 1;
    ops[0].sem_flg = SEM_UNDO;

    ops[1].sem_num = QSystemReadWriteLockPrivate::TotalWriters;
    ops[1].sem_op = 0;
    ops[1].sem_flg = 0;

    if (-1 == ::semop(d->semId, ops, 2)) {
        d->setError(QObject::tr("QSystemReadWriteLock::lockForRead: "
                                "Unable to lock for read for key %1(%2)")
                    .arg(d->key).arg(QString::fromLatin1(strerror(errno))));
        return false;
    } else {
        d->errorString.clear();
        d->error = NoError;
        return true;
    }
}

/*
   Locks the lock for writing.  This function will block if another thread/process
   has locked for reading or writing.
 */
bool QSystemReadWriteLock::lockForWrite()
{
    if (d->semId == -1) {
        d->errorString = QObject::tr("QSystemReadWriteLock::lockForWrite: "
                                     "Unable to lock for write for key %1"
                                     "(Lock had not been correctly initialized)").arg(d->key);
        d->error = UnknownError;
        return false;
    }

    struct sembuf op;
    op.sem_num = QSystemReadWriteLockPrivate::TotalWriters;
    op.sem_op = 1;
    op.sem_flg = SEM_UNDO;

    int semoprv = ::semop(d->semId, &op, 1);
    if (semoprv == -1) {
        d->setError(QObject::tr("QSystemReadWriteLock::lockForWrite: "
                                "Could not increment TotalWriters semaphore for key %1(%2)")
                    .arg(d->key).arg(QString::fromLatin1(strerror(errno))));
        return false;
    }

    op.sem_num = QSystemReadWriteLockPrivate::ActiveReaders;
    op.sem_op = 0;
    op.sem_flg = 0;
    semoprv = ::semop(d->semId, &op, 1);
    if (semoprv == -1) {
        d->setError(QObject::tr("QSystemReadWriteLock::lockForWrite: "
                                "Could not detect if all readers were finished for key %1(%2)")
                    .arg(d->key).arg(QString::fromLatin1(strerror(errno))));

        // Decrement our write lock
        op.sem_num = QSystemReadWriteLockPrivate::TotalWriters;
        op.sem_op = -1;
        op.sem_flg = SEM_UNDO;
        ::semop(d->semId, &op, 1);
        return false;
    } else {
        op.sem_num = QSystemReadWriteLockPrivate::ActiveWriterSem;
        op.sem_op = -1;
        op.sem_flg =SEM_UNDO;
        semoprv = ::semop(d->semId, &op, 1);

        if (semoprv == -1) {
            d->setError(QObject::tr("QSystemReadWriteLock::lockForWrite: "
                                    "Could not decrement ActiveWriterSem semaphore for key %1(%2)")
                        .arg(d->key).arg(QString::fromLatin1(strerror(errno))));

            op.sem_num = QSystemReadWriteLockPrivate::TotalWriters;
            op.sem_op = -1;
            op.sem_flg = 0;
            ::semop(d->semId, &op, 1);
            return false;
        }
        d->errorString.clear();
        d->error = NoError;
        return true;
    }
}

/*
  Release the lock.
 */
void QSystemReadWriteLock::unlock()
{
    if (d->semId == -1) {
        d->errorString = QObject::tr("QSystemReadWriteLock::unlock: "
                                     "Unable to unlock for key %1"
                                     "(Lock had not been correctly initialized)").arg(d->key);
        d->error = UnknownError;
        return;
    }

    struct sembuf op;
    op.sem_num = QSystemReadWriteLockPrivate::ActiveReaders;
    op.sem_op = -1;
    op.sem_flg = SEM_UNDO | IPC_NOWAIT;
    if (::semop(d->semId, &op, 1) == 0) {
        //do nothing, succeeded in decrementing number of readers
    } else if (errno == EAGAIN){ //no readers, so check for writers
            struct sembuf ops[3];
            ops[0].sem_num = QSystemReadWriteLockPrivate::ActiveWriterSem;
            ops[0].sem_op = 0;
            ops[0].sem_flg = IPC_NOWAIT;

            ops[1].sem_num = QSystemReadWriteLockPrivate::ActiveWriterSem;
            ops[1].sem_op = 1;
            ops[1].sem_flg = SEM_UNDO;

            ops[2].sem_num = QSystemReadWriteLockPrivate::TotalWriters;
            ops[2].sem_op = -1;
            ops[2].sem_flg = SEM_UNDO;

            if (::semop(d->semId, ops, 3) == -1) {
                if (errno != EAGAIN) {
                    d->setError(QObject::tr("QSystemSemaphoreWriteLock::unlock: "
                                            "Unable to check and update writer semaphores for key %1(%2)")
                                .arg(d->key).arg(QString::fromLatin1(strerror(errno))));
                    return;
                } //Note: EAGAIN indicates that ActiveWriterSem is has a non zero value
                  //indicating there is no current writer, so nothing needs to be done
            }
    } else {
        //error in decrementing readers
        d->setError(QObject::tr("QSystemReadWriteLock::unlock: "
                                "Unable to decrement ActiveReaders semaphore for key %1(%2)")
                    .arg(d->key).arg(QString::fromLatin1(strerror(errno))));
        return;
    }
    d->errorString.clear();
    d->error = NoError;
}

/*
  Returns the error code of the last encountered error
 */
QSystemReadWriteLock::SystemReadWriteLockError QSystemReadWriteLock::error() const {
    return d->error;
}

/*
  Returns a string describing the last encountered error
 */
QString QSystemReadWriteLock::errorString() const
{
    return d->errorString;
}

QTM_END_NAMESPACE