1 /****************************************************************************
2 **
3 ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of a Qt Solutions component.
8 **
9 ** Commercial Usage
10 ** Licensees holding valid Qt Commercial licenses may use this file in
11 ** accordance with the Qt Solutions Commercial License Agreement provided
12 ** with the Software or, alternatively, in accordance with the terms
13 ** contained in a written agreement between you and Nokia.
14 **
15 ** GNU Lesser General Public License Usage
16 ** Alternatively, this file may be used under the terms of the GNU Lesser
17 ** General Public License version 2.1 as published by the Free Software
18 ** Foundation and appearing in the file LICENSE.LGPL included in the
19 ** packaging of this file.  Please review the following information to
20 ** ensure the GNU Lesser General Public License version 2.1 requirements
21 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22 **
23 ** In addition, as a special exception, Nokia gives you certain
24 ** additional rights. These rights are described in the Nokia Qt LGPL
25 ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
26 ** package.
27 **
28 ** GNU General Public License Usage
29 ** Alternatively, this file may be used under the terms of the GNU
30 ** General Public License version 3.0 as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL included in the
32 ** packaging of this file.  Please review the following information to
33 ** ensure the GNU General Public License version 3.0 requirements will be
34 ** met: http://www.gnu.org/copyleft/gpl.html.
35 **
36 ** Please note Third Party Software included with Qt Solutions may impose
37 ** additional restrictions and it is the user's responsibility to ensure
38 ** that they have met the licensing requirements of the GPL, LGPL, or Qt
39 ** Solutions Commercial license and the relevant license of the Third
40 ** Party Software they are using.
41 **
42 ** If you are unsure which license is appropriate for your use, please
43 ** contact Nokia at qt-info@nokia.com.
44 **
45 ****************************************************************************/
46 
47 #include "qtlockedfile.h"
48 #include <qt_windows.h>
49 #include <QFileInfo>
50 
51 #define MUTEX_PREFIX "QtLockedFile mutex "
52 // Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS
53 #define MAX_READERS MAXIMUM_WAIT_OBJECTS
54 
55 #if QT_VERSION >= 0x050000
56 #define QT_WA(unicode, ansi) unicode
57 #endif
58 
getMutexHandle(int idx,bool doCreate)59 Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate)
60 {
61     if (mutexname.isEmpty()) {
62         QFileInfo fi(*this);
63         mutexname = QString::fromLatin1(MUTEX_PREFIX)
64                     + fi.absoluteFilePath().toLower();
65     }
66     QString mname(mutexname);
67     if (idx >= 0)
68         mname += QString::number(idx);
69 
70     Qt::HANDLE mutex;
71     if (doCreate) {
72         QT_WA( { mutex = CreateMutexW(NULL, FALSE, (WCHAR*)mname.utf16()); },
73                { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } );
74         if (!mutex) {
75             qErrnoWarning("QtLockedFile::lock(): CreateMutex failed");
76             return 0;
77         }
78     }
79     else {
80         QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (WCHAR*)mname.utf16()); },
81                { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } );
82         if (!mutex) {
83             if (GetLastError() != ERROR_FILE_NOT_FOUND)
84                 qErrnoWarning("QtLockedFile::lock(): OpenMutex failed");
85             return 0;
86         }
87     }
88     return mutex;
89 }
90 
waitMutex(Qt::HANDLE mutex,bool doBlock)91 bool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock)
92 {
93     Q_ASSERT(mutex);
94     DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0);
95     switch (res) {
96     case WAIT_OBJECT_0:
97     case WAIT_ABANDONED:
98         return true;
99         break;
100     case WAIT_TIMEOUT:
101         break;
102     default:
103         qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed");
104     }
105     return false;
106 }
107 
108 
109 
lock(LockMode mode,bool block)110 bool QtLockedFile::lock(LockMode mode, bool block)
111 {
112     if (!isOpen()) {
113         qWarning("QtLockedFile::lock(): file is not opened");
114         return false;
115     }
116 
117     if (mode == NoLock)
118         return unlock();
119 
120     if (mode == m_lock_mode)
121         return true;
122 
123     if (m_lock_mode != NoLock)
124         unlock();
125 
126     if (!wmutex && !(wmutex = getMutexHandle(-1, true)))
127         return false;
128 
129     if (!waitMutex(wmutex, block))
130         return false;
131 
132     if (mode == ReadLock) {
133         int idx = 0;
134         for (; idx < MAX_READERS; idx++) {
135             rmutex = getMutexHandle(idx, false);
136             if (!rmutex || waitMutex(rmutex, false))
137                 break;
138             CloseHandle(rmutex);
139         }
140         bool ok = true;
141         if (idx >= MAX_READERS) {
142             qWarning("QtLockedFile::lock(): too many readers");
143             rmutex = 0;
144             ok = false;
145         }
146         else if (!rmutex) {
147             rmutex = getMutexHandle(idx, true);
148             if (!rmutex || !waitMutex(rmutex, false))
149                 ok = false;
150         }
151         if (!ok && rmutex) {
152             CloseHandle(rmutex);
153             rmutex = 0;
154         }
155         ReleaseMutex(wmutex);
156         if (!ok)
157             return false;
158     }
159     else {
160         Q_ASSERT(rmutexes.isEmpty());
161         for (int i = 0; i < MAX_READERS; i++) {
162             Qt::HANDLE mutex = getMutexHandle(i, false);
163             if (mutex)
164                 rmutexes.append(mutex);
165         }
166         if (rmutexes.size()) {
167             DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(),
168                                                TRUE, block ? INFINITE : 0);
169             if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) {
170                 if (res != WAIT_TIMEOUT)
171                     qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed");
172                 m_lock_mode = WriteLock;  // trick unlock() to clean up - semiyucky
173                 unlock();
174                 return false;
175             }
176         }
177     }
178 
179     m_lock_mode = mode;
180     return true;
181 }
182 
unlock()183 bool QtLockedFile::unlock()
184 {
185     if (!isOpen()) {
186         qWarning("QtLockedFile::unlock(): file is not opened");
187         return false;
188     }
189 
190     if (!isLocked())
191         return true;
192 
193     if (m_lock_mode == ReadLock) {
194         ReleaseMutex(rmutex);
195         CloseHandle(rmutex);
196         rmutex = 0;
197     }
198     else {
199         for (Qt::HANDLE mutex: rmutexes) {
200             ReleaseMutex(mutex);
201             CloseHandle(mutex);
202         }
203         rmutexes.clear();
204         ReleaseMutex(wmutex);
205     }
206 
207     m_lock_mode = QtLockedFile::NoLock;
208     return true;
209 }
210 
~QtLockedFile()211 QtLockedFile::~QtLockedFile()
212 {
213     if (isOpen())
214         unlock();
215     if (wmutex)
216         CloseHandle(wmutex);
217 }
218