summaryrefslogtreecommitdiffstats
path: root/src/corelib/io/qsettings_win.cpp
blob: 7c6b782acd3f9f6a77ee8e543321652ee7ae8c67 (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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsettings.h"

#ifndef QT_NO_SETTINGS

#include "qsettings_p.h"
#include "qvector.h"
#include "qmap.h"
#include "qdebug.h"
#include <qt_windows.h>

// See "Accessing an Alternate Registry View" at:
// http://msdn.microsoft.com/en-us/library/aa384129%28VS.85%29.aspx
#ifndef KEY_WOW64_64KEY
   // Access a 32-bit key from either a 32-bit or 64-bit application.
#  define KEY_WOW64_64KEY 0x0100
#endif

#ifndef KEY_WOW64_32KEY
   // Access a 64-bit key from either a 32-bit or 64-bit application.
#  define KEY_WOW64_32KEY 0x0200
#endif

QT_BEGIN_NAMESPACE

/*  Keys are stored in QStrings. If the variable name starts with 'u', this is a "user"
    key, ie. "foo/bar/alpha/beta". If the variable name starts with 'r', this is a "registry"
    key, ie. "\foo\bar\alpha\beta". */

/*******************************************************************************
** Some convenience functions
*/

/*
  We don't use KEY_ALL_ACCESS because it gives more rights than what we
  need. See task 199061.
 */
static const REGSAM registryPermissions = KEY_READ | KEY_WRITE;

static QString keyPath(const QString &rKey)
{
    int idx = rKey.lastIndexOf(QLatin1Char('\\'));
    if (idx == -1)
        return QString();
    return rKey.left(idx + 1);
}

static QString keyName(const QString &rKey)
{
    int idx = rKey.lastIndexOf(QLatin1Char('\\'));

    QString res;
    if (idx == -1)
        res = rKey;
    else
        res = rKey.mid(idx + 1);

    if (res == QLatin1String("Default") || res == QLatin1String("."))
        res = QLatin1String("");

    return res;
}

static QString escapedKey(QString uKey)
{
    QChar *data = uKey.data();
    int l = uKey.length();
    for (int i = 0; i < l; ++i) {
        ushort &ucs = data[i].unicode();
        if (ucs == '\\')
            ucs = '/';
        else if (ucs == '/')
            ucs = '\\';
    }
    return uKey;
}

static QString unescapedKey(QString rKey)
{
    return escapedKey(rKey);
}

typedef QMap<QString, QString> NameSet;

static void mergeKeySets(NameSet *dest, const NameSet &src)
{
    NameSet::const_iterator it = src.constBegin();
    for (; it != src.constEnd(); ++it)
        dest->insert(unescapedKey(it.key()), QString());
}

static void mergeKeySets(NameSet *dest, const QStringList &src)
{
    QStringList::const_iterator it = src.constBegin();
    for (; it != src.constEnd(); ++it)
        dest->insert(unescapedKey(*it), QString());
}

/*******************************************************************************
** Wrappers for the insane windows registry API
*/

static QString errorCodeToString(DWORD errorCode)
{
    wchar_t *data = 0;
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, errorCode, 0, data, 0, 0);
    QString result = QString::fromWCharArray(data);

    if (data != 0)
        LocalFree(data);

    if (result.endsWith(QLatin1Char('\n')))
        result.truncate(result.length() - 1);

    return result;
}

// Open a key with the specified "perms".
// "access" is to explicitly use the 32- or 64-bit branch.
static HKEY openKey(HKEY parentHandle, REGSAM perms, const QString &rSubKey, REGSAM access = 0)
{
    HKEY resultHandle = 0;
    LONG res = RegOpenKeyEx(parentHandle, reinterpret_cast<const wchar_t *>(rSubKey.utf16()),
                            0, perms | access, &resultHandle);

    if (res == ERROR_SUCCESS)
        return resultHandle;

    return 0;
}

// Open a key with the specified "perms", create it if it does not exist.
// "access" is to explicitly use the 32- or 64-bit branch.
static HKEY createOrOpenKey(HKEY parentHandle, REGSAM perms, const QString &rSubKey, REGSAM access = 0)
{
    // try to open it
    HKEY resultHandle = openKey(parentHandle, perms, rSubKey, access);
    if (resultHandle != 0)
        return resultHandle;

    // try to create it
    LONG res = RegCreateKeyEx(parentHandle, reinterpret_cast<const wchar_t *>(rSubKey.utf16()), 0, 0,
                              REG_OPTION_NON_VOLATILE, perms | access, 0, &resultHandle, 0);

    if (res == ERROR_SUCCESS)
        return resultHandle;

    //qWarning("QSettings: Failed to create subkey \"%s\": %s",
    //        rSubKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());

    return 0;
}

// Open or create a key in read-write mode if possible, otherwise read-only.
// "access" is to explicitly use the 32- or 64-bit branch.
static HKEY createOrOpenKey(HKEY parentHandle, const QString &rSubKey, bool *readOnly, REGSAM access = 0)
{
    // try to open or create it read/write
    HKEY resultHandle = createOrOpenKey(parentHandle, registryPermissions, rSubKey, access);
    if (resultHandle != 0) {
        if (readOnly != 0)
            *readOnly = false;
        return resultHandle;
    }

    // try to open or create it read/only
    resultHandle = createOrOpenKey(parentHandle, KEY_READ, rSubKey, access);
    if (resultHandle != 0) {
        if (readOnly != 0)
            *readOnly = true;
        return resultHandle;
    }
    return 0;
}

static QStringList childKeysOrGroups(HKEY parentHandle, QSettingsPrivate::ChildSpec spec)
{
    QStringList result;
    DWORD numKeys;
    DWORD maxKeySize;
    DWORD numSubgroups;
    DWORD maxSubgroupSize;

    // Find the number of keys and subgroups, as well as the max of their lengths.
    LONG res = RegQueryInfoKey(parentHandle, 0, 0, 0, &numSubgroups, &maxSubgroupSize, 0,
                               &numKeys, &maxKeySize, 0, 0, 0);

    if (res != ERROR_SUCCESS) {
        qWarning("QSettings: RegQueryInfoKey() failed: %s", errorCodeToString(res).toLatin1().data());
        return result;
    }

    ++maxSubgroupSize;
    ++maxKeySize;

    int n;
    int m;
    if (spec == QSettingsPrivate::ChildKeys) {
        n = numKeys;
        m = maxKeySize;
    } else {
        n = numSubgroups;
        m = maxSubgroupSize;
    }

    /* The size does not include the terminating null character. */
    ++m;

    // Get the list
    QByteArray buff(m * sizeof(wchar_t), 0);
    for (int i = 0; i < n; ++i) {
        QString item;
        DWORD l = buff.size() / sizeof(wchar_t);
        if (spec == QSettingsPrivate::ChildKeys) {
            res = RegEnumValue(parentHandle, i, reinterpret_cast<wchar_t *>(buff.data()), &l, 0, 0, 0, 0);
        } else {
            res = RegEnumKeyEx(parentHandle, i, reinterpret_cast<wchar_t *>(buff.data()), &l, 0, 0, 0, 0);
        }
        if (res == ERROR_SUCCESS)
            item = QString::fromWCharArray((const wchar_t *)buff.constData(), l);

        if (res != ERROR_SUCCESS) {
            qWarning("QSettings: RegEnumValue failed: %s", errorCodeToString(res).toLatin1().data());
            continue;
        }
        if (item.isEmpty())
            item = QLatin1String(".");
        result.append(item);
    }
    return result;
}

static void allKeys(HKEY parentHandle, const QString &rSubKey, NameSet *result, REGSAM access = 0)
{
    HKEY handle = openKey(parentHandle, KEY_READ, rSubKey, access);
    if (handle == 0)
        return;

    QStringList childKeys = childKeysOrGroups(handle, QSettingsPrivate::ChildKeys);
    QStringList childGroups = childKeysOrGroups(handle, QSettingsPrivate::ChildGroups);
    RegCloseKey(handle);

    for (int i = 0; i < childKeys.size(); ++i) {
        QString s = rSubKey;
        if (!s.isEmpty())
            s += QLatin1Char('\\');
        s += childKeys.at(i);
        result->insert(s, QString());
    }

    for (int i = 0; i < childGroups.size(); ++i) {
        QString s = rSubKey;
        if (!s.isEmpty())
            s += QLatin1Char('\\');
        s += childGroups.at(i);
        allKeys(parentHandle, s, result, access);
    }
}

static void deleteChildGroups(HKEY parentHandle, REGSAM access = 0)
{
    QStringList childGroups = childKeysOrGroups(parentHandle, QSettingsPrivate::ChildGroups);

    for (int i = 0; i < childGroups.size(); ++i) {
        QString group = childGroups.at(i);

        // delete subgroups in group
        HKEY childGroupHandle = openKey(parentHandle, registryPermissions, group, access);
        if (childGroupHandle == 0)
            continue;
        deleteChildGroups(childGroupHandle, access);
        RegCloseKey(childGroupHandle);

        // delete group itself
        LONG res = RegDeleteKey(parentHandle, reinterpret_cast<const wchar_t *>(group.utf16()));
        if (res != ERROR_SUCCESS) {
            qWarning("QSettings: RegDeleteKey failed on subkey \"%s\": %s",
                      group.toLatin1().data(), errorCodeToString(res).toLatin1().data());
            return;
        }
    }
}

/*******************************************************************************
** class RegistryKey
*/

class RegistryKey
{
public:
    RegistryKey(HKEY parent_handle = 0, const QString &key = QString(), bool read_only = true, REGSAM access = 0);
    QString key() const;
    HKEY handle() const;
    HKEY parentHandle() const;
    bool readOnly() const;
    void close();
private:
    HKEY m_parent_handle;
    mutable HKEY m_handle;
    QString m_key;
    mutable bool m_read_only;
    REGSAM m_access;
};

RegistryKey::RegistryKey(HKEY parent_handle, const QString &key, bool read_only, REGSAM access)
    : m_parent_handle(parent_handle),
      m_handle(0),
      m_key(key),
      m_read_only(read_only),
      m_access(access)
{
}

QString RegistryKey::key() const
{
    return m_key;
}

HKEY RegistryKey::handle() const
{
    if (m_handle != 0)
        return m_handle;

    if (m_read_only)
        m_handle = openKey(m_parent_handle, KEY_READ, m_key, m_access);
    else
        m_handle = createOrOpenKey(m_parent_handle, m_key, &m_read_only, m_access);

    return m_handle;
}

HKEY RegistryKey::parentHandle() const
{
    return m_parent_handle;
}

bool RegistryKey::readOnly() const
{
    return m_read_only;
}

void RegistryKey::close()
{
    if (m_handle != 0)
        RegCloseKey(m_handle);
    m_handle = 0;
}

typedef QVector<RegistryKey> RegistryKeyList;

/*******************************************************************************
** class QWinSettingsPrivate
*/

class QWinSettingsPrivate : public QSettingsPrivate
{
public:
    QWinSettingsPrivate(QSettings::Scope scope, const QString &organization,
                        const QString &application, REGSAM access = 0);
    QWinSettingsPrivate(QString rKey, REGSAM access = 0);
    ~QWinSettingsPrivate();

    void remove(const QString &uKey);
    void set(const QString &uKey, const QVariant &value);
    bool get(const QString &uKey, QVariant *value) const;
    QStringList children(const QString &uKey, ChildSpec spec) const;
    void clear();
    void sync();
    void flush();
    bool isWritable() const;
    HKEY writeHandle() const;
    bool readKey(HKEY parentHandle, const QString &rSubKey, QVariant *value) const;
    QString fileName() const;

private:
    RegistryKeyList regList; // list of registry locations to search for keys
    bool deleteWriteHandleOnExit;
    REGSAM access;
};

QWinSettingsPrivate::QWinSettingsPrivate(QSettings::Scope scope, const QString &organization,
                                         const QString &application, REGSAM access)
    : QSettingsPrivate(QSettings::NativeFormat, scope, organization, application),
      access(access)
{
    deleteWriteHandleOnExit = false;

    if (!organization.isEmpty()) {
        QString prefix = QLatin1String("Software\\") + organization;
        QString orgPrefix = prefix + QLatin1String("\\OrganizationDefaults");
        QString appPrefix = prefix + QLatin1Char('\\') + application;

        if (scope == QSettings::UserScope) {
            if (!application.isEmpty())
                regList.append(RegistryKey(HKEY_CURRENT_USER, appPrefix, !regList.isEmpty(), access));

            regList.append(RegistryKey(HKEY_CURRENT_USER, orgPrefix, !regList.isEmpty(), access));
        }

        if (!application.isEmpty())
            regList.append(RegistryKey(HKEY_LOCAL_MACHINE, appPrefix, !regList.isEmpty(), access));

        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, orgPrefix, !regList.isEmpty(), access));
    }

    if (regList.isEmpty())
        setStatus(QSettings::AccessError);
}

QWinSettingsPrivate::QWinSettingsPrivate(QString rPath, REGSAM access)
    : QSettingsPrivate(QSettings::NativeFormat),
      access(access)
{
    deleteWriteHandleOnExit = false;

    if (rPath.startsWith(QLatin1Char('\\')))
        rPath.remove(0, 1);

    int keyLength;
    HKEY keyName;

    if (rPath.startsWith(QLatin1String("HKEY_CURRENT_USER"))) {
        keyLength = 17;
        keyName = HKEY_CURRENT_USER;
    } else if (rPath.startsWith(QLatin1String("HKCU"))) {
        keyLength = 4;
        keyName = HKEY_CURRENT_USER;
    } else if (rPath.startsWith(QLatin1String("HKEY_LOCAL_MACHINE"))) {
        keyLength = 18;
        keyName = HKEY_LOCAL_MACHINE;
    } else if (rPath.startsWith(QLatin1String("HKLM"))) {
        keyLength = 4;
        keyName = HKEY_LOCAL_MACHINE;
    } else if (rPath.startsWith(QLatin1String("HKEY_CLASSES_ROOT"))) {
        keyLength = 17;
        keyName = HKEY_CLASSES_ROOT;
    } else if (rPath.startsWith(QLatin1String("HKCR"))) {
        keyLength = 4;
        keyName = HKEY_CLASSES_ROOT;
    } else if (rPath.startsWith(QLatin1String("HKEY_USERS"))) {
        keyLength = 10;
        keyName = HKEY_USERS;
    } else if (rPath.startsWith(QLatin1String("HKU"))) {
        keyLength = 3;
        keyName = HKEY_USERS;
    } else {
        return;
    }

    if (rPath.length() == keyLength)
        regList.append(RegistryKey(keyName, QString(), false, access));
    else if (rPath[keyLength] == QLatin1Char('\\'))
        regList.append(RegistryKey(keyName, rPath.mid(keyLength+1), false, access));
}

bool QWinSettingsPrivate::readKey(HKEY parentHandle, const QString &rSubKey, QVariant *value) const
{
    QString rSubkeyName = keyName(rSubKey);
    QString rSubkeyPath = keyPath(rSubKey);

    // open a handle on the subkey
    HKEY handle = openKey(parentHandle, KEY_READ, rSubkeyPath, access);
    if (handle == 0)
        return false;

    // get the size and type of the value
    DWORD dataType;
    DWORD dataSize;
    LONG res = RegQueryValueEx(handle, reinterpret_cast<const wchar_t *>(rSubkeyName.utf16()), 0, &dataType, 0, &dataSize);
    if (res != ERROR_SUCCESS) {
        RegCloseKey(handle);
        return false;
    }

    // workaround for rare cases where trailing '\0' are missing in registry
    if (dataType == REG_SZ || dataType == REG_EXPAND_SZ)
        dataSize += 2;
    else if (dataType == REG_MULTI_SZ)
        dataSize += 4;

    // get the value
    QByteArray data(dataSize, 0);
    res = RegQueryValueEx(handle, reinterpret_cast<const wchar_t *>(rSubkeyName.utf16()), 0, 0,
                           reinterpret_cast<unsigned char*>(data.data()), &dataSize);
    if (res != ERROR_SUCCESS) {
        RegCloseKey(handle);
        return false;
    }

    switch (dataType) {
        case REG_EXPAND_SZ:
        case REG_SZ: {
            QString s;
            if (dataSize) {
                s = QString::fromWCharArray(((const wchar_t *)data.constData()));
            }
            if (value != 0)
                *value = stringToVariant(s);
            break;
        }

        case REG_MULTI_SZ: {
            QStringList l;
            if (dataSize) {
                int i = 0;
                for (;;) {
                    QString s = QString::fromWCharArray((const wchar_t *)data.constData() + i);
                    i += s.length() + 1;

                    if (s.isEmpty())
                        break;
                    l.append(s);
                }
            }
            if (value != 0)
                *value = stringListToVariantList(l);
            break;
        }

        case REG_NONE:
        case REG_BINARY: {
            QString s;
            if (dataSize) {
                s = QString::fromWCharArray((const wchar_t *)data.constData(), data.size() / 2);
            }
            if (value != 0)
                *value = stringToVariant(s);
            break;
        }

        case REG_DWORD_BIG_ENDIAN:
        case REG_DWORD: {
            Q_ASSERT(data.size() == sizeof(int));
            int i;
            memcpy((char*)&i, data.constData(), sizeof(int));
            if (value != 0)
                *value = i;
            break;
        }

        case REG_QWORD: {
            Q_ASSERT(data.size() == sizeof(qint64));
            qint64 i;
            memcpy((char*)&i, data.constData(), sizeof(qint64));
            if (value != 0)
                *value = i;
            break;
        }

        default:
            qWarning("QSettings: Unknown data %d type in Windows registry", static_cast<int>(dataType));
            if (value != 0)
                *value = QVariant();
            break;
    }

    RegCloseKey(handle);
    return true;
}

HKEY QWinSettingsPrivate::writeHandle() const
{
    if (regList.isEmpty())
        return 0;
    const RegistryKey &key = regList.at(0);
    if (key.handle() == 0 || key.readOnly())
        return 0;
    return key.handle();
}

QWinSettingsPrivate::~QWinSettingsPrivate()
{
    if (deleteWriteHandleOnExit && writeHandle() != 0) {
        QString emptyKey;
        DWORD res = RegDeleteKey(writeHandle(), reinterpret_cast<const wchar_t *>(emptyKey.utf16()));
        if (res != ERROR_SUCCESS) {
            qWarning("QSettings: Failed to delete key \"%s\": %s",
                    regList.at(0).key().toLatin1().data(), errorCodeToString(res).toLatin1().data());
        }
    }

    for (int i = 0; i < regList.size(); ++i)
        regList[i].close();
}

void QWinSettingsPrivate::remove(const QString &uKey)
{
    if (writeHandle() == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    QString rKey = escapedKey(uKey);

    // try to delete value bar in key foo
    LONG res;
    HKEY handle = openKey(writeHandle(), registryPermissions, keyPath(rKey), access);
    if (handle != 0) {
        res = RegDeleteValue(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()));
        RegCloseKey(handle);
    }

    // try to delete key foo/bar and all subkeys
    handle = openKey(writeHandle(), registryPermissions, rKey, access);
    if (handle != 0) {
        deleteChildGroups(handle, access);

        if (rKey.isEmpty()) {
            QStringList childKeys = childKeysOrGroups(handle, QSettingsPrivate::ChildKeys);

            for (int i = 0; i < childKeys.size(); ++i) {
                QString group = childKeys.at(i);

                LONG res = RegDeleteValue(handle, reinterpret_cast<const wchar_t *>(group.utf16()));
                if (res != ERROR_SUCCESS) {
                    qWarning("QSettings: RegDeleteValue failed on subkey \"%s\": %s",
                              group.toLatin1().data(), errorCodeToString(res).toLatin1().data());
                }
            }
        } else {
            res = RegDeleteKey(writeHandle(), reinterpret_cast<const wchar_t *>(rKey.utf16()));

            if (res != ERROR_SUCCESS) {
                qWarning("QSettings: RegDeleteKey failed on key \"%s\": %s",
                            rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
            }
        }
        RegCloseKey(handle);
    }
}

static bool stringContainsNullChar(const QString &s)
{
    for (int i = 0; i < s.length(); ++i) {
        if (s.at(i).unicode() == 0)
            return true;
    }
    return false;
}

void QWinSettingsPrivate::set(const QString &uKey, const QVariant &value)
{
    if (writeHandle() == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    QString rKey = escapedKey(uKey);

    HKEY handle = createOrOpenKey(writeHandle(), registryPermissions, keyPath(rKey), access);
    if (handle == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    DWORD type;
    QByteArray regValueBuff;

    // Determine the type
    switch (value.type()) {
        case QVariant::List:
        case QVariant::StringList: {
            // If none of the elements contains '\0', we can use REG_MULTI_SZ, the
            // native registry string list type. Otherwise we use REG_BINARY.
            type = REG_MULTI_SZ;
            QStringList l = variantListToStringList(value.toList());
            QStringList::const_iterator it = l.constBegin();
            for (; it != l.constEnd(); ++it) {
                if ((*it).length() == 0 || stringContainsNullChar(*it)) {
                    type = REG_BINARY;
                    break;
                }
            }

            if (type == REG_BINARY) {
                QString s = variantToString(value);
                regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
            } else {
                QStringList::const_iterator it = l.constBegin();
                for (; it != l.constEnd(); ++it) {
                    const QString &s = *it;
                    regValueBuff += QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
                }
                regValueBuff.append((char)0);
                regValueBuff.append((char)0);
            }
            break;
        }

        case QVariant::Int:
        case QVariant::UInt: {
            type = REG_DWORD;
            qint32 i = value.toInt();
            regValueBuff = QByteArray((const char*)&i, sizeof(qint32));
            break;
        }

        case QVariant::LongLong:
        case QVariant::ULongLong: {
            type = REG_QWORD;
            qint64 i = value.toLongLong();
            regValueBuff = QByteArray((const char*)&i, sizeof(qint64));
            break;
        }

        case QVariant::ByteArray:
            // fallthrough intended

        default: {
            // If the string does not contain '\0', we can use REG_SZ, the native registry
            // string type. Otherwise we use REG_BINARY.
            QString s = variantToString(value);
            type = stringContainsNullChar(s) ? REG_BINARY : REG_SZ;
            if (type == REG_BINARY) {
                regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
            } else {
                regValueBuff = QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
            }
            break;
        }
    }

    // set the value
    LONG res = RegSetValueEx(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()), 0, type,
                             reinterpret_cast<const unsigned char*>(regValueBuff.constData()),
                             regValueBuff.size());

    if (res == ERROR_SUCCESS) {
        deleteWriteHandleOnExit = false;
    } else {
        qWarning("QSettings: failed to set subkey \"%s\": %s",
                rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
        setStatus(QSettings::AccessError);
    }

    RegCloseKey(handle);
}

bool QWinSettingsPrivate::get(const QString &uKey, QVariant *value) const
{
    QString rKey = escapedKey(uKey);

    for (int i = 0; i < regList.size(); ++i) {
        HKEY handle = regList.at(i).handle();
        if (handle != 0 && readKey(handle, rKey, value))
            return true;

        if (!fallbacks)
            return false;
    }

    return false;
}

QStringList QWinSettingsPrivate::children(const QString &uKey, ChildSpec spec) const
{
    NameSet result;
    QString rKey = escapedKey(uKey);

    for (int i = 0; i < regList.size(); ++i) {
        HKEY parent_handle = regList.at(i).handle();
        if (parent_handle == 0)
            continue;
        HKEY handle = openKey(parent_handle, KEY_READ, rKey, access);
        if (handle == 0)
            continue;

        if (spec == AllKeys) {
            NameSet keys;
            allKeys(handle, QLatin1String(""), &keys, access);
            mergeKeySets(&result, keys);
        } else { // ChildGroups or ChildKeys
            QStringList names = childKeysOrGroups(handle, spec);
            mergeKeySets(&result, names);
        }

        RegCloseKey(handle);

        if (!fallbacks)
            return result.keys();
    }

    return result.keys();
}

void QWinSettingsPrivate::clear()
{
    remove(QString());
    deleteWriteHandleOnExit = true;
}

void QWinSettingsPrivate::sync()
{
    RegFlushKey(writeHandle());
}

void QWinSettingsPrivate::flush()
{
    // Windows does this for us.
}

QString QWinSettingsPrivate::fileName() const
{
    if (regList.isEmpty())
        return QString();

    const RegistryKey &key = regList.at(0);
    QString result;
    if (key.parentHandle() == HKEY_CURRENT_USER)
        result = QLatin1String("\\HKEY_CURRENT_USER\\");
    else
        result = QLatin1String("\\HKEY_LOCAL_MACHINE\\");

    return result + regList.at(0).key();
}

bool QWinSettingsPrivate::isWritable() const
{
    return writeHandle() != 0;
}

QSettingsPrivate *QSettingsPrivate::create(QSettings::Format format, QSettings::Scope scope,
                                           const QString &organization, const QString &application)
{
    if (format == QSettings::NativeFormat)
        return new QWinSettingsPrivate(scope, organization, application);
    else if (format == QSettings::Registry32Format)
        return new QWinSettingsPrivate(scope, organization, application, KEY_WOW64_32KEY);
    else if (format == QSettings::Registry64Format)
        return new QWinSettingsPrivate(scope, organization, application, KEY_WOW64_64KEY);
    else
        return new QConfFileSettingsPrivate(format, scope, organization, application);
}

QSettingsPrivate *QSettingsPrivate::create(const QString &fileName, QSettings::Format format)
{
    if (format == QSettings::NativeFormat)
        return new QWinSettingsPrivate(fileName);
    else if (format == QSettings::Registry32Format)
        return new QWinSettingsPrivate(fileName, KEY_WOW64_32KEY);
    else if (format == QSettings::Registry64Format)
        return new QWinSettingsPrivate(fileName, KEY_WOW64_64KEY);
    else
        return new QConfFileSettingsPrivate(fileName, format);
}

QT_END_NAMESPACE
#endif // QT_NO_SETTINGS