diff --git a/.gitignore b/.gitignore
index 5a23b64d69db1779f9aaffde3e388bc1e748aaef..1ecd8c1009f808a0765481c86d66e2f4b393d14f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,6 +47,10 @@ pcviewer.cfg
 *_resource.rc
 .#*
 *.*#
+*_wrapper.sh
+*_wrapper.bat
+wrapper.sh
+wrapper.bat
 core
 .qmake.cache
 .qmake.vars
diff --git a/doc/global/externalsites/external-resources.qdoc b/doc/global/externalsites/external-resources.qdoc
index d2cf88c1744fb28c425a0b20d77f5587b2398922..3e82dfe814c3f4dfa8a0dea9a44439f68faf5634 100644
--- a/doc/global/externalsites/external-resources.qdoc
+++ b/doc/global/externalsites/external-resources.qdoc
@@ -489,6 +489,6 @@
 */
 
 /*!
-    \externalpage http://qt.digia.com/Try-Buy/Qt-Account-Sign-up/
+    \externalpage https://login.qt.io/
     \title Qt Account Sign-up
 */
diff --git a/mkspecs/common/winrt_winphone/qmake.conf b/mkspecs/common/winrt_winphone/qmake.conf
index bf237882ff432223ddc874f18fe869f4618926e1..a9450b0c32db755c3bfc207585120435fd981763 100644
--- a/mkspecs/common/winrt_winphone/qmake.conf
+++ b/mkspecs/common/winrt_winphone/qmake.conf
@@ -78,9 +78,9 @@ QMAKE_PREFIX_STATICLIB  =
 QMAKE_EXTENSION_STATICLIB = lib
 
 QMAKE_LIBS             += runtimeobject.lib
-QMAKE_LIBS_CORE         =
+QMAKE_LIBS_CORE        += ws2_32.lib
 QMAKE_LIBS_GUI          =
-QMAKE_LIBS_NETWORK      =
+QMAKE_LIBS_NETWORK     += ws2_32.lib
 QMAKE_LIBS_OPENGL_ES2   = $${LIBEGL_NAME}.lib $${LIBGLESV2_NAME}.lib
 QMAKE_LIBS_OPENGL_ES2_DEBUG = $${LIBEGL_NAME}d.lib $${LIBGLESV2_NAME}d.lib
 
diff --git a/mkspecs/common/winrt_winphone/qplatformdefs.h b/mkspecs/common/winrt_winphone/qplatformdefs.h
index 6abac1e94df1a71e1bf182eb85b4efee7bf0cd17..14f6c58253694bc0a344da717f4adeb046530167 100644
--- a/mkspecs/common/winrt_winphone/qplatformdefs.h
+++ b/mkspecs/common/winrt_winphone/qplatformdefs.h
@@ -130,14 +130,4 @@
 
 typedef int mode_t;
 
-#ifndef INADDR_ANY
-#  define INADDR_ANY        (u_long)0x00000000
-#endif
-#ifndef INADDR_LOOPBACK
-#  define INADDR_LOOPBACK   0x7f000001
-#endif
-#ifndef INADDR_BROADCAST
-#  define INADDR_BROADCAST  (u_long)0xffffffff
-#endif
-
 #endif // QPLATFORMDEFS_H
diff --git a/mkspecs/features/android/android.prf b/mkspecs/features/android/android.prf
index f428f7db876635853fa444eef0cd3417d66fea73..7d77598e76cbfe8a21da2e3e5ddccf207ce7c968 100644
--- a/mkspecs/features/android/android.prf
+++ b/mkspecs/features/android/android.prf
@@ -3,7 +3,7 @@ contains(TEMPLATE, ".*app") {
         !contains(TARGET, ".so"): TARGET = lib$${TARGET}.so
         QMAKE_LFLAGS += -Wl,-soname,$$shell_quote($$TARGET)
 
-        android_install: {
+        android_install {
             target.path=/libs/$$ANDROID_TARGET_ARCH/
             INSTALLS *= target
         }
diff --git a/mkspecs/features/data/cmake/Qt5ConfigVersion.cmake.in b/mkspecs/features/data/cmake/Qt5ConfigVersion.cmake.in
index e804754912e5b85f8b00ad7dfe7e48351bfce524..7c42430e97b3247fc8e64176c2beb42f74864368 100644
--- a/mkspecs/features/data/cmake/Qt5ConfigVersion.cmake.in
+++ b/mkspecs/features/data/cmake/Qt5ConfigVersion.cmake.in
@@ -1,11 +1,11 @@
 
 set(PACKAGE_VERSION $$CMAKE_PACKAGE_VERSION)
 
-if(\"\${PACKAGE_VERSION}\" VERSION_LESS \"\${PACKAGE_FIND_VERSION}\")
+if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
     set(PACKAGE_VERSION_COMPATIBLE FALSE)
 else()
     set(PACKAGE_VERSION_COMPATIBLE TRUE)
-    if(\"\${PACKAGE_FIND_VERSION}\" STREQUAL \"\${PACKAGE_VERSION}\")
+    if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
         set(PACKAGE_VERSION_EXACT TRUE)
     endif()
 endif()
diff --git a/mkspecs/features/data/unix/findclasslist.pl b/mkspecs/features/data/unix/findclasslist.pl
index 9113b4921c6a451c8163809d64a9a09a8361f55f..adec22d58dd43956d2d617373a4e39626d372725 100644
--- a/mkspecs/features/data/unix/findclasslist.pl
+++ b/mkspecs/features/data/unix/findclasslist.pl
@@ -1,7 +1,7 @@
 #!/usr/bin/env perl
 #############################################################################
 ##
-## Copyright (C) 2015 Intel Corporation
+## Copyright (C) 2016 Intel Corporation
 ## Contact: http://www.qt.io/licensing/
 ##
 ## This file is part of the build configuration tools of the Qt Toolkit.
@@ -33,27 +33,26 @@
 #############################################################################
 
 use strict;
-my $syntax = "findclasslist.pl [private header list]\n" .
-             "Replaces \@CLASSLIST\@ with the classes found in the header files\n";
+my $syntax = "findclasslist.pl\n" .
+             "Replaces each \@FILE:filename\@ in stdin with the classes found in that file\n";
+
 $\ = $/;
 while (<STDIN>) {
     chomp;
-    unless (/\@CLASSLIST\@/) {
+    unless (/\@FILE:(.*)\@/) {
         print;
         next;
     }
 
-    # Replace @CLASSLIST@ with the class list
-    for my $header (@ARGV) {
-        open HDR, "<$header" or die("Could not open header $header: $!");
-        my $comment = "    /* $header */";
-        while (my $line = <HDR>) {
-            # Match a struct or class declaration, but not a forward declaration
-            $line =~ /^(?:struct|class) (?:Q_.*_EXPORT)? (\w+)(?!;)/ or next;
-            print $comment if $comment;
-            printf "    *%d%s*;\n", length $1, $1;
-            $comment = 0;
-        }
-        close HDR;
+    # Replace this line with the class list
+    open HDR, "<$1" or die("Could not open header $1: $!");
+    my $comment = "    /* $1 */";
+    while (my $line = <HDR>) {
+        # Match a struct or class declaration, but not a forward declaration
+        $line =~ /^(?:struct|class) (?:Q_.*_EXPORT)? (\w+)(?!;)/ or next;
+        print $comment if $comment;
+        printf "    *%d%s*;\n", length $1, $1;
+        $comment = 0;
     }
+    close HDR;
 }
diff --git a/mkspecs/features/qt.prf b/mkspecs/features/qt.prf
index c3448718b934e49c0d9b7bf814268f743d7edf86..72632a14ee25cd974dbb4dd428c04c8a35e47f65 100644
--- a/mkspecs/features/qt.prf
+++ b/mkspecs/features/qt.prf
@@ -208,7 +208,7 @@ contains(qt_module_deps, qml): \
 
     !isEmpty(IMPORTS._KEYS_) {
         # add import plugins to LIBS line
-        for (key, IMPORTS._KEYS_): {
+        for (key, IMPORTS._KEYS_) {
             PATH = $$eval(IMPORTS.$${key}.path)
             PLUGIN = $$eval(IMPORTS.$${key}.plugin)
             !isEmpty(PATH):!isEmpty(PLUGIN): LIBS *= -L$$PATH -l$${PLUGIN}$$qtPlatformTargetSuffix()
@@ -347,7 +347,7 @@ for(QT_CURRENT_VERIFY, $$list($$QT_PLUGIN_VERIFY)) {
         QT_LINKAGE = -l$${QTPLUG}$$qtPlatformTargetSuffix()
 
         # Only link against plugin in static builds
-        isEqual(QT_CURRENT_VERIFY, QTPLUGIN): {
+        isEqual(QT_CURRENT_VERIFY, QTPLUGIN) {
             !isEmpty(QT_PLUGINPATH) {
                 plugpath = $$eval(QT_PLUGIN.$${QTPLUG}.PATH)
                 isEmpty(plugpath): \
diff --git a/mkspecs/features/qt_build_config.prf b/mkspecs/features/qt_build_config.prf
index eaf23cf63a85b08982a338384cef35c7b2e4321c..518fd93f0457c6060721c38ad8b6a0286407e562 100644
--- a/mkspecs/features/qt_build_config.prf
+++ b/mkspecs/features/qt_build_config.prf
@@ -52,6 +52,12 @@ QMAKE_DIR_REPLACE_SANE = PRECOMPILED_DIR OBJECTS_DIR MOC_DIR RCC_DIR UI_DIR
     unset(modpath)
 }
 
+# Don't actually try to install anything in non-prefix builds.
+# This is much easier and safer than making every single INSTALLS
+# assignment conditional.
+!prefix_build: \
+    CONFIG += qt_clear_installs
+
 cross_compile: \
     CONFIG += force_bootstrap
 
diff --git a/mkspecs/features/qt_clear_installs.prf b/mkspecs/features/qt_clear_installs.prf
new file mode 100644
index 0000000000000000000000000000000000000000..66d12f9d6d1fd4f2f95465f434d5780510949f79
--- /dev/null
+++ b/mkspecs/features/qt_clear_installs.prf
@@ -0,0 +1,12 @@
+#
+#  W A R N I N G
+#  -------------
+#
+# This file is not part of the Qt API.  It exists purely as an
+# implementation detail.  It may change from version to version
+# without notice, or even be removed.
+#
+# We mean it.
+#
+
+INSTALLS =
diff --git a/mkspecs/features/qt_docs.prf b/mkspecs/features/qt_docs.prf
index 15bd12072a42aaed1813217e07369744c6b25602..183d0c9502d94214f0dedc65bbd7ae9500a168a1 100644
--- a/mkspecs/features/qt_docs.prf
+++ b/mkspecs/features/qt_docs.prf
@@ -11,13 +11,6 @@
 
 !exists($$QMAKE_DOCS): error("Cannot find documentation specification file $$QMAKE_DOCS")
 
-load(qt_build_paths)
-QMAKE_DOCS_BASE_OUTDIR = $$MODULE_BASE_OUTDIR/doc
-
-QMAKE_DOCS_TARGET = $$replace(QMAKE_DOCS, ^(.*/)?(.*)\\.qdocconf$, \\2)
-isEmpty(QMAKE_DOCS_TARGETDIR): QMAKE_DOCS_TARGETDIR = $$QMAKE_DOCS_TARGET
-QMAKE_DOCS_OUTPUTDIR = $$QMAKE_DOCS_BASE_OUTDIR/$$QMAKE_DOCS_TARGETDIR
-
 qtver.name = QT_VERSION
 qtver.value = $$VERSION
 isEmpty(qtver.value): qtver.value = $$MODULE_VERSION
@@ -31,9 +24,24 @@ qtdocs.value = $$[QT_INSTALL_DOCS/src]
 QT_TOOL_ENV = qtver qtmver qtvertag qtdocs
 qtPrepareTool(QDOC, qdoc)
 QT_TOOL_ENV =
-QDOC += -outputdir $$QMAKE_DOCS_OUTPUTDIR
+
+!build_online_docs: qtPrepareTool(QHELPGENERATOR, qhelpgenerator)
+
+# qtPrepareTool() must be called outside a build pass, as it protects
+# against concurrent wrapper creation by omitting it during build passes.
+# However, creating the actual targets is reserved to the build passes.
+debug_and_release:!build_pass: return()
+
+load(qt_build_paths)
+QMAKE_DOCS_BASE_OUTDIR = $$MODULE_BASE_OUTDIR/doc
+
+QMAKE_DOCS_TARGET = $$replace(QMAKE_DOCS, ^(.*/)?(.*)\\.qdocconf$, \\2)
+isEmpty(QMAKE_DOCS_TARGETDIR): QMAKE_DOCS_TARGETDIR = $$QMAKE_DOCS_TARGET
+QMAKE_DOCS_OUTPUTDIR = $$QMAKE_DOCS_BASE_OUTDIR/$$QMAKE_DOCS_TARGETDIR
+
+QDOC += -outputdir $$shell_quote($$QMAKE_DOCS_OUTPUTDIR)
 !build_online_docs: \
-    QDOC += -installdir $$[QT_INSTALL_DOCS]
+    QDOC += -installdir $$shell_quote($$[QT_INSTALL_DOCS])
 PREP_DOC_INDEXES =
 DOC_INDEXES =
 !isEmpty(QTREPOS) {
@@ -46,14 +54,14 @@ DOC_INDEXES =
             mps += $$dirname(QT.$${d}.libs)
         mps = $$unique(mps)
         for (mp, mps): \
-            PREP_DOC_INDEXES += -indexdir $$mp/doc
+            PREP_DOC_INDEXES += -indexdir $$shell_quote($$mp/doc)
     }
     for(qrep, QTREPOS): \
-        DOC_INDEXES += -indexdir $$qrep/doc
+        DOC_INDEXES += -indexdir $$shell_quote($$qrep/doc)
 } else {
     prepare_docs: \
-        PREP_DOC_INDEXES += -indexdir $$[QT_INSTALL_DOCS/get]
-    DOC_INDEXES += -indexdir $$[QT_INSTALL_DOCS/get]
+        PREP_DOC_INDEXES += -indexdir $$shell_quote($$[QT_INSTALL_DOCS/get])
+    DOC_INDEXES += -indexdir $$shell_quote($$[QT_INSTALL_DOCS/get])
 }
 doc_command = $$QDOC $$QMAKE_DOCS
 prepare_docs {
@@ -64,8 +72,7 @@ prepare_docs {
 }
 
 !build_online_docs {
-    qtPrepareTool(QHELPGENERATOR, qhelpgenerator)
-    qch_docs.commands = $$QHELPGENERATOR $$QMAKE_DOCS_OUTPUTDIR/$${QMAKE_DOCS_TARGET}.qhp -o $$QMAKE_DOCS_BASE_OUTDIR/$${QMAKE_DOCS_TARGET}.qch
+    qch_docs.commands = $$QHELPGENERATOR $$shell_quote($$QMAKE_DOCS_OUTPUTDIR/$${QMAKE_DOCS_TARGET}.qhp) -o $$shell_quote($$QMAKE_DOCS_BASE_OUTDIR/$${QMAKE_DOCS_TARGET}.qch)
 
     inst_html_docs.files = $$QMAKE_DOCS_OUTPUTDIR
     inst_html_docs.path = $$[QT_INSTALL_DOCS]
diff --git a/mkspecs/features/qt_docs_targets.prf b/mkspecs/features/qt_docs_targets.prf
index 89f080cc5e344ac6bca11748a829f526e4e87a6d..1f9e2b0b47800a4c8185bb00fb8090b306105c2b 100644
--- a/mkspecs/features/qt_docs_targets.prf
+++ b/mkspecs/features/qt_docs_targets.prf
@@ -29,17 +29,17 @@ QMAKE_EXTRA_TARGETS += docs
 contains(TEMPLATE, subdirs) {
     for(inst, DOC_TARGETS): \
         prepareRecursiveTarget($$inst)
-} else:debug_and_release:!build_pass {
-    sub = $$first(BUILDS)
-    for(inst, DOC_TARGETS) {
-        $${inst}.CONFIG = recursive
-        $${inst}.recurse = $$sub
-    }
 } else {
-    # apps and libs only generate docs if QMAKE_DOCS is set
-    !isEmpty(QMAKE_DOCS) {
-        # backwards compat hack
-        load(qt_docs)
+    debug_and_release:!build_pass {
+        sub = $$first(BUILDS)
+        for(inst, DOC_TARGETS) {
+            $${inst}.CONFIG = recursive
+            $${inst}.recurse = $$sub
+        }
     }
+    # Apps and libs request docs creation by setting QMAKE_DOCS.
+    # This is a backwards compat hack - technically, the modules which need it
+    # are supposed to load(qt_docs) themselves.
+    !isEmpty(QMAKE_DOCS): load(qt_docs)
 }
 QMAKE_EXTRA_TARGETS += $$DOC_TARGETS
diff --git a/mkspecs/features/qt_functions.prf b/mkspecs/features/qt_functions.prf
index 00f4bdf93e8171df3279656d08efbd6758271b8c..e239db24548fc3485cac8709e6feb743ff21d2c5 100644
--- a/mkspecs/features/qt_functions.prf
+++ b/mkspecs/features/qt_functions.prf
@@ -70,6 +70,7 @@ defineTest(qtPrepareTool) {
         }
     }
     QT_TOOL_ENV += $$eval(QT_TOOL.$${2}.envvars)
+    QT_TOOL_NAME = $$2
     !isEmpty(3)|!isEmpty(4) {
         $$1$$3 =
         for (arg, cmd): \
@@ -90,29 +91,73 @@ defineTest(qtAddToolEnv) {
         ds = $$QMAKE_DIR_SEP
     else: \
         ds = $$DIR_SEPARATOR
+    batch_sets =
     for(env, 2) {
         value = $$eval($${env}.value)
         !isEmpty(value) {
             name = $$eval($${env}.name)
+            config = $$eval($${env}.CONFIG)
             equals(ds, /) {
-                contains($${env}.CONFIG, prepend): infix = \${$$name:+:\$$$name}
+                contains(config, prepend): infix = \${$$name:+:\$$$name}
+                else: contains(config, always_prepend): infix = :\$$$name
                 else: infix =
-                val = "$$name=$$shell_quote($$join(value, :))$$infix"
+                # Under msys, this path is taken only in the non-system()
+                # case, so using shell_quote() always works.
+                batch_sets += \
+                    "$$name=$$shell_quote($$join(value, :))$$infix" \
+                    "export $$name"
             } else {
-                # Escape closing parens when expanding the variable, otherwise cmd confuses itself.
-                contains($${env}.CONFIG, prepend): infix = ;%$$name:)=^)%
-                else: infix =
+                value ~= s,\\^,^^^^,g
+                value ~= s,!,^^!,g
                 value ~= s,\\),^),g
-                val = "(set $$name=$$join(value, ;)$$infix) &"
-            }
-            isEmpty(3): !contains(TEMPLATE, vc.*) {
-                contains(MAKEFILE_GENERATOR, MS.*): val ~= s,%,%%,g
-                val ~= s,\\\$,\$\$,g
+                contains(config, prepend) {
+                    batch_sets += \
+                        "if defined $$name (" \
+                        "    set $$name=$$join(value, ;);!$$name!" \
+                        ") else (" \
+                        "    set $$name=$$join(value, ;)" \
+                        ")"
+                } else: contains(config, always_prepend) {
+                    batch_sets += "(set $$name=$$join(value, ;);!$$name!)"
+                } else {
+                    batch_sets += "(set $$name=$$join(value, ;))"
+                }
             }
-            $$1 = "$$val $$eval($$1)"
         }
     }
+    !isEmpty(batch_sets) {
+        batch_name = wrapper
+        !isEmpty(QT_TOOL_NAME): batch_name = $${QT_TOOL_NAME}_wrapper
+        cmd = $$eval($$1)
+        !isEmpty(cmd): cmd = "$$cmd "
+        equals(ds, /) {
+            batch_name = $${batch_name}.sh
+            batch_cont = \
+                "$$LITERAL_HASH!/bin/sh" \
+                $$batch_sets \
+                "exec $$cmd\"$@\""
+            # It would be nicer to use the '.' command (without 'exec' above),
+            # but that doesn't set the positional arguments under (d)ash.
+            $$1 =
+        } else {
+            batch_name = $${batch_name}.bat
+            batch_cont = \
+                "@echo off" \
+                "SetLocal EnableDelayedExpansion" \
+                $$batch_sets \
+                "$$cmd%*" \
+                "EndLocal"
+            $$1 = call
+        }
+        !build_pass:!write_file($$OUT_PWD/$$batch_name, batch_cont, exe): error("Aborting.")
+        isEmpty(3): \
+            $$1 += $$shell_quote($$shell_path($$OUT_PWD/$$batch_name))
+        else: \
+            $$1 += $$system_quote($$system_path($$OUT_PWD/$$batch_name))
+        QMAKE_DISTCLEAN += $$OUT_PWD/$$batch_name
+    }
     export($$1)
+    export(QMAKE_DISTCLEAN)
 }
 
 # target variable, dependency var name, [non-empty: prepare for system(), not make]
@@ -120,9 +165,9 @@ defineTest(qtAddTargetEnv) {
     deps = $$replace($$2, -private$, _private)
     deps = $$resolve_depends(deps, "QT.", ".depends" ".run_depends")
     !isEmpty(deps) {
-        libs = libs
+        deppath.CONFIG = prepend
         equals(QMAKE_HOST.os, Windows) {
-            libs = bins
+            deppath.CONFIG = always_prepend
             deppath.name = PATH
         } else:contains(QMAKE_HOST.os, Linux|FreeBSD|OpenBSD|NetBSD|DragonFly|SunOS|HP-UX|QNX|GNU) {
             deppath.name = LD_LIBRARY_PATH
@@ -141,13 +186,12 @@ defineTest(qtAddTargetEnv) {
         ptypes =
         for(dep, deps) {
             isEmpty(3): \
-                deppath += $$shell_path($$eval(QT.$${dep}.$$libs))
+                deppath += $$shell_path($$eval(QT.$${dep}.libs))
             else: \
-                deppath += $$system_path($$eval(QT.$${dep}.$$libs))
+                deppath += $$system_path($$eval(QT.$${dep}.libs))
             ptypes += $$eval(QT.$${dep}.plugin_types)
         }
         deppath.value = $$unique(deppath)
-        deppath.CONFIG = prepend
 
         pluginpath.value =
         ppaths = $$[QT_INSTALL_PLUGINS/get]
@@ -162,6 +206,7 @@ defineTest(qtAddTargetEnv) {
                 pluginpath.value += $$system_path($$qplug)
         }
         pluginpath.name = QT_PLUGIN_PATH
+        pluginpath.CONFIG = prepend
 
         QT_TOOL_ENV += deppath pluginpath
     }
diff --git a/mkspecs/features/qt_module.prf b/mkspecs/features/qt_module.prf
index 9a4ed20af8f24f5851ed30aec151cc17558eddcb..fdce486c0021631d9693af8f9aa6b6b1b8a2ceb7 100644
--- a/mkspecs/features/qt_module.prf
+++ b/mkspecs/features/qt_module.prf
@@ -80,10 +80,10 @@ CONFIG          += qmake_cache target_qt
 
 QMAKE_DOCS_TARGETDIR = qt$${MODULE}
 
-load(qt_module_pris)
 load(qt_common)
-
 !no_module_headers: load(qt_module_headers)
+load(qt_module_pris)
+
 INCLUDEPATH *= $$eval(QT.$${MODULE}.includes) $$eval(QT.$${MODULE}_private.includes)
 
 # If Qt was configured with -debug-and-release then build the module the same way
@@ -132,7 +132,6 @@ lib_bundle {
 }
 
 mac {
-   CONFIG += explicitlib
    macx-g++ {
        QMAKE_CFLAGS += -fconstant-cfstrings
        QMAKE_CXXFLAGS += -fconstant-cfstrings
@@ -200,7 +199,10 @@ android: CONFIG += qt_android_deps no_linker_version_script
         verscript_content = "Qt_$${QT_MAJOR_VERSION}_PRIVATE_API { *; };"
     } else {
         verscript_content = "Qt_$${QT_MAJOR_VERSION}_PRIVATE_API {" \
-                            "    qt_private_api_tag*;" "@CLASSLIST@" "};"
+                            "    qt_private_api_tag*;"
+        for(header, SYNCQT.PRIVATE_HEADER_FILES): \
+            verscript_content += "    @FILE:$${_PRO_FILE_PWD_}/$$header@"
+        verscript_content += "};"
 
         current = Qt_$$QT_MAJOR_VERSION
         verscript_content += "$$current { *; };"
@@ -214,12 +216,12 @@ android: CONFIG += qt_android_deps no_linker_version_script
             else:                          verscript_content += "$$current {} $$previous;"
         }
 
-        # Add a post-processing step to replace the @CLASSLIST@
-        verscriptprocess.commands = perl $${PWD}/data/unix/findclasslist.pl < $^ > $@
+        # Add a post-processing step to replace the @FILE:filename@
+        verscriptprocess.commands = perl $${PWD}/data/unix/findclasslist.pl < $${verscript}.in > $@
         verscriptprocess.target = $$verscript
-        verscriptprocess.depends = $${verscript}.in
         for(header, SYNCQT.PRIVATE_HEADER_FILES): \
             verscriptprocess.depends += $${_PRO_FILE_PWD_}/$$header
+        verscriptprocess.depends += $${verscript}.in
         QMAKE_EXTRA_TARGETS += verscriptprocess
         PRE_TARGETDEPS += $$verscript
         verscript = $${verscript}.in
@@ -257,19 +259,18 @@ load(qt_targets)
         pclib_replace.replace = $$QMAKE_PKGCONFIG_LIBDIR
     pclib_replace.CONFIG = path
     QMAKE_PKGCONFIG_INSTALL_REPLACE += pclib_replace
-
-    unix {
-        CONFIG += create_libtool explicitlib
-        host_build: \
-            QMAKE_LIBTOOL_LIBDIR = $$[QT_HOST_LIBS]
-        else: \
-            QMAKE_LIBTOOL_LIBDIR = "=$$[QT_INSTALL_LIBS/raw]"
-        ltlib_replace.match = $$lib_replace.match
-        !isEmpty(lib_replace.replace): \
-            ltlib_replace.replace = $$QMAKE_LIBTOOL_LIBDIR
-        ltlib_replace.CONFIG = path
-        QMAKE_LIBTOOL_INSTALL_REPLACE += ltlib_replace
-    }
+}
+!lib_bundle:unix {
+    CONFIG += create_libtool
+    host_build: \
+        QMAKE_LIBTOOL_LIBDIR = $$[QT_HOST_LIBS]
+    else: \
+        QMAKE_LIBTOOL_LIBDIR = "=$$[QT_INSTALL_LIBS/raw]"
+    ltlib_replace.match = $$lib_replace.match
+    !isEmpty(lib_replace.replace): \
+        ltlib_replace.replace = $$QMAKE_LIBTOOL_LIBDIR
+    ltlib_replace.CONFIG = path
+    QMAKE_LIBTOOL_INSTALL_REPLACE += ltlib_replace
 }
 
 contains(QT_PRODUCT, OpenSource.*):DEFINES *= QT_OPENSOURCE
diff --git a/mkspecs/features/qt_module_headers.prf b/mkspecs/features/qt_module_headers.prf
index 892a9a2c4ba922dabc26614970bb17286d65ad58..eb1db084051dc9b64f4c6d3ca2ff6fba001f16f1 100644
--- a/mkspecs/features/qt_module_headers.prf
+++ b/mkspecs/features/qt_module_headers.prf
@@ -18,10 +18,11 @@ load(qt_build_paths)
     } else {
         contains(QT_CONFIG, private_tests): \   # -developer-build
             QMAKE_SYNCQT += -check-includes
-        QMAKE_SYNCQT += -module $$MODULE_INCNAME -version $$VERSION
     }
+    for(mod, MODULE_INCNAME): \
+        QMAKE_SYNCQT += -module $$mod
     QMAKE_SYNCQT += \
-        -outdir $$system_quote($$MODULE_BASE_OUTDIR) $$MODULE_SYNCQT_DIR
+        -version $$VERSION -outdir $$system_quote($$MODULE_BASE_OUTDIR) $$MODULE_SYNCQT_DIR
     !silent: message($$QMAKE_SYNCQT)
     system($$QMAKE_SYNCQT)|error("Failed to run: $$QMAKE_SYNCQT")
 
@@ -33,6 +34,63 @@ load(qt_build_paths)
     }
 }
 
+# Pre-generated headers in the source tree (tar-ball) and
+# - shadow build or
+# - non-shadow non-prefix build of a module which is not qtbase
+#   (because the build-time generated headers all end up in qtbase).
+!git_build: \
+        if(!equals(_PRO_FILE_PWD_, $$OUT_PWD) \
+           |if(!prefix_build:!equals(MODULE_BASE_INDIR, $$[QT_HOST_PREFIX]))): \
+    CONFIG += split_incpath
+
+# To avoid stuffing the code with repetetive conditionals,
+# we parametrize the names of the variables we assign to.
+
+# Internal modules have no private part - they *are* private.
+!internal_module: \
+    prv = _PRIVATE
+
+# When doing a framework build with a prefix, the module needs to point
+# into the frameworks' Headers dirs directly, as no shared include/ dir
+# is installed.
+# However, during the build, it needs to point into the shared include/
+# dir, as the framework doesn't even exist yet. For bootstrapped modules
+# which borrow headers from "proper" modules, this situation persists
+# even beyond the module's own build. The implication of this is that
+# qmake might never use a framework's headers in a non-prefix build,
+# as there is no separate set of .pri files for users outside Qt.
+prefix_build:lib_bundle: \
+    fwd = _FWD
+# When using a split include path during the build, the installed module's
+# include path is also structurally different from that in the build dir.
+prefix_build:split_incpath: \
+    sfwd = _FWD
+
+ibase = \$\$QT_MODULE_INCLUDE_BASE
+MODULE$${fwd}_INCLUDES = $$ibase
+split_incpath {
+    bibase = $$val_escape(MODULE_BASE_OUTDIR)/include
+    MODULE$${sfwd}_INCLUDES += $$bibase
+}
+for(mod, MODULE_INCNAME) {
+    mibase = $$ibase/$$mod
+    MODULE$${fwd}_INCLUDES += $$mibase
+    MODULE$${fwd}$${prv}_INCLUDES += $$mibase/$$VERSION $$mibase/$$VERSION/$$mod
+    split_incpath {
+        mbibase = $$bibase/$$mod
+        MODULE$${sfwd}_INCLUDES += $$mbibase
+        generated_privates: \
+            MODULE$${sfwd}$${prv}_INCLUDES += $$mbibase/$$VERSION $$mbibase/$$VERSION/$$mod
+    }
+    prefix_build:lib_bundle {
+        mfbase = \$\$QT_MODULE_LIB_BASE/$${mod}.framework/Headers
+        MODULE_INCLUDES += $$mfbase
+        MODULE$${prv}_INCLUDES += $$mfbase/$$VERSION $$mfbase/$$VERSION/$$mod
+    }
+}
+MODULE_INCLUDES += $$MODULE_AUX_INCLUDES
+MODULE_PRIVATE_INCLUDES += $$MODULE_PRIVATE_AUX_INCLUDES
+
 minimal_syncqt: return()
 
 #load up the headers info
diff --git a/mkspecs/features/qt_module_pris.prf b/mkspecs/features/qt_module_pris.prf
index 3f21a0f7d536cdb69a749861863fa0fcade999fa..fdcb9df270506a999c610443dde16a236924021a 100644
--- a/mkspecs/features/qt_module_pris.prf
+++ b/mkspecs/features/qt_module_pris.prf
@@ -10,14 +10,7 @@
 #
 
 load(qt_build_paths)
-# Pre-generated headers in the source tree and
-# - shadow build or
-# - non-shadow non-prefix build of a module which is not qtbase (because the build-time
-#   generated headers all end up in qtbase).
-!git_build:if(!equals(_PRO_FILE_PWD_, $$OUT_PWD) \
-              |if(!prefix_build:!equals(MODULE_BASE_INDIR, $$[QT_HOST_PREFIX]))): \
-    CONFIG += split_incpath
-force_independent|split_incpath: \
+force_independent|!isEmpty(MODULE_FWD_INCLUDES): \
     CONFIG += need_fwd_pri
 mod_work_pfx = $$MODULE_QMAKE_OUTDIR/mkspecs/modules
 need_fwd_pri: \
@@ -77,27 +70,6 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
         module_master = "QT.$${MODULE_ID}.master_header = $$MODULE_MASTER_HEADER"
     else: \
         module_master =
-    !no_module_headers:!minimal_syncqt {
-        MODULE_INCLUDES = \$\$QT_MODULE_INCLUDE_BASE \$\$QT_MODULE_INCLUDE_BASE/$$MODULE_INCNAME
-        MODULE_PRIVATE_INCLUDES = \$\$QT_MODULE_INCLUDE_BASE/$$MODULE_INCNAME/$$VERSION \
-                                  \$\$QT_MODULE_INCLUDE_BASE/$$MODULE_INCNAME/$$VERSION/$$MODULE_INCNAME
-    }
-    split_incpath {
-        MODULE_SHADOW_INCLUDES = $$replace(MODULE_INCLUDES, ^\\\$\\\$QT_MODULE_INCLUDE_BASE, \
-                                                            $$MODULE_BASE_OUTDIR/include)
-        generated_privates: \
-            MODULE_SHADOW_PRIVATE_INCLUDES = $$replace(MODULE_PRIVATE_INCLUDES, ^\\\$\\\$QT_MODULE_INCLUDE_BASE, \
-                                                                                $$MODULE_BASE_OUTDIR/include)
-    }
-    MODULE_INCLUDES += $$MODULE_AUX_INCLUDES
-    MODULE_PRIVATE_INCLUDES += $$MODULE_PRIVATE_AUX_INCLUDES
-    internal_module: \
-        MODULE_INCLUDES += $$MODULE_PRIVATE_INCLUDES
-    split_incpath {
-        MODULE_FWD_PRI_CONT_SUFFIX += "QT.$${MODULE_ID}.includes += $$val_escape(MODULE_SHADOW_INCLUDES)"
-        generated_privates: \
-            MODULE_FWD_PRI_CONT_SUFFIX += "QT.$${MODULE}_private.includes += $$val_escape(MODULE_SHADOW_PRIVATE_INCLUDES)"
-    }
     MODULE_PRI_CONT = \
         "QT.$${MODULE_ID}.VERSION = $${VERSION}" \
         "QT.$${MODULE_ID}.MAJOR_VERSION = $$section(VERSION, ., 0, 0)" \
@@ -143,7 +115,7 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
 
     need_fwd_pri {
 
-        split_incpath: \
+        !git_build: \
             MODULE_BASE_INCDIR = $$MODULE_BASE_INDIR
         else: \
             MODULE_BASE_INCDIR = $$MODULE_BASE_OUTDIR
@@ -163,7 +135,15 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
         !internal_module:!no_private_module: MODULE_FWD_PRI_CONT += \
             "include($$val_escape(MODULE_PRIVATE_PRI))" \
             "QT.$${MODULE}_private.priority = 1"
-        MODULE_FWD_PRI_CONT += $$MODULE_FWD_PRI_CONT_SUFFIX
+        !isEmpty(MODULE_FWD_INCLUDES) {
+            !lib_bundle: \
+                pls = +
+            MODULE_FWD_PRI_CONT += \
+                "QT.$${MODULE_ID}.includes $$pls= $$MODULE_FWD_INCLUDES"
+            !internal_module: \
+                MODULE_FWD_PRI_CONT += \
+                    "QT.$${MODULE}_private.includes $$pls= $$MODULE_FWD_PRIVATE_INCLUDES"
+        }
         write_file($$MODULE_FWD_PRI, MODULE_FWD_PRI_CONT)|error("Aborting.")
         touch($$MODULE_FWD_PRI, $$MODULE_PRI)
         MODULE_PRI_FILES += $$MODULE_FWD_PRI
diff --git a/mkspecs/features/qt_tool.prf b/mkspecs/features/qt_tool.prf
index 3f0301a2929e390218318c974020ffbaa42d69ba..839c3d6b887dd6eab107e837f2f60425a9363874 100644
--- a/mkspecs/features/qt_tool.prf
+++ b/mkspecs/features/qt_tool.prf
@@ -64,3 +64,5 @@ DEFINES *= QT_USE_QSTRINGBUILDER
         cache(QT_TOOL.$${MODULE}.$$var, transient)
 
 }
+# The variable is re-used by qtPrepareTool(), and we really don't want that.
+unset(QT_TOOL_ENV)
diff --git a/mkspecs/features/testcase.prf b/mkspecs/features/testcase.prf
index 6bac0546c32da8295f3c7e0dd310941a284ebe33..5ad372f976ce3d7597c8eddcefee76eef832e279 100644
--- a/mkspecs/features/testcase.prf
+++ b/mkspecs/features/testcase.prf
@@ -9,6 +9,11 @@ testcase_exceptions: CONFIG += exceptions
 check.files                =
 check.path                 = .
 
+# Add environment for non-installed builds. Do this first, so the
+# 'make' variable expansions don't end up in a batch file/script.
+QT_TOOL_NAME = target
+qtAddTargetEnv(check.commands, QT)
+
 # If the test ends up in a different directory, we should cd to that directory.
 TESTRUN_CWD = $$DESTDIR
 
@@ -40,10 +45,6 @@ unix {
 # Allow for custom arguments to tests
 check.commands += $(TESTARGS)
 
-# Add environment for non-installed builds
-qtAddTargetEnv(check.commands, QT)
-
-# This must happen after adding the environment.
 !isEmpty(TESTRUN_CWD):!contains(TESTRUN_CWD, ^\\./?): \
     check.commands = cd $$shell_path($$TESTRUN_CWD) && $$check.commands
 
diff --git a/mkspecs/features/win32/idcidl.prf b/mkspecs/features/win32/idcidl.prf
index a688b3ff413dd21a1ffba1c6440983c009b17c94..fba7173e79be3552d0787235f4e5b75266b824fa 100644
--- a/mkspecs/features/win32/idcidl.prf
+++ b/mkspecs/features/win32/idcidl.prf
@@ -1,4 +1,4 @@
-build_pass:console: {
+build_pass:console {
     warning("QAxServer applications cannot be console applications.")
     warning("Remove 'console' from your CONFIG.")
 }
diff --git a/mkspecs/features/win32/windows.prf b/mkspecs/features/win32/windows.prf
index 6ea9756f9af1ab5eba39fdfcecec10484c32c659..986067fc8c95c195c5061ea9eb7d1916c065dbb9 100644
--- a/mkspecs/features/win32/windows.prf
+++ b/mkspecs/features/win32/windows.prf
@@ -5,7 +5,7 @@ contains(TEMPLATE, ".*app") {
     mingw:DEFINES += QT_NEEDS_QMAIN
 
     qt:for(entryLib, $$list($$unique(QMAKE_LIBS_QT_ENTRY))) {
-        isEqual(entryLib, -lqtmain): {
+        isEqual(entryLib, -lqtmain) {
             !contains(QMAKE_DEFAULT_LIBDIRS, $$QT.core.libs): \
                 QMAKE_LIBS += -L$$QT.core.libs
             CONFIG(debug, debug|release): QMAKE_LIBS += $${entryLib}$${QT_LIBINFIX}d
diff --git a/mkspecs/win32-g++/qmake.conf b/mkspecs/win32-g++/qmake.conf
index 9cb811b5bf86b2803fb02a2fc523d862918baff5..61963c7b0df21319a24e59896a61cb025aa35133 100644
--- a/mkspecs/win32-g++/qmake.conf
+++ b/mkspecs/win32-g++/qmake.conf
@@ -85,7 +85,6 @@ QMAKE_LFLAGS_CXX11      =
 QMAKE_LFLAGS_CXX14      =
 QMAKE_LFLAGS_CXX1Z      =
 QMAKE_LFLAGS_GCSECTIONS = -Wl,--gc-sections
-QMAKE_LFLAGS_USE_GOLD   = -fuse-ld=gold
 QMAKE_LINK_OBJECT_MAX   = 10
 QMAKE_LINK_OBJECT_SCRIPT = object_script
 QMAKE_PREFIX_SHLIB      =
diff --git a/qmake/generators/makefiledeps.cpp b/qmake/generators/makefiledeps.cpp
index 53e095474927ae9dd0c69d63de8e9035eb229822..047d17f18aaf4e8749e89bd65c37664e781deae0 100644
--- a/qmake/generators/makefiledeps.cpp
+++ b/qmake/generators/makefiledeps.cpp
@@ -422,6 +422,87 @@ static bool matchWhileUnsplitting(const char *buffer, int buffer_len, int start,
     return true;
 }
 
+/* Advance from an opening quote at buffer[offset] to the matching close quote. */
+static int scanPastString(char *buffer, int buffer_len, int offset, int *lines)
+{
+    // It might be a C++11 raw string.
+    bool israw = false;
+    if (buffer[offset] == '"' && offset > 0) {
+        int explore = offset - 1;
+        while (explore > 0 && buffer[explore] != 'R') {
+            if (buffer[explore] == '8' || buffer[explore] == 'u' || buffer[explore] == 'U') {
+                explore--;
+            } else if (explore > 1 && qmake_endOfLine(buffer[explore])
+                       && buffer[explore - 1] == '\\') {
+                explore -= 2;
+            } else if (explore > 2 && buffer[explore] == '\n'
+                       && buffer[explore - 1] == '\r'
+                       && buffer[explore - 2] == '\\') {
+                explore -= 3;
+            } else {
+                break;
+            }
+        }
+        israw = (buffer[explore] == 'R');
+    }
+
+    if (israw) {
+#define SKIP_BSNL(pos) skipEscapedLineEnds(buffer, buffer_len, (pos), lines)
+
+        offset = SKIP_BSNL(offset + 1);
+        const char *const delim = buffer + offset;
+        int clean = offset;
+        while (offset < buffer_len && buffer[offset] != '(') {
+            if (clean < offset)
+                buffer[clean++] = buffer[offset];
+            else
+                clean++;
+
+            offset = SKIP_BSNL(offset + 1);
+        }
+        /*
+          Not checking correctness (trust real compiler to do that):
+          - no controls, spaces, '(', ')', '\\' or (presumably) '"' in delim;
+          - at most 16 bytes in delim
+
+          Raw strings are surely defined after phase 2, when BSNLs are resolved;
+          so the delimiter's exclusion of '\\' and space (including newlines)
+          applies too late to save us the need to cope with BSNLs in it.
+        */
+
+        const int delimlen = buffer + clean - delim;
+        int matchlen = delimlen, extralines = 0;
+        while ((offset = SKIP_BSNL(offset + 1)) < buffer_len
+               && (buffer[offset] != ')'
+                   || (delimlen > 0 &&
+                       !matchWhileUnsplitting(buffer, buffer_len,
+                                              offset + 1, delim, delimlen,
+                                              &matchlen, &extralines))
+                   || buffer[offset + 1 + matchlen] != '"')) {
+            // skip, but keep track of lines
+            if (qmake_endOfLine(buffer[offset]))
+                ++*lines;
+            extralines = 0;
+        }
+        *lines += extralines; // from the match
+        // buffer[offset] is ')'
+        offset += 1 + matchlen; // 1 for ')', then delim
+        // buffer[offset] is '"'
+
+#undef SKIP_BSNL
+    } else { // Traditional string or char literal:
+        const char term = buffer[offset];
+        while (++offset < buffer_len && buffer[offset] != term) {
+            if (buffer[offset] == '\\')
+                ++offset;
+            else if (qmake_endOfLine(buffer[offset]))
+                ++*lines;
+        }
+    }
+
+    return offset;
+}
+
 bool QMakeSourceFileInfo::findDeps(SourceFile *file)
 {
     if(file->dep_checked || file->type == TYPE_UNKNOWN)
@@ -696,75 +777,7 @@ bool QMakeSourceFileInfo::findDeps(SourceFile *file)
                 case InCode:
                     // matching quotes (string literals and character literals)
                     if (buffer[x] == '\'' || buffer[x] == '"') {
-                        // It might be a C++11 raw string.
-                        bool israw = false;
-                        if (buffer[x] == '"' && x > 0) {
-                            int y = x - 1;
-                            while (y > 0 && buffer[y] != 'R') {
-                                if (buffer[y] == '8' || buffer[y] == 'u' || buffer[y] == 'U')
-                                    y--;
-                                else if (y > 1 && qmake_endOfLine(buffer[y])
-                                         && buffer[y - 1] == '\\')
-                                    y -= 2;
-                                else if (y > 2 && buffer[y] == '\n'
-                                         && buffer[y - 1] == '\r'
-                                         && buffer[y - 2] == '\\')
-                                    y -= 3;
-                                else
-                                    break;
-                            }
-                            israw = (buffer[y] == 'R');
-                        }
-                        if (israw) {
-                            x = SKIP_BSNL(x + 1);
-                            const char *const delim = buffer + x;
-                            int clean = x;
-                            while (x < buffer_len && buffer[x] != '(') {
-                                if (clean < x)
-                                    buffer[clean++] = buffer[x];
-                                else
-                                    clean++;
-
-                                x = SKIP_BSNL(x + 1);
-                            }
-                            /*
-                              Not checking correctness (trust real compiler to do that):
-                              - no controls, spaces, '(', ')', '\\' or (presumably) '"' in delim;
-                              - at most 16 bytes in delim
-
-                              Raw strings are surely defined after phase 2, when
-                              BSNLs are resolved; so the delimiter's exclusion
-                              of '\\' and space (including newlines) applies too
-                              late to save us the need to cope with BSNLs in it.
-                            */
-
-                            const int delimlen = buffer + clean - delim;
-                            int matchlen = delimlen, extralines = 0;
-                            while ((x = SKIP_BSNL(x + 1)) < buffer_len
-                                   && (buffer[x] != ')'
-                                       || (delimlen > 0 &&
-                                           !matchWhileUnsplitting(buffer, buffer_len,
-                                                                  x + 1, delim, delimlen,
-                                                                  &matchlen, &extralines))
-                                       || buffer[x + 1 + matchlen] != '"')) {
-                                // skip, but keep track of lines
-                                if (qmake_endOfLine(buffer[x]))
-                                    ++line_count;
-                                extralines = 0;
-                            }
-                            line_count += extralines; // from the match
-                            // buffer[x] is ')'
-                            x += 1 + matchlen; // 1 for ')', then delim
-                            // buffer[x] is '"'
-                        } else {
-                            const char term = buffer[x];
-                            while (++x < buffer_len && buffer[x] != term) {
-                                if (buffer[x] == '\\')
-                                    ++x;
-                                else if (qmake_endOfLine(buffer[x]))
-                                    ++line_count;
-                            }
-                        }
+                        x = scanPastString(buffer, buffer_len, x, &line_count);
                         // for loop's ++x shall step over the closing quote.
                     }
                     // else: buffer[x] is just some code; move on.
@@ -859,7 +872,7 @@ bool QMakeSourceFileInfo::findMocs(SourceFile *file)
     files_changed = true;
     file->moc_checked = true;
 
-    int buffer_len;
+    int buffer_len = 0;
     char *buffer = 0;
     {
         struct stat fst;
@@ -877,101 +890,101 @@ bool QMakeSourceFileInfo::findMocs(SourceFile *file)
             return false; //shouldn't happen
         }
         buffer = getBuffer(fst.st_size);
-        for(int have_read = buffer_len = 0;
-            (have_read = QT_READ(fd, buffer + buffer_len, fst.st_size - buffer_len));
-            buffer_len += have_read) ;
+        while (int have_read = QT_READ(fd, buffer + buffer_len, fst.st_size - buffer_len))
+            buffer_len += have_read;
+
         QT_CLOSE(fd);
     }
 
     debug_msg(2, "findMocs: %s", file->file.local().toLatin1().constData());
     int line_count = 1;
-    bool ignore_qobject = false, ignore_qgadget = false;
+    bool ignore[2] = { false, false }; // [0] for Q_OBJECT, [1] for Q_GADGET
  /* qmake ignore Q_GADGET */
  /* qmake ignore Q_OBJECT */
     for(int x = 0; x < buffer_len; x++) {
+#define SKIP_BSNL(pos) skipEscapedLineEnds(buffer, buffer_len, (pos), &line_count)
+        x = SKIP_BSNL(x);
         if (buffer[x] == '/') {
-            ++x;
-            if(buffer_len >= x) {
-                if (buffer[x] == '/') { // C++-style comment
-                    for (; x < buffer_len && !qmake_endOfLine(buffer[x]); ++x) {} // skip
-                } else if (buffer[x] == '*') { // C-style comment
-                    for(++x; x < buffer_len; ++x) {
+            int extralines = 0;
+            int y = skipEscapedLineEnds(buffer, buffer_len, x + 1, &extralines);
+            if (buffer_len > y) {
+                // If comment, advance to the character that ends it:
+                if (buffer[y] == '/') { // C++-style comment
+                    line_count += extralines;
+                    x = y;
+                    do {
+                        x = SKIP_BSNL(x + 1);
+                    } while (x < buffer_len && !qmake_endOfLine(buffer[x]));
+
+                } else if (buffer[y] == '*') { // C-style comment
+                    line_count += extralines;
+                    x = SKIP_BSNL(y + 1);
+                    for (; x < buffer_len; x = SKIP_BSNL(x + 1)) {
                         if (buffer[x] == 't' || buffer[x] == 'q') { // ignore
                             if(buffer_len >= (x + 20) &&
                                !strncmp(buffer + x + 1, "make ignore Q_OBJECT", 20)) {
                                 debug_msg(2, "Mocgen: %s:%d Found \"qmake ignore Q_OBJECT\"",
                                           file->file.real().toLatin1().constData(), line_count);
                                 x += 20;
-                                ignore_qobject = true;
+                                ignore[0] = true;
                             } else if(buffer_len >= (x + 20) &&
                                       !strncmp(buffer + x + 1, "make ignore Q_GADGET", 20)) {
                                 debug_msg(2, "Mocgen: %s:%d Found \"qmake ignore Q_GADGET\"",
                                           file->file.real().toLatin1().constData(), line_count);
                                 x += 20;
-                                ignore_qgadget = true;
+                                ignore[1] = true;
                             }
                         } else if (buffer[x] == '*') {
-                            if (buffer_len >= x + 1 && buffer[x + 1] == '/') {
-                                ++x;
+                            extralines = 0;
+                            y = skipEscapedLineEnds(buffer, buffer_len, x + 1, &extralines);
+                            if (buffer_len > y && buffer[y] == '/') {
+                                line_count += extralines;
+                                x = y;
                                 break;
                             }
                         } else if (Option::debug_level && qmake_endOfLine(buffer[x])) {
                             ++line_count;
                         }
                     }
-                } else { // not a comment, in fact; undo the extra x++ we did.
-                    x--;
                 }
+                // else: don't update x, buffer[x] is just the division operator.
             }
         } else if (buffer[x] == '\'' || buffer[x] == '"') {
-            const char term = buffer[x++];
-            while(x < buffer_len) {
-                if (buffer[x] == term)
-                    break;
-                if (buffer[x] == '\\') {
-                    x+=2;
-                } else {
-                    if (qmake_endOfLine(buffer[x]))
-                        ++line_count;
-                    ++x;
-                }
-            }
+            x = scanPastString(buffer, buffer_len, x, &line_count);
+            // Leaves us on closing quote; for loop's x++ steps us past it.
         }
-        if (Option::debug_level && qmake_endOfLine(buffer[x]))
+
+        if (x < buffer_len && Option::debug_level && qmake_endOfLine(buffer[x]))
             ++line_count;
-        if (buffer_len > x + 2 && buffer[x + 1] == 'Q' &&
-            buffer[x + 2] == '_' && !isCWordChar(buffer[x])) {
-            ++x;
-            int match = 0;
-            static const char *interesting[] = { "OBJECT", "GADGET" };
-            for (int interest = 0, m1, m2; interest < 2; ++interest) {
-                if(interest == 0 && ignore_qobject)
-                    continue;
-                else if(interest == 1 && ignore_qgadget)
-                    continue;
-                for (m1 = 0, m2 = 0; interesting[interest][m1]; ++m1) {
-                    if (interesting[interest][m1] != buffer[x + 2 + m1]) {
-                        m2 = -1;
-                        break;
+        if (buffer_len > x + 8 && !isCWordChar(buffer[x])) {
+            int morelines = 0;
+            int y = skipEscapedLineEnds(buffer, buffer_len, x + 1, &morelines);
+            if (buffer[y] == 'Q') {
+                static const char interesting[][9] = { "Q_OBJECT", "Q_GADGET" };
+                for (int interest = 0; interest < 2; ++interest) {
+                    if (ignore[interest])
+                        continue;
+
+                    int matchlen = 0, extralines = 0;
+                    if (matchWhileUnsplitting(buffer, buffer_len, y,
+                                              interesting[interest],
+                                              strlen(interesting[interest]),
+                                              &matchlen, &extralines)
+                        && y + matchlen < buffer_len
+                        && !isCWordChar(buffer[y + matchlen])) {
+                        if (Option::debug_level) {
+                            buffer[y + matchlen] = '\0';
+                            debug_msg(2, "Mocgen: %s:%d Found MOC symbol %s",
+                                      file->file.real().toLatin1().constData(),
+                                      line_count + morelines, buffer + y);
+                        }
+                        file->mocable = true;
+                        return true;
                     }
-                    ++m2;
-                }
-                if(m1 == m2) {
-                    match = m2 + 2;
-                    break;
                 }
             }
-            if (match && !isCWordChar(buffer[x + match])) {
-                if (Option::debug_level) {
-                    buffer[x + match] = '\0';
-                    debug_msg(2, "Mocgen: %s:%d Found MOC symbol %s",
-                              file->file.real().toLatin1().constData(),
-                              line_count, buffer + x);
-                }
-                file->mocable = true;
-                return true;
-            }
         }
+#undef SKIP_BSNL
     }
     return true;
 }
diff --git a/qmake/generators/win32/msbuild_objectmodel.cpp b/qmake/generators/win32/msbuild_objectmodel.cpp
index aad6e6e8787e5935a56e19e206c03a3d674ad8ef..8e2be589cdd19f839cb5eab00b9bd93165a1c088 100644
--- a/qmake/generators/win32/msbuild_objectmodel.cpp
+++ b/qmake/generators/win32/msbuild_objectmodel.cpp
@@ -628,7 +628,7 @@ void VCXProjectWriter::write(XmlOutput &xml, VCProject &tool)
             << tagValue("Platform", tool.SingleProjects.at(i).PlatformName)
             << closetag();
         isWinRT = isWinRT || tool.SingleProjects.at(i).Configuration.WinRT;
-        isWinPhone = isWinPhone = tool.SingleProjects.at(i).Configuration.WinPhone;
+        isWinPhone = isWinPhone || tool.SingleProjects.at(i).Configuration.WinPhone;
     }
 
     xml << closetag()
diff --git a/qmake/generators/win32/msvc_objectmodel.cpp b/qmake/generators/win32/msvc_objectmodel.cpp
index 339dae953aea8641ea2c5df8030fe78a5fff913a..18457ac5ad3db2b5d9f5039a4cc046e86d6d511c 100644
--- a/qmake/generators/win32/msvc_objectmodel.cpp
+++ b/qmake/generators/win32/msvc_objectmodel.cpp
@@ -2399,11 +2399,7 @@ bool VCFilter::addExtraCompiler(const VCFilterFile &info)
         if (!CustomBuildTool.Description.isEmpty())
             CustomBuildTool.Description += ", ";
         CustomBuildTool.Description += cmd_name;
-        // Execute custom build steps in an environment variable scope to prevent unwanted
-        // side effects for downstream build steps
-        CustomBuildTool.CommandLine += QLatin1String("setlocal");
         CustomBuildTool.CommandLine += VCToolBase::fixCommandLine(cmd.trimmed());
-        CustomBuildTool.CommandLine += QLatin1String("endlocal");
         int space = cmd.indexOf(' ');
         QFileInfo finf(cmd.left(space));
         if (CustomBuildTool.ToolPath.isEmpty())
diff --git a/qmake/generators/win32/msvc_vcproj.cpp b/qmake/generators/win32/msvc_vcproj.cpp
index 1e187075c8877e473030f16367cdbe1453f963c9..465c8fc31295896dffdd065579306ec0b1cc8b05 100644
--- a/qmake/generators/win32/msvc_vcproj.cpp
+++ b/qmake/generators/win32/msvc_vcproj.cpp
@@ -1428,11 +1428,11 @@ void VcprojGenerator::initWinDeployQtTool()
         //  itself contains the original subdirectories as parameters and hence the
         //  call fails.
         //  Neither there is a way to disable this behavior for Windows Phone, nor
-        //  to influence the parameters. Hence the only way to get a release build
+        //  to influence the parameters. Hence the only way to get a build
         //  done is to recreate the directory structure manually by invoking
         //  windeployqt a second time, so that the MDILXapCompile call succeeds and
         //  deployment continues.
-        if (conf.WinPhone && conf.Name == QStringLiteral("Release|ARM")) {
+        if (conf.WinPhone) {
             conf.windeployqt.CommandLine = commandLine
                     + QStringLiteral(" -list relative -dir \"$(MSBuildProjectDirectory)\\")
                     + var("OBJECTS_DIR")
diff --git a/qmake/library/qmakebuiltins.cpp b/qmake/library/qmakebuiltins.cpp
index f57d9c89a7d30c7e500807e7ad9183369dc0bf20..02cd8a276062f83133d585b65fd3a126e3fe1385 100644
--- a/qmake/library/qmakebuiltins.cpp
+++ b/qmake/library/qmakebuiltins.cpp
@@ -358,10 +358,10 @@ static QMakeEvaluator::VisitReturn parseJsonInto(const QByteArray &json, const Q
 
 QMakeEvaluator::VisitReturn
 QMakeEvaluator::writeFile(const QString &ctx, const QString &fn, QIODevice::OpenMode mode,
-                          const QString &contents)
+                          bool exe, const QString &contents)
 {
     QString errStr;
-    if (!m_vfs->writeFile(fn, mode, contents, &errStr)) {
+    if (!m_vfs->writeFile(fn, mode, exe, contents, &errStr)) {
         evalError(fL1S("Cannot write %1file %2: %3")
                   .arg(ctx, QDir::toNativeSeparators(fn), errStr));
         return ReturnFalse;
@@ -1470,8 +1470,12 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateBuiltinConditional(
                 fputs(msg.toLatin1().constData(), stderr);
 #endif
             } else {
-                m_handler->fileMessage(fL1S("Project %1: %2")
-                                       .arg(function.toQString(m_tmp1).toUpper(), msg));
+                m_handler->fileMessage(
+                        (func_t == T_ERROR   ? QMakeHandler::ErrorMessage :
+                         func_t == T_WARNING ? QMakeHandler::WarningMessage :
+                                               QMakeHandler::InfoMessage)
+                        | (m_cumulative ? QMakeHandler::CumulativeEvalMessage : 0),
+                        fL1S("Project %1: %2").arg(function.toQString(m_tmp1).toUpper(), msg));
             }
         }
         return (func_t == T_ERROR && !m_cumulative) ? ReturnError : ReturnTrue;
@@ -1543,22 +1547,33 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateBuiltinConditional(
     }
     case T_WRITE_FILE: {
         if (args.count() > 3) {
-            evalError(fL1S("write_file(name, [content var, [append]]) requires one to three arguments."));
+            evalError(fL1S("write_file(name, [content var, [append] [exe]]) requires one to three arguments."));
             return ReturnFalse;
         }
         QIODevice::OpenMode mode = QIODevice::Truncate;
+        bool exe = false;
         QString contents;
         if (args.count() >= 2) {
             const ProStringList &vals = values(args.at(1).toKey());
             if (!vals.isEmpty())
                 contents = vals.join(QLatin1Char('\n')) + QLatin1Char('\n');
-            if (args.count() >= 3)
-                if (!args.at(2).toQString(m_tmp1).compare(fL1S("append"), Qt::CaseInsensitive))
-                    mode = QIODevice::Append;
+            if (args.count() >= 3) {
+                foreach (const ProString &opt, split_value_list(args.at(2).toQString(m_tmp2))) {
+                    opt.toQString(m_tmp3);
+                    if (m_tmp3 == QLatin1String("append")) {
+                        mode = QIODevice::Append;
+                    } else if (m_tmp3 == QLatin1String("exe")) {
+                        exe = true;
+                    } else {
+                        evalError(fL1S("write_file(): invalid flag %1.").arg(m_tmp3));
+                        return ReturnFalse;
+                    }
+                }
+            }
         }
         QString path = resolvePath(args.at(0).toQString(m_tmp1));
         path.detach(); // make sure to not leak m_tmp1 into the map of written files.
-        return writeFile(QString(), path, mode, contents);
+        return writeFile(QString(), path, mode, exe, contents);
     }
     case T_TOUCH: {
         if (args.count() != 2) {
@@ -1769,7 +1784,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateBuiltinConditional(
                 valuesRef(ProKey("_QMAKE_STASH_")) << ProString(fn);
             }
         }
-        return writeFile(fL1S("cache "), fn, QIODevice::Append, varstr);
+        return writeFile(fL1S("cache "), fn, QIODevice::Append, false, varstr);
     }
     default:
         evalError(fL1S("Function '%1' is not implemented.").arg(function.toQString(m_tmp1)));
diff --git a/qmake/library/qmakeevaluator.cpp b/qmake/library/qmakeevaluator.cpp
index e220d59517419b74794e489f660c596ae6c14277..4c5ce2e097859d8982891ec408cde9747b620d79 100644
--- a/qmake/library/qmakeevaluator.cpp
+++ b/qmake/library/qmakeevaluator.cpp
@@ -1306,7 +1306,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConfigFeatures()
                 config.detach();
                 processed.insert(config);
                 VisitReturn vr = evaluateFeatureFile(config, true);
-                if (vr == ReturnError)
+                if (vr == ReturnError && !m_cumulative)
                     return vr;
                 if (vr == ReturnTrue) {
                     finished = false;
diff --git a/qmake/library/qmakeevaluator.h b/qmake/library/qmakeevaluator.h
index 8995d495829576090ab34e1618196381682f1c61..9560f715875f723b02e9443ac906bb0a2ae3a100 100644
--- a/qmake/library/qmakeevaluator.h
+++ b/qmake/library/qmakeevaluator.h
@@ -41,7 +41,6 @@
 #include "qmakeparser.h"
 #include "ioutils.h"
 
-#include <qiodevice.h>
 #include <qlist.h>
 #include <qlinkedlist.h>
 #include <qmap.h>
@@ -52,6 +51,8 @@
 #include <qshareddata.h>
 #ifndef QT_BOOTSTRAPPED
 # include <qprocess.h>
+#else
+# include <qiodevice.h>
 #endif
 #ifdef PROEVALUATOR_THREAD_SAFE
 # include <qmutex.h>
@@ -67,6 +68,8 @@ public:
     enum {
         SourceEvaluator = 0x10,
 
+        CumulativeEvalMessage = 0x1000,
+
         EvalWarnLanguage = SourceEvaluator |  WarningMessage | WarnLanguage,
         EvalWarnDeprecated = SourceEvaluator | WarningMessage | WarnDeprecated,
 
@@ -74,7 +77,7 @@ public:
     };
 
     // error(), warning() and message() from .pro file
-    virtual void fileMessage(const QString &msg) = 0;
+    virtual void fileMessage(int type, const QString &msg) = 0;
 
     enum EvalFileType { EvalProjectFile, EvalIncludeFile, EvalConfigFile, EvalFeatureFile, EvalAuxFile };
     virtual void aboutToEval(ProFile *parent, ProFile *proFile, EvalFileType type) = 0;
@@ -235,7 +238,7 @@ public:
             QMultiMap<int, ProString> &rootSet) const;
 
     VisitReturn writeFile(const QString &ctx, const QString &fn, QIODevice::OpenMode mode,
-                          const QString &contents);
+                          bool exe, const QString &contents);
 #ifndef QT_BOOTSTRAPPED
     void runProcess(QProcess *proc, const QString &command) const;
 #endif
diff --git a/qmake/library/qmakeparser.h b/qmake/library/qmakeparser.h
index dfea1ddfdf853b66b62bd96d32907e41b2d3ced6..7fa4f62a963a69584d5fbf468c72b93fff9707d8 100644
--- a/qmake/library/qmakeparser.h
+++ b/qmake/library/qmakeparser.h
@@ -50,8 +50,9 @@ class QMAKE_EXPORT QMakeParserHandler
 public:
     enum {
         CategoryMask = 0xf00,
-        WarningMessage = 0x000,
-        ErrorMessage = 0x100,
+        InfoMessage = 0x100,
+        WarningMessage = 0x200,
+        ErrorMessage = 0x300,
 
         SourceMask = 0xf0,
         SourceParser = 0,
diff --git a/qmake/library/qmakevfs.cpp b/qmake/library/qmakevfs.cpp
index 613e4e90d793d19b35ed5571b096b1132cb4723b..d23d1f06ff3a572c37d31b7fc8f7e06d38944056 100644
--- a/qmake/library/qmakevfs.cpp
+++ b/qmake/library/qmakevfs.cpp
@@ -52,8 +52,8 @@ QMakeVfs::QMakeVfs()
 {
 }
 
-bool QMakeVfs::writeFile(const QString &fn, QIODevice::OpenMode mode, const QString &contents,
-                         QString *errStr)
+bool QMakeVfs::writeFile(const QString &fn, QIODevice::OpenMode mode, bool exe,
+                         const QString &contents, QString *errStr)
 {
 #ifndef PROEVALUATOR_FULL
 # ifdef PROEVALUATOR_THREAD_SAFE
@@ -75,8 +75,16 @@ bool QMakeVfs::writeFile(const QString &fn, QIODevice::OpenMode mode, const QStr
     QByteArray bytes = contents.toLocal8Bit();
     QFile cfile(fn);
     if (!(mode & QIODevice::Append) && cfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
-        if (cfile.readAll() == bytes)
+        if (cfile.readAll() == bytes) {
+            if (exe) {
+                cfile.setPermissions(cfile.permissions()
+                                     | QFile::ExeUser | QFile::ExeGroup | QFile::ExeOther);
+            } else {
+                cfile.setPermissions(cfile.permissions()
+                                     & ~(QFile::ExeUser | QFile::ExeGroup | QFile::ExeOther));
+            }
             return true;
+        }
         cfile.close();
     }
     if (!cfile.open(mode | QIODevice::WriteOnly | QIODevice::Text)) {
@@ -89,6 +97,9 @@ bool QMakeVfs::writeFile(const QString &fn, QIODevice::OpenMode mode, const QStr
         *errStr = cfile.errorString();
         return false;
     }
+    if (exe)
+        cfile.setPermissions(cfile.permissions()
+                             | QFile::ExeUser | QFile::ExeGroup | QFile::ExeOther);
     return true;
 #endif
 }
diff --git a/qmake/library/qmakevfs.h b/qmake/library/qmakevfs.h
index 8eeae15dccb21f3b6f6d46a395d6df4d2a68140b..1bc11d35932935f69a4d636fe56744bc90e751ad 100644
--- a/qmake/library/qmakevfs.h
+++ b/qmake/library/qmakevfs.h
@@ -52,7 +52,7 @@ class QMAKE_EXPORT QMakeVfs
 public:
     QMakeVfs();
 
-    bool writeFile(const QString &fn, QIODevice::OpenMode mode, const QString &contents, QString *errStr);
+    bool writeFile(const QString &fn, QIODevice::OpenMode mode, bool exe, const QString &contents, QString *errStr);
     bool readFile(const QString &fn, QString *contents, QString *errStr);
     bool exists(const QString &fn);
 
diff --git a/qmake/option.cpp b/qmake/option.cpp
index da59616e5ce1dbb2646d5245f9337f63034cb378..46bfa33dd39ff36fe7770d3c776e1fdc500b222c 100644
--- a/qmake/option.cpp
+++ b/qmake/option.cpp
@@ -601,8 +601,9 @@ void EvalHandler::message(int type, const QString &msg, const QString &fileName,
         fprintf(stderr, "%s%s\n", qPrintable(pfx), qPrintable(msg));
 }
 
-void EvalHandler::fileMessage(const QString &msg)
+void EvalHandler::fileMessage(int type, const QString &msg)
 {
+    Q_UNUSED(type)
     fprintf(stderr, "%s\n", qPrintable(msg));
 }
 
diff --git a/qmake/option.h b/qmake/option.h
index 663f096072da7b73f3b396daf5789b3171f15999..cb3eb1341a6406523bb5294cf6f018a0f3c3900b 100644
--- a/qmake/option.h
+++ b/qmake/option.h
@@ -67,7 +67,7 @@ class EvalHandler : public QMakeHandler {
 public:
     void message(int type, const QString &msg, const QString &fileName, int lineNo);
 
-    void fileMessage(const QString &msg);
+    void fileMessage(int type, const QString &msg);
 
     void aboutToEval(ProFile *, ProFile *, EvalFileType);
     void doneWithEval(ProFile *);
diff --git a/src/3rdparty/pcre/pcre.h b/src/3rdparty/pcre/pcre.h
index c2557cf4b1bdc5c58ffdd4271c6f14fd46669789..609deb5be64bd25a7324127a8f00f99abb24c9a2 100644
--- a/src/3rdparty/pcre/pcre.h
+++ b/src/3rdparty/pcre/pcre.h
@@ -42,9 +42,9 @@ POSSIBILITY OF SUCH DAMAGE.
 /* The current PCRE version information. */
 
 #define PCRE_MAJOR          8
-#define PCRE_MINOR          38
+#define PCRE_MINOR          39
 #define PCRE_PRERELEASE     -RC1
-#define PCRE_DATE           2015-05-03
+#define PCRE_DATE           2015-11-23
 
 /* When an application links to a PCRE DLL in Windows, the symbols that are
 imported have to be identified as such. When building PCRE, the appropriate
diff --git a/src/3rdparty/pcre/pcre_compile.c b/src/3rdparty/pcre/pcre_compile.c
index 866aa8c693d20e0e3744bdc5945137b250600f79..b9a239e5544fc0522585f79ac10844120075871c 100644
--- a/src/3rdparty/pcre/pcre_compile.c
+++ b/src/3rdparty/pcre/pcre_compile.c
@@ -4639,16 +4639,16 @@ for (;; ptr++)
   /* In the real compile phase, just check the workspace used by the forward
   reference list. */
 
-  else if (cd->hwm > cd->start_workspace + cd->workspace_size -
-           WORK_SIZE_SAFETY_MARGIN)
+  else if (cd->hwm > cd->start_workspace + cd->workspace_size)
     {
     *errorcodeptr = ERR52;
     goto FAILED;
     }
 
-  /* If in \Q...\E, check for the end; if not, we have a literal */
+  /* If in \Q...\E, check for the end; if not, we have a literal. Otherwise an
+  isolated \E is ignored. */
 
-  if (inescq && c != CHAR_NULL)
+  if (c != CHAR_NULL)
     {
     if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E)
       {
@@ -4656,7 +4656,7 @@ for (;; ptr++)
       ptr++;
       continue;
       }
-    else
+    else if (inescq)
       {
       if (previous_callout != NULL)
         {
@@ -4671,18 +4671,27 @@ for (;; ptr++)
         }
       goto NORMAL_CHAR;
       }
-    /* Control does not reach here. */
+
+    /* Check for the start of a \Q...\E sequence. We must do this here rather
+    than later in case it is immediately followed by \E, which turns it into a
+    "do nothing" sequence. */
+
+    if (c == CHAR_BACKSLASH && ptr[1] == CHAR_Q)
+      {
+      inescq = TRUE;
+      ptr++;
+      continue;
+      }
     }
 
-  /* In extended mode, skip white space and comments. We need a loop in order
-  to check for more white space and more comments after a comment. */
+  /* In extended mode, skip white space and comments. */
 
   if ((options & PCRE_EXTENDED) != 0)
     {
-    for (;;)
+    const pcre_uchar *wscptr = ptr;
+    while (MAX_255(c) && (cd->ctypes[c] & ctype_space) != 0) c = *(++ptr);
+    if (c == CHAR_NUMBER_SIGN)
       {
-      while (MAX_255(c) && (cd->ctypes[c] & ctype_space) != 0) c = *(++ptr);
-      if (c != CHAR_NUMBER_SIGN) break;
       ptr++;
       while (*ptr != CHAR_NULL)
         {
@@ -4696,10 +4705,35 @@ for (;; ptr++)
         if (utf) FORWARDCHAR(ptr);
 #endif
         }
-      c = *ptr;     /* Either NULL or the char after a newline */
+      }
+
+    /* If we skipped any characters, restart the loop. Otherwise, we didn't see
+    a comment. */
+
+    if (ptr > wscptr)
+      {
+      ptr--;
+      continue;
       }
     }
 
+  /* Skip over (?# comments. We need to do this here because we want to know if
+  the next thing is a quantifier, and these comments may come between an item
+  and its quantifier. */
+
+  if (c == CHAR_LEFT_PARENTHESIS && ptr[1] == CHAR_QUESTION_MARK &&
+      ptr[2] == CHAR_NUMBER_SIGN)
+    {
+    ptr += 3;
+    while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++;
+    if (*ptr == CHAR_NULL)
+      {
+      *errorcodeptr = ERR18;
+      goto FAILED;
+      }
+    continue;
+    }
+
   /* See if the next thing is a quantifier. */
 
   is_quantifier =
@@ -4941,9 +4975,10 @@ for (;; ptr++)
       (which is on the stack). We have to remember that there was XCLASS data,
       however. */
 
+      if (class_uchardata > class_uchardata_base) xclass = TRUE;
+
       if (lengthptr != NULL && class_uchardata > class_uchardata_base)
         {
-        xclass = TRUE;
         *lengthptr += (int)(class_uchardata - class_uchardata_base);
         class_uchardata = class_uchardata_base;
         }
@@ -5046,10 +5081,28 @@ for (;; ptr++)
             ptr = tempptr + 1;
             continue;
 
-            /* For all other POSIX classes, no special action is taken in UCP
-            mode. Fall through to the non_UCP case. */
+            /* For the other POSIX classes (ascii, cntrl, xdigit) we are going
+            to fall through to the non-UCP case and build a bit map for
+            characters with code points less than 256. If we are in a negated
+            POSIX class, characters with code points greater than 255 must
+            either all match or all not match. In the special case where we
+            have not yet generated any xclass data, and this is the final item
+            in the overall class, we need do nothing: later on, the opcode
+            OP_NCLASS will be used to indicate that characters greater than 255
+            are acceptable. If we have already seen an xclass item or one may
+            follow (we have to assume that it might if this is not the end of
+            the class), explicitly list all wide codepoints, which will then
+            either not match or match, depending on whether the class is or is
+            not negated. */
 
             default:
+            if (local_negate &&
+                (xclass || tempptr[2] != CHAR_RIGHT_SQUARE_BRACKET))
+              {
+              *class_uchardata++ = XCL_RANGE;
+              class_uchardata += PRIV(ord2utf)(0x100, class_uchardata);
+              class_uchardata += PRIV(ord2utf)(0x10ffff, class_uchardata);
+              }
             break;
             }
           }
@@ -5388,16 +5441,20 @@ for (;; ptr++)
       CLASS_SINGLE_CHARACTER:
       if (class_one_char < 2) class_one_char++;
 
-      /* If class_one_char is 1, we have the first single character in the
-      class, and there have been no prior ranges, or XCLASS items generated by
-      escapes. If this is the final character in the class, we can optimize by
-      turning the item into a 1-character OP_CHAR[I] if it's positive, or
-      OP_NOT[I] if it's negative. In the positive case, it can cause firstchar
-      to be set. Otherwise, there can be no first char if this item is first,
-      whatever repeat count may follow. In the case of reqchar, save the
-      previous value for reinstating. */
+      /* If xclass_has_prop is false and class_one_char is 1, we have the first
+      single character in the class, and there have been no prior ranges, or
+      XCLASS items generated by escapes. If this is the final character in the
+      class, we can optimize by turning the item into a 1-character OP_CHAR[I]
+      if it's positive, or OP_NOT[I] if it's negative. In the positive case, it
+      can cause firstchar to be set. Otherwise, there can be no first char if
+      this item is first, whatever repeat count may follow. In the case of
+      reqchar, save the previous value for reinstating. */
 
-      if (!inescq && class_one_char == 1 && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
+      if (!inescq &&
+#ifdef SUPPORT_UCP
+          !xclass_has_prop &&
+#endif
+          class_one_char == 1 && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET)
         {
         ptr++;
         zeroreqchar = reqchar;
@@ -5513,9 +5570,10 @@ for (;; ptr++)
     actual compiled code. */
 
 #ifdef SUPPORT_UTF
-    if (xclass && (!should_flip_negation || (options & PCRE_UCP) != 0))
+    if (xclass && (xclass_has_prop || !should_flip_negation ||
+        (options & PCRE_UCP) != 0))
 #elif !defined COMPILE_PCRE8
-    if (xclass && !should_flip_negation)
+    if (xclass && (xclass_has_prop || !should_flip_negation))
 #endif
 #if defined SUPPORT_UTF || !defined COMPILE_PCRE8
       {
@@ -6508,21 +6566,6 @@ for (;; ptr++)
     case CHAR_LEFT_PARENTHESIS:
     ptr++;
 
-    /* First deal with comments. Putting this code right at the start ensures
-    that comments have no bad side effects. */
-
-    if (ptr[0] == CHAR_QUESTION_MARK && ptr[1] == CHAR_NUMBER_SIGN)
-      {
-      ptr += 2;
-      while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++;
-      if (*ptr == CHAR_NULL)
-        {
-        *errorcodeptr = ERR18;
-        goto FAILED;
-        }
-      continue;
-      }
-
     /* Now deal with various "verbs" that can be introduced by '*'. */
 
     if (ptr[0] == CHAR_ASTERISK && (ptr[1] == ':'
@@ -6613,9 +6656,17 @@ for (;; ptr++)
               goto FAILED;
               }
             setverb = *code++ = verbs[i].op_arg;
-            *code++ = arglen;
-            memcpy(code, arg, IN_UCHARS(arglen));
-            code += arglen;
+            if (lengthptr != NULL)    /* In pass 1 just add in the length */
+              {                       /* to avoid potential workspace */
+              *lengthptr += arglen;   /* overflow. */
+              *code++ = 0;
+              }
+            else
+              {
+              *code++ = arglen;
+              memcpy(code, arg, IN_UCHARS(arglen));
+              code += arglen;
+              }
             *code++ = 0;
             }
 
@@ -6668,7 +6719,7 @@ for (;; ptr++)
         /* ------------------------------------------------------------ */
         case CHAR_VERTICAL_LINE:  /* Reset capture count for each branch */
         reset_bracount = TRUE;
-        cd->dupgroups = TRUE;     /* Record (?| encountered */ 
+        cd->dupgroups = TRUE;     /* Record (?| encountered */
         /* Fall through */
 
         /* ------------------------------------------------------------ */
@@ -6769,11 +6820,11 @@ for (;; ptr++)
           {
           while (IS_DIGIT(*ptr))
             {
-            if (recno > INT_MAX / 10 - 1)  /* Integer overflow */              
-              {                                                             
-              while (IS_DIGIT(*ptr)) ptr++;                                 
-              *errorcodeptr = ERR61;                                        
-              goto FAILED; 
+            if (recno > INT_MAX / 10 - 1)  /* Integer overflow */
+              {
+              while (IS_DIGIT(*ptr)) ptr++;
+              *errorcodeptr = ERR61;
+              goto FAILED;
               }
             recno = recno * 10 + (int)(*ptr - CHAR_0);
             ptr++;
@@ -6909,11 +6960,11 @@ for (;; ptr++)
               *errorcodeptr = ERR15;
               goto FAILED;
               }
-            if (recno > INT_MAX / 10 - 1)   /* Integer overflow */          
-              {                                                                
-              *errorcodeptr = ERR61;                                        
-              goto FAILED;                                
-              }   
+            if (recno > INT_MAX / 10 - 1)   /* Integer overflow */
+              {
+              *errorcodeptr = ERR61;
+              goto FAILED;
+              }
             recno = recno * 10 + name[i] - CHAR_0;
             }
           if (recno == 0) recno = RREF_ANY;
@@ -7191,7 +7242,7 @@ for (;; ptr++)
           {
           named_group *ng;
           recno = 0;
-           
+
           if (namelen == 0)
             {
             *errorcodeptr = ERR62;
@@ -7229,24 +7280,24 @@ for (;; ptr++)
           issue is fixed "properly" in PCRE2. As PCRE1 is now in maintenance
           only mode, we finesse the bug by allowing more memory always. */
 
-          *lengthptr += 2 + 2*LINK_SIZE;
-          
+          *lengthptr += 4 + 4*LINK_SIZE;
+
           /* It is even worse than that. The current reference may be to an
           existing named group with a different number (so apparently not
           recursive) but which later on is also attached to a group with the
-          current number. This can only happen if $(| has been previous 
-          encountered. In that case, we allow yet more memory, just in case. 
+          current number. This can only happen if $(| has been previous
+          encountered. In that case, we allow yet more memory, just in case.
           (Again, this is fixed "properly" in PCRE2. */
-          
+
           if (cd->dupgroups) *lengthptr += 4 + 4*LINK_SIZE;
 
           /* Otherwise, check for recursion here. The name table does not exist
           in the first pass; instead we must scan the list of names encountered
           so far in order to get the number. If the name is not found, leave
           the value of recno as 0 for a forward reference. */
-           
+
           else
-            { 
+            {
             ng = cd->named_groups;
             for (i = 0; i < cd->names_found; i++, ng++)
               {
@@ -7266,7 +7317,7 @@ for (;; ptr++)
                   }
                 }
               }
-            }   
+            }
           }
 
         /* In the real compile, search the name table. We check the name
@@ -7556,39 +7607,15 @@ for (;; ptr++)
         newoptions = (options | set) & (~unset);
 
         /* If the options ended with ')' this is not the start of a nested
-        group with option changes, so the options change at this level. If this
-        item is right at the start of the pattern, the options can be
-        abstracted and made external in the pre-compile phase, and ignored in
-        the compile phase. This can be helpful when matching -- for instance in
-        caseless checking of required bytes.
-
-        If the code pointer is not (cd->start_code + 1 + LINK_SIZE), we are
-        definitely *not* at the start of the pattern because something has been
-        compiled. In the pre-compile phase, however, the code pointer can have
-        that value after the start, because it gets reset as code is discarded
-        during the pre-compile. However, this can happen only at top level - if
-        we are within parentheses, the starting BRA will still be present. At
-        any parenthesis level, the length value can be used to test if anything
-        has been compiled at that level. Thus, a test for both these conditions
-        is necessary to ensure we correctly detect the start of the pattern in
-        both phases.
-
+        group with option changes, so the options change at this level.
         If we are not at the pattern start, reset the greedy defaults and the
         case value for firstchar and reqchar. */
 
         if (*ptr == CHAR_RIGHT_PARENTHESIS)
           {
-          if (code == cd->start_code + 1 + LINK_SIZE &&
-               (lengthptr == NULL || *lengthptr == 2 + 2*LINK_SIZE))
-            {
-            cd->external_options = newoptions;
-            }
-          else
-            {
-            greedy_default = ((newoptions & PCRE_UNGREEDY) != 0);
-            greedy_non_default = greedy_default ^ 1;
-            req_caseopt = ((newoptions & PCRE_CASELESS) != 0)? REQ_CASELESS:0;
-            }
+          greedy_default = ((newoptions & PCRE_UNGREEDY) != 0);
+          greedy_non_default = greedy_default ^ 1;
+          req_caseopt = ((newoptions & PCRE_CASELESS) != 0)? REQ_CASELESS:0;
 
           /* Change options at this level, and pass them back for use
           in subsequent branches. */
@@ -7867,16 +7894,6 @@ for (;; ptr++)
       c = ec;
     else
       {
-      if (escape == ESC_Q)            /* Handle start of quoted string */
-        {
-        if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E)
-          ptr += 2;               /* avoid empty string */
-            else inescq = TRUE;
-        continue;
-        }
-
-      if (escape == ESC_E) continue;  /* Perl ignores an orphan \E */
-
       /* For metasequences that actually match a character, we disable the
       setting of a first character if it hasn't already been set. */
 
@@ -9296,7 +9313,7 @@ if (errorcode != 0) goto PCRE_EARLY_ERROR_RETURN;
 
 DPRINTF(("end pre-compile: length=%d workspace=%d\n", length,
   (int)(cd->hwm - cworkspace)));
-  
+
 if (length > MAX_PATTERN_SIZE)
   {
   errorcode = ERR20;
@@ -9434,16 +9451,16 @@ if (cd->hwm > cd->start_workspace)
     int offset, recno;
     cd->hwm -= LINK_SIZE;
     offset = GET(cd->hwm, 0);
-    
+
     /* Check that the hwm handling hasn't gone wrong. This whole area is
-    rewritten in PCRE2 because there are some obscure cases. */ 
-     
+    rewritten in PCRE2 because there are some obscure cases. */
+
     if (offset == 0 || codestart[offset-1] != OP_RECURSE)
       {
-      errorcode = ERR10; 
+      errorcode = ERR10;
       break;
-      }  
- 
+      }
+
     recno = GET(codestart, offset);
     if (recno != prev_recno)
       {
diff --git a/src/3rdparty/pcre/pcre_get.c b/src/3rdparty/pcre/pcre_get.c
index 8094b34bbfb7768bc3be312a2f9b5c6c245ddd5c..cdd2abc80f2c357d5cd5d1a191d0371038c6c811 100644
--- a/src/3rdparty/pcre/pcre_get.c
+++ b/src/3rdparty/pcre/pcre_get.c
@@ -250,6 +250,7 @@ Arguments:
   code         the compiled regex
   stringname   the name of the capturing substring
   ovector      the vector of matched substrings
+  stringcount  number of captured substrings 
 
 Returns:       the number of the first that is set,
                or the number of the last one if none are set,
@@ -258,13 +259,16 @@ Returns:       the number of the first that is set,
 
 #if defined COMPILE_PCRE8
 static int
-get_first_set(const pcre *code, const char *stringname, int *ovector)
+get_first_set(const pcre *code, const char *stringname, int *ovector,
+  int stringcount)
 #elif defined COMPILE_PCRE16
 static int
-get_first_set(const pcre16 *code, PCRE_SPTR16 stringname, int *ovector)
+get_first_set(const pcre16 *code, PCRE_SPTR16 stringname, int *ovector,
+  int stringcount)
 #elif defined COMPILE_PCRE32
 static int
-get_first_set(const pcre32 *code, PCRE_SPTR32 stringname, int *ovector)
+get_first_set(const pcre32 *code, PCRE_SPTR32 stringname, int *ovector,
+  int stringcount)
 #endif
 {
 const REAL_PCRE *re = (const REAL_PCRE *)code;
@@ -295,7 +299,7 @@ if (entrysize <= 0) return entrysize;
 for (entry = (pcre_uchar *)first; entry <= (pcre_uchar *)last; entry += entrysize)
   {
   int n = GET2(entry, 0);
-  if (ovector[n*2] >= 0) return n;
+  if (n < stringcount && ovector[n*2] >= 0) return n;
   }
 return GET2(entry, 0);
 }
@@ -402,7 +406,7 @@ pcre32_copy_named_substring(const pcre32 *code, PCRE_SPTR32 subject,
   PCRE_UCHAR32 *buffer, int size)
 #endif
 {
-int n = get_first_set(code, stringname, ovector);
+int n = get_first_set(code, stringname, ovector, stringcount);
 if (n <= 0) return n;
 #if defined COMPILE_PCRE8
 return pcre_copy_substring(subject, ovector, stringcount, n, buffer, size);
@@ -457,7 +461,10 @@ pcre_uchar **stringlist;
 pcre_uchar *p;
 
 for (i = 0; i < double_count; i += 2)
-  size += sizeof(pcre_uchar *) + IN_UCHARS(ovector[i+1] - ovector[i] + 1);
+  {
+  size += sizeof(pcre_uchar *) + IN_UCHARS(1);
+  if (ovector[i+1] > ovector[i]) size += IN_UCHARS(ovector[i+1] - ovector[i]);
+  } 
 
 stringlist = (pcre_uchar **)(PUBL(malloc))(size);
 if (stringlist == NULL) return PCRE_ERROR_NOMEMORY;
@@ -473,7 +480,7 @@ p = (pcre_uchar *)(stringlist + stringcount + 1);
 
 for (i = 0; i < double_count; i += 2)
   {
-  int len = ovector[i+1] - ovector[i];
+  int len = (ovector[i+1] > ovector[i])? (ovector[i+1] - ovector[i]) : 0;
   memcpy(p, subject + ovector[i], IN_UCHARS(len));
   *stringlist++ = p;
   p += len;
@@ -619,7 +626,7 @@ pcre32_get_named_substring(const pcre32 *code, PCRE_SPTR32 subject,
   PCRE_SPTR32 *stringptr)
 #endif
 {
-int n = get_first_set(code, stringname, ovector);
+int n = get_first_set(code, stringname, ovector, stringcount);
 if (n <= 0) return n;
 #if defined COMPILE_PCRE8
 return pcre_get_substring(subject, ovector, stringcount, n, stringptr);
diff --git a/src/3rdparty/pcre/pcre_internal.h b/src/3rdparty/pcre/pcre_internal.h
index 544d9c07097acd14fd878cb67758b2354268ad0c..f7a5ee7aa6f3b543851eee09bf5a7c7df2a6408e 100644
--- a/src/3rdparty/pcre/pcre_internal.h
+++ b/src/3rdparty/pcre/pcre_internal.h
@@ -2454,7 +2454,7 @@ typedef struct compile_data {
   BOOL had_pruneorskip;             /* (*PRUNE) or (*SKIP) encountered */
   BOOL check_lookbehind;            /* Lookbehinds need later checking */
   BOOL dupnames;                    /* Duplicate names exist */
-  BOOL dupgroups;                   /* Duplicate groups exist: (?| found */ 
+  BOOL dupgroups;                   /* Duplicate groups exist: (?| found */
   BOOL iscondassert;                /* Next assert is a condition */
   int  nltype;                      /* Newline type */
   int  nllen;                       /* Newline string length */
diff --git a/src/3rdparty/pcre/pcre_jit_compile.c b/src/3rdparty/pcre/pcre_jit_compile.c
index 868d1d91bfe1afe33e0eada8c5022fb16c342dfb..445de0cbefebcbd8cc8e898029c6296d0fe569e4 100644
--- a/src/3rdparty/pcre/pcre_jit_compile.c
+++ b/src/3rdparty/pcre/pcre_jit_compile.c
@@ -4342,8 +4342,10 @@ switch(length)
   case 4:
   if ((ranges[1] - ranges[0]) == (ranges[3] - ranges[2])
       && (ranges[0] | (ranges[2] - ranges[0])) == ranges[2]
+      && (ranges[1] & (ranges[2] - ranges[0])) == 0
       && is_powerof2(ranges[2] - ranges[0]))
     {
+    SLJIT_ASSERT((ranges[0] & (ranges[2] - ranges[0])) == 0 && (ranges[2] & ranges[3] & (ranges[2] - ranges[0])) != 0);
     OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[0]);
     if (ranges[2] + 1 != ranges[3])
       {
@@ -4931,9 +4933,10 @@ else if ((cc[-1] & XCL_MAP) != 0)
   if (!check_class_ranges(common, (const pcre_uint8 *)cc, FALSE, TRUE, list))
     {
 #ifdef COMPILE_PCRE8
-    SLJIT_ASSERT(common->utf);
+    jump = NULL;
+    if (common->utf)
 #endif
-    jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);
+      jump = CMP(SLJIT_GREATER, TMP1, 0, SLJIT_IMM, 255);
 
     OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7);
     OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3);
@@ -4942,7 +4945,10 @@ else if ((cc[-1] & XCL_MAP) != 0)
     OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0);
     add_jump(compiler, list, JUMP(SLJIT_NOT_ZERO));
 
-    JUMPHERE(jump);
+#ifdef COMPILE_PCRE8
+    if (common->utf)
+#endif
+      JUMPHERE(jump);
     }
 
   OP1(SLJIT_MOV, TMP1, 0, TMP3, 0);
@@ -5250,7 +5256,7 @@ while (*cc != XCL_END)
       OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_LESS_EQUAL);
 
       SET_CHAR_OFFSET(0);
-      OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xff);
+      OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x7f);
       OP_FLAGS(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_LESS_EQUAL);
 
       SET_TYPE_OFFSET(ucp_Pc);
@@ -8477,8 +8483,7 @@ while (cc < ccend)
       OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), STR_PTR, 0);
       }
     BACKTRACK_AS(braminzero_backtrack)->matchingpath = LABEL();
-    if (cc[1] > OP_ASSERTBACK_NOT)
-      count_match(common);
+    count_match(common);
     break;
 
     case OP_ONCE:
@@ -9660,7 +9665,7 @@ static SLJIT_INLINE void compile_recurse(compiler_common *common)
 DEFINE_COMPILER;
 pcre_uchar *cc = common->start + common->currententry->start;
 pcre_uchar *ccbegin = cc + 1 + LINK_SIZE + (*cc == OP_BRA ? 0 : IMM2_SIZE);
-pcre_uchar *ccend = bracketend(cc);
+pcre_uchar *ccend = bracketend(cc) - (1 + LINK_SIZE);
 BOOL needs_control_head;
 int framesize = get_framesize(common, cc, NULL, TRUE, &needs_control_head);
 int private_data_size = get_private_data_copy_length(common, ccbegin, ccend, needs_control_head);
diff --git a/src/3rdparty/pcre/pcre_study.c b/src/3rdparty/pcre/pcre_study.c
index 932e9a7c4c63a9483601055a6abe42c4f43757ed..7fd0ba0b3d806481dc8f03cfcbbdeb144287bb6d 100644
--- a/src/3rdparty/pcre/pcre_study.c
+++ b/src/3rdparty/pcre/pcre_study.c
@@ -71,7 +71,7 @@ Arguments:
   startcode       pointer to start of the whole pattern's code
   options         the compiling options
   recurses        chain of recurse_check to catch mutual recursion
-  countptr        pointer to call count (to catch over complexity) 
+  countptr        pointer to call count (to catch over complexity)
 
 Returns:   the minimum length
            -1 if \C in UTF-8 mode or (*ACCEPT) was encountered
diff --git a/src/3rdparty/pcre/pcre_xclass.c b/src/3rdparty/pcre/pcre_xclass.c
index c2b61f0f920f1b54181e5a7017c957ebf6384beb..ef759a589a621de89aeef30a09c10b94452bbac1 100644
--- a/src/3rdparty/pcre/pcre_xclass.c
+++ b/src/3rdparty/pcre/pcre_xclass.c
@@ -246,7 +246,7 @@ while ((t = *data++) != XCL_END)
 
       case PT_PXPUNCT:
       if ((PRIV(ucp_gentype)[prop->chartype] == ucp_P ||
-            (c < 256 && PRIV(ucp_gentype)[prop->chartype] == ucp_S)) == isprop)
+            (c < 128 && PRIV(ucp_gentype)[prop->chartype] == ucp_S)) == isprop)
         return !negated;
       break;
 
diff --git a/src/3rdparty/pcre/sljit/sljitLir.h b/src/3rdparty/pcre/sljit/sljitLir.h
index f0969dac2e4dc8b419cfc4720f01e462d2aef6c0..2e2e9ac09cd660883f7c362b2260c7730a6060ca 100644
--- a/src/3rdparty/pcre/sljit/sljitLir.h
+++ b/src/3rdparty/pcre/sljit/sljitLir.h
@@ -869,34 +869,6 @@ SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_emit_op2(struct sljit_compiler *compiler
 	sljit_si src1, sljit_sw src1w,
 	sljit_si src2, sljit_sw src2w);
 
-/* The following function is a helper function for sljit_emit_op_custom.
-   It returns with the real machine register index ( >=0 ) of any SLJIT_R,
-   SLJIT_S and SLJIT_SP registers.
-
-   Note: it returns with -1 for virtual registers (only on x86-32). */
-
-SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_get_register_index(sljit_si reg);
-
-/* The following function is a helper function for sljit_emit_op_custom.
-   It returns with the real machine register index of any SLJIT_FLOAT register.
-
-   Note: the index is always an even number on ARM (except ARM-64), MIPS, and SPARC. */
-
-SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_get_float_register_index(sljit_si reg);
-
-/* Any instruction can be inserted into the instruction stream by
-   sljit_emit_op_custom. It has a similar purpose as inline assembly.
-   The size parameter must match to the instruction size of the target
-   architecture:
-
-         x86: 0 < size <= 15. The instruction argument can be byte aligned.
-      Thumb2: if size == 2, the instruction argument must be 2 byte aligned.
-              if size == 4, the instruction argument must be 4 byte aligned.
-   Otherwise: size must be 4 and instruction argument must be 4 byte aligned. */
-
-SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_emit_op_custom(struct sljit_compiler *compiler,
-	void *instruction, sljit_si size);
-
 /* Returns with non-zero if fpu is available. */
 
 SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_is_fpu_available(void);
@@ -1214,4 +1186,64 @@ SLJIT_API_FUNC_ATTRIBUTE void sljit_set_function_context(void** func_ptr, struct
 
 #endif /* !(defined SLJIT_INDIRECT_CALL && SLJIT_INDIRECT_CALL) */
 
+/* --------------------------------------------------------------------- */
+/*  CPU specific functions                                               */
+/* --------------------------------------------------------------------- */
+
+/* The following function is a helper function for sljit_emit_op_custom.
+   It returns with the real machine register index ( >=0 ) of any SLJIT_R,
+   SLJIT_S and SLJIT_SP registers.
+
+   Note: it returns with -1 for virtual registers (only on x86-32). */
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_get_register_index(sljit_si reg);
+
+/* The following function is a helper function for sljit_emit_op_custom.
+   It returns with the real machine register index of any SLJIT_FLOAT register.
+
+   Note: the index is always an even number on ARM (except ARM-64), MIPS, and SPARC. */
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_get_float_register_index(sljit_si reg);
+
+/* Any instruction can be inserted into the instruction stream by
+   sljit_emit_op_custom. It has a similar purpose as inline assembly.
+   The size parameter must match to the instruction size of the target
+   architecture:
+
+         x86: 0 < size <= 15. The instruction argument can be byte aligned.
+      Thumb2: if size == 2, the instruction argument must be 2 byte aligned.
+              if size == 4, the instruction argument must be 4 byte aligned.
+   Otherwise: size must be 4 and instruction argument must be 4 byte aligned. */
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_emit_op_custom(struct sljit_compiler *compiler,
+	void *instruction, sljit_si size);
+
+#if (defined SLJIT_CONFIG_X86 && SLJIT_CONFIG_X86)
+
+/* Returns with non-zero if sse2 is available. */
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_x86_is_sse2_available(void);
+
+/* Returns with non-zero if cmov instruction is available. */
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_x86_is_cmov_available(void);
+
+/* Emit a conditional mov instruction on x86 CPUs. This instruction
+   moves src to destination, if the condition is satisfied. Unlike
+   other arithmetic instructions, destination must be a register.
+   Before such instructions are emitted, cmov support should be
+   checked by sljit_x86_is_cmov_available function.
+    type must be between SLJIT_EQUAL and SLJIT_S_ORDERED
+    dst_reg must be a valid register and it can be combined
+      with SLJIT_INT_OP to perform 32 bit arithmetic
+   Flags: I - (never set any flags)
+ */
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_x86_emit_cmov(struct sljit_compiler *compiler,
+	sljit_si type,
+	sljit_si dst_reg,
+	sljit_si src, sljit_sw srcw);
+
+#endif
+
 #endif /* _SLJIT_LIR_H_ */
diff --git a/src/3rdparty/pcre/sljit/sljitNativeX86_common.c b/src/3rdparty/pcre/sljit/sljitNativeX86_common.c
index e148c34cd10df762ed69c4a55003d8418c0d841f..416c15afafa6a6180a1fc51296c3208d9fcb477b 100644
--- a/src/3rdparty/pcre/sljit/sljitNativeX86_common.c
+++ b/src/3rdparty/pcre/sljit/sljitNativeX86_common.c
@@ -2936,3 +2936,69 @@ SLJIT_API_FUNC_ATTRIBUTE void sljit_set_const(sljit_uw addr, sljit_sw new_consta
 {
 	*(sljit_sw*)addr = new_constant;
 }
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_x86_is_sse2_available(void)
+{
+#if (defined SLJIT_DETECT_SSE2 && SLJIT_DETECT_SSE2)
+	if (cpu_has_sse2 == -1)
+		get_cpu_features();
+	return cpu_has_sse2;
+#else
+	return 1;
+#endif
+}
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_x86_is_cmov_available(void)
+{
+	if (cpu_has_cmov == -1)
+		get_cpu_features();
+	return cpu_has_cmov;
+}
+
+SLJIT_API_FUNC_ATTRIBUTE sljit_si sljit_x86_emit_cmov(struct sljit_compiler *compiler,
+	sljit_si type,
+	sljit_si dst_reg,
+	sljit_si src, sljit_sw srcw)
+{
+	sljit_ub* inst;
+
+	CHECK_ERROR();
+#if (defined SLJIT_ARGUMENT_CHECKS && SLJIT_ARGUMENT_CHECKS)
+	CHECK_ARGUMENT(sljit_x86_is_cmov_available());
+	CHECK_ARGUMENT(!(type & ~(0xff | SLJIT_INT_OP)));
+	CHECK_ARGUMENT((type & 0xff) >= SLJIT_EQUAL && (type & 0xff) <= SLJIT_D_ORDERED);
+	CHECK_ARGUMENT(FUNCTION_CHECK_IS_REG(dst_reg & ~SLJIT_INT_OP));
+	FUNCTION_CHECK_SRC(src, srcw);
+#endif
+#if (defined SLJIT_VERBOSE && SLJIT_VERBOSE)
+	if (SLJIT_UNLIKELY(!!compiler->verbose)) {
+		fprintf(compiler->verbose, "  x86_cmov%s %s%s, ",
+			!(dst_reg & SLJIT_INT_OP) ? "" : ".i",
+			JUMP_PREFIX(type), jump_names[type & 0xff]);
+		sljit_verbose_reg(compiler, dst_reg & ~SLJIT_INT_OP);
+		fprintf(compiler->verbose, ", ");
+		sljit_verbose_param(compiler, src, srcw);
+		fprintf(compiler->verbose, "\n");
+	}
+#endif
+
+	ADJUST_LOCAL_OFFSET(src, srcw);
+	CHECK_EXTRA_REGS(src, srcw, (void)0);
+
+#if (defined SLJIT_CONFIG_X86_64 && SLJIT_CONFIG_X86_64)
+	compiler->mode32 = dst_reg & SLJIT_INT_OP;
+#endif
+	dst_reg &= ~SLJIT_INT_OP;
+
+	if (SLJIT_UNLIKELY(src & SLJIT_IMM)) {
+		EMIT_MOV(compiler, TMP_REG1, 0, SLJIT_IMM, srcw);
+		src = TMP_REG1;
+		srcw = 0;
+	}
+
+	inst = emit_x86_instruction(compiler, 2, dst_reg, 0, src, srcw);
+	FAIL_IF(!inst);
+	*inst++ = GROUP_0F;
+	*inst = get_jump_code(type & 0xff) - 0x40;
+	return SLJIT_SUCCESS;
+}
diff --git a/src/3rdparty/xcb/README b/src/3rdparty/xcb/README
index 4de7a17409d5c670050a9c6c3f5b3a6fdf0798ce..d7c8eba294d617c036334c919c1e3e69de66a823 100644
--- a/src/3rdparty/xcb/README
+++ b/src/3rdparty/xcb/README
@@ -1,6 +1,6 @@
 Contains the header and sources files from selected xcb libraries:
 
-   libxcb-1.5 together with xcb-proto-1.6 (sync, xfixes, randr sources)
+   libxcb-1.5 together with xcb-proto-1.6 (sync, xfixes, randr, xinerama sources)
    # libxkbcommon-x11 requires libxcb-xkb >= 1.10
    libxcb-1.10 together with xcb-proto-1.10 (xkb sources)
    libxcb-util-image-0.3.9
diff --git a/src/3rdparty/xcb/include/xcb/xinerama.h b/src/3rdparty/xcb/include/xcb/xinerama.h
new file mode 100644
index 0000000000000000000000000000000000000000..74da5458d2acff8cda9f15e045958519be123185
--- /dev/null
+++ b/src/3rdparty/xcb/include/xcb/xinerama.h
@@ -0,0 +1,808 @@
+/*
+ * This file generated automatically from xinerama.xml by c_client.py.
+ * Edit at your peril.
+ */
+
+/**
+ * @defgroup XCB_Xinerama_API XCB Xinerama API
+ * @brief Xinerama XCB Protocol Implementation.
+ * @{
+ **/
+
+#ifndef __XINERAMA_H
+#define __XINERAMA_H
+
+#include "xcb.h"
+#include "xproto.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define XCB_XINERAMA_MAJOR_VERSION 1
+#define XCB_XINERAMA_MINOR_VERSION 1
+
+extern xcb_extension_t xcb_xinerama_id;
+
+/**
+ * @brief xcb_xinerama_screen_info_t
+ **/
+typedef struct xcb_xinerama_screen_info_t {
+    int16_t  x_org; /**<  */
+    int16_t  y_org; /**<  */
+    uint16_t width; /**<  */
+    uint16_t height; /**<  */
+} xcb_xinerama_screen_info_t;
+
+/**
+ * @brief xcb_xinerama_screen_info_iterator_t
+ **/
+typedef struct xcb_xinerama_screen_info_iterator_t {
+    xcb_xinerama_screen_info_t *data; /**<  */
+    int                         rem; /**<  */
+    int                         index; /**<  */
+} xcb_xinerama_screen_info_iterator_t;
+
+/**
+ * @brief xcb_xinerama_query_version_cookie_t
+ **/
+typedef struct xcb_xinerama_query_version_cookie_t {
+    unsigned int sequence; /**<  */
+} xcb_xinerama_query_version_cookie_t;
+
+/** Opcode for xcb_xinerama_query_version. */
+#define XCB_XINERAMA_QUERY_VERSION 0
+
+/**
+ * @brief xcb_xinerama_query_version_request_t
+ **/
+typedef struct xcb_xinerama_query_version_request_t {
+    uint8_t  major_opcode; /**<  */
+    uint8_t  minor_opcode; /**<  */
+    uint16_t length; /**<  */
+    uint8_t  major; /**<  */
+    uint8_t  minor; /**<  */
+} xcb_xinerama_query_version_request_t;
+
+/**
+ * @brief xcb_xinerama_query_version_reply_t
+ **/
+typedef struct xcb_xinerama_query_version_reply_t {
+    uint8_t  response_type; /**<  */
+    uint8_t  pad0; /**<  */
+    uint16_t sequence; /**<  */
+    uint32_t length; /**<  */
+    uint16_t major; /**<  */
+    uint16_t minor; /**<  */
+} xcb_xinerama_query_version_reply_t;
+
+/**
+ * @brief xcb_xinerama_get_state_cookie_t
+ **/
+typedef struct xcb_xinerama_get_state_cookie_t {
+    unsigned int sequence; /**<  */
+} xcb_xinerama_get_state_cookie_t;
+
+/** Opcode for xcb_xinerama_get_state. */
+#define XCB_XINERAMA_GET_STATE 1
+
+/**
+ * @brief xcb_xinerama_get_state_request_t
+ **/
+typedef struct xcb_xinerama_get_state_request_t {
+    uint8_t      major_opcode; /**<  */
+    uint8_t      minor_opcode; /**<  */
+    uint16_t     length; /**<  */
+    xcb_window_t window; /**<  */
+} xcb_xinerama_get_state_request_t;
+
+/**
+ * @brief xcb_xinerama_get_state_reply_t
+ **/
+typedef struct xcb_xinerama_get_state_reply_t {
+    uint8_t      response_type; /**<  */
+    uint8_t      state; /**<  */
+    uint16_t     sequence; /**<  */
+    uint32_t     length; /**<  */
+    xcb_window_t window; /**<  */
+} xcb_xinerama_get_state_reply_t;
+
+/**
+ * @brief xcb_xinerama_get_screen_count_cookie_t
+ **/
+typedef struct xcb_xinerama_get_screen_count_cookie_t {
+    unsigned int sequence; /**<  */
+} xcb_xinerama_get_screen_count_cookie_t;
+
+/** Opcode for xcb_xinerama_get_screen_count. */
+#define XCB_XINERAMA_GET_SCREEN_COUNT 2
+
+/**
+ * @brief xcb_xinerama_get_screen_count_request_t
+ **/
+typedef struct xcb_xinerama_get_screen_count_request_t {
+    uint8_t      major_opcode; /**<  */
+    uint8_t      minor_opcode; /**<  */
+    uint16_t     length; /**<  */
+    xcb_window_t window; /**<  */
+} xcb_xinerama_get_screen_count_request_t;
+
+/**
+ * @brief xcb_xinerama_get_screen_count_reply_t
+ **/
+typedef struct xcb_xinerama_get_screen_count_reply_t {
+    uint8_t      response_type; /**<  */
+    uint8_t      screen_count; /**<  */
+    uint16_t     sequence; /**<  */
+    uint32_t     length; /**<  */
+    xcb_window_t window; /**<  */
+} xcb_xinerama_get_screen_count_reply_t;
+
+/**
+ * @brief xcb_xinerama_get_screen_size_cookie_t
+ **/
+typedef struct xcb_xinerama_get_screen_size_cookie_t {
+    unsigned int sequence; /**<  */
+} xcb_xinerama_get_screen_size_cookie_t;
+
+/** Opcode for xcb_xinerama_get_screen_size. */
+#define XCB_XINERAMA_GET_SCREEN_SIZE 3
+
+/**
+ * @brief xcb_xinerama_get_screen_size_request_t
+ **/
+typedef struct xcb_xinerama_get_screen_size_request_t {
+    uint8_t      major_opcode; /**<  */
+    uint8_t      minor_opcode; /**<  */
+    uint16_t     length; /**<  */
+    xcb_window_t window; /**<  */
+    uint32_t     screen; /**<  */
+} xcb_xinerama_get_screen_size_request_t;
+
+/**
+ * @brief xcb_xinerama_get_screen_size_reply_t
+ **/
+typedef struct xcb_xinerama_get_screen_size_reply_t {
+    uint8_t      response_type; /**<  */
+    uint8_t      pad0; /**<  */
+    uint16_t     sequence; /**<  */
+    uint32_t     length; /**<  */
+    uint32_t     width; /**<  */
+    uint32_t     height; /**<  */
+    xcb_window_t window; /**<  */
+    uint32_t     screen; /**<  */
+} xcb_xinerama_get_screen_size_reply_t;
+
+/**
+ * @brief xcb_xinerama_is_active_cookie_t
+ **/
+typedef struct xcb_xinerama_is_active_cookie_t {
+    unsigned int sequence; /**<  */
+} xcb_xinerama_is_active_cookie_t;
+
+/** Opcode for xcb_xinerama_is_active. */
+#define XCB_XINERAMA_IS_ACTIVE 4
+
+/**
+ * @brief xcb_xinerama_is_active_request_t
+ **/
+typedef struct xcb_xinerama_is_active_request_t {
+    uint8_t  major_opcode; /**<  */
+    uint8_t  minor_opcode; /**<  */
+    uint16_t length; /**<  */
+} xcb_xinerama_is_active_request_t;
+
+/**
+ * @brief xcb_xinerama_is_active_reply_t
+ **/
+typedef struct xcb_xinerama_is_active_reply_t {
+    uint8_t  response_type; /**<  */
+    uint8_t  pad0; /**<  */
+    uint16_t sequence; /**<  */
+    uint32_t length; /**<  */
+    uint32_t state; /**<  */
+} xcb_xinerama_is_active_reply_t;
+
+/**
+ * @brief xcb_xinerama_query_screens_cookie_t
+ **/
+typedef struct xcb_xinerama_query_screens_cookie_t {
+    unsigned int sequence; /**<  */
+} xcb_xinerama_query_screens_cookie_t;
+
+/** Opcode for xcb_xinerama_query_screens. */
+#define XCB_XINERAMA_QUERY_SCREENS 5
+
+/**
+ * @brief xcb_xinerama_query_screens_request_t
+ **/
+typedef struct xcb_xinerama_query_screens_request_t {
+    uint8_t  major_opcode; /**<  */
+    uint8_t  minor_opcode; /**<  */
+    uint16_t length; /**<  */
+} xcb_xinerama_query_screens_request_t;
+
+/**
+ * @brief xcb_xinerama_query_screens_reply_t
+ **/
+typedef struct xcb_xinerama_query_screens_reply_t {
+    uint8_t  response_type; /**<  */
+    uint8_t  pad0; /**<  */
+    uint16_t sequence; /**<  */
+    uint32_t length; /**<  */
+    uint32_t number; /**<  */
+    uint8_t  pad1[20]; /**<  */
+} xcb_xinerama_query_screens_reply_t;
+
+/**
+ * Get the next element of the iterator
+ * @param i Pointer to a xcb_xinerama_screen_info_iterator_t
+ *
+ * Get the next element in the iterator. The member rem is
+ * decreased by one. The member data points to the next
+ * element. The member index is increased by sizeof(xcb_xinerama_screen_info_t)
+ */
+
+/*****************************************************************************
+ **
+ ** void xcb_xinerama_screen_info_next
+ **
+ ** @param xcb_xinerama_screen_info_iterator_t *i
+ ** @returns void
+ **
+ *****************************************************************************/
+
+void
+xcb_xinerama_screen_info_next (xcb_xinerama_screen_info_iterator_t *i  /**< */);
+
+/**
+ * Return the iterator pointing to the last element
+ * @param i An xcb_xinerama_screen_info_iterator_t
+ * @return  The iterator pointing to the last element
+ *
+ * Set the current element in the iterator to the last element.
+ * The member rem is set to 0. The member data points to the
+ * last element.
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_generic_iterator_t xcb_xinerama_screen_info_end
+ **
+ ** @param xcb_xinerama_screen_info_iterator_t i
+ ** @returns xcb_generic_iterator_t
+ **
+ *****************************************************************************/
+
+xcb_generic_iterator_t
+xcb_xinerama_screen_info_end (xcb_xinerama_screen_info_iterator_t i  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_version_cookie_t xcb_xinerama_query_version
+ **
+ ** @param xcb_connection_t *c
+ ** @param uint8_t           major
+ ** @param uint8_t           minor
+ ** @returns xcb_xinerama_query_version_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_version_cookie_t
+xcb_xinerama_query_version (xcb_connection_t *c  /**< */,
+                            uint8_t           major  /**< */,
+                            uint8_t           minor  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ * This form can be used only if the request will cause
+ * a reply to be generated. Any returned error will be
+ * placed in the event queue.
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_version_cookie_t xcb_xinerama_query_version_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @param uint8_t           major
+ ** @param uint8_t           minor
+ ** @returns xcb_xinerama_query_version_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_version_cookie_t
+xcb_xinerama_query_version_unchecked (xcb_connection_t *c  /**< */,
+                                      uint8_t           major  /**< */,
+                                      uint8_t           minor  /**< */);
+
+/**
+ * Return the reply
+ * @param c      The connection
+ * @param cookie The cookie
+ * @param e      The xcb_generic_error_t supplied
+ *
+ * Returns the reply of the request asked by
+ *
+ * The parameter @p e supplied to this function must be NULL if
+ * xcb_xinerama_query_version_unchecked(). is used.
+ * Otherwise, it stores the error if any.
+ *
+ * The returned value must be freed by the caller using free().
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_version_reply_t * xcb_xinerama_query_version_reply
+ **
+ ** @param xcb_connection_t                     *c
+ ** @param xcb_xinerama_query_version_cookie_t   cookie
+ ** @param xcb_generic_error_t                 **e
+ ** @returns xcb_xinerama_query_version_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_version_reply_t *
+xcb_xinerama_query_version_reply (xcb_connection_t                     *c  /**< */,
+                                  xcb_xinerama_query_version_cookie_t   cookie  /**< */,
+                                  xcb_generic_error_t                 **e  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_state_cookie_t xcb_xinerama_get_state
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @returns xcb_xinerama_get_state_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_state_cookie_t
+xcb_xinerama_get_state (xcb_connection_t *c  /**< */,
+                        xcb_window_t      window  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ * This form can be used only if the request will cause
+ * a reply to be generated. Any returned error will be
+ * placed in the event queue.
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_state_cookie_t xcb_xinerama_get_state_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @returns xcb_xinerama_get_state_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_state_cookie_t
+xcb_xinerama_get_state_unchecked (xcb_connection_t *c  /**< */,
+                                  xcb_window_t      window  /**< */);
+
+/**
+ * Return the reply
+ * @param c      The connection
+ * @param cookie The cookie
+ * @param e      The xcb_generic_error_t supplied
+ *
+ * Returns the reply of the request asked by
+ *
+ * The parameter @p e supplied to this function must be NULL if
+ * xcb_xinerama_get_state_unchecked(). is used.
+ * Otherwise, it stores the error if any.
+ *
+ * The returned value must be freed by the caller using free().
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_state_reply_t * xcb_xinerama_get_state_reply
+ **
+ ** @param xcb_connection_t                 *c
+ ** @param xcb_xinerama_get_state_cookie_t   cookie
+ ** @param xcb_generic_error_t             **e
+ ** @returns xcb_xinerama_get_state_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_state_reply_t *
+xcb_xinerama_get_state_reply (xcb_connection_t                 *c  /**< */,
+                              xcb_xinerama_get_state_cookie_t   cookie  /**< */,
+                              xcb_generic_error_t             **e  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_count_cookie_t xcb_xinerama_get_screen_count
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @returns xcb_xinerama_get_screen_count_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_count_cookie_t
+xcb_xinerama_get_screen_count (xcb_connection_t *c  /**< */,
+                               xcb_window_t      window  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ * This form can be used only if the request will cause
+ * a reply to be generated. Any returned error will be
+ * placed in the event queue.
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_count_cookie_t xcb_xinerama_get_screen_count_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @returns xcb_xinerama_get_screen_count_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_count_cookie_t
+xcb_xinerama_get_screen_count_unchecked (xcb_connection_t *c  /**< */,
+                                         xcb_window_t      window  /**< */);
+
+/**
+ * Return the reply
+ * @param c      The connection
+ * @param cookie The cookie
+ * @param e      The xcb_generic_error_t supplied
+ *
+ * Returns the reply of the request asked by
+ *
+ * The parameter @p e supplied to this function must be NULL if
+ * xcb_xinerama_get_screen_count_unchecked(). is used.
+ * Otherwise, it stores the error if any.
+ *
+ * The returned value must be freed by the caller using free().
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_count_reply_t * xcb_xinerama_get_screen_count_reply
+ **
+ ** @param xcb_connection_t                        *c
+ ** @param xcb_xinerama_get_screen_count_cookie_t   cookie
+ ** @param xcb_generic_error_t                    **e
+ ** @returns xcb_xinerama_get_screen_count_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_count_reply_t *
+xcb_xinerama_get_screen_count_reply (xcb_connection_t                        *c  /**< */,
+                                     xcb_xinerama_get_screen_count_cookie_t   cookie  /**< */,
+                                     xcb_generic_error_t                    **e  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_size_cookie_t xcb_xinerama_get_screen_size
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @param uint32_t          screen
+ ** @returns xcb_xinerama_get_screen_size_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_size_cookie_t
+xcb_xinerama_get_screen_size (xcb_connection_t *c  /**< */,
+                              xcb_window_t      window  /**< */,
+                              uint32_t          screen  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ * This form can be used only if the request will cause
+ * a reply to be generated. Any returned error will be
+ * placed in the event queue.
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_size_cookie_t xcb_xinerama_get_screen_size_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @param uint32_t          screen
+ ** @returns xcb_xinerama_get_screen_size_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_size_cookie_t
+xcb_xinerama_get_screen_size_unchecked (xcb_connection_t *c  /**< */,
+                                        xcb_window_t      window  /**< */,
+                                        uint32_t          screen  /**< */);
+
+/**
+ * Return the reply
+ * @param c      The connection
+ * @param cookie The cookie
+ * @param e      The xcb_generic_error_t supplied
+ *
+ * Returns the reply of the request asked by
+ *
+ * The parameter @p e supplied to this function must be NULL if
+ * xcb_xinerama_get_screen_size_unchecked(). is used.
+ * Otherwise, it stores the error if any.
+ *
+ * The returned value must be freed by the caller using free().
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_size_reply_t * xcb_xinerama_get_screen_size_reply
+ **
+ ** @param xcb_connection_t                       *c
+ ** @param xcb_xinerama_get_screen_size_cookie_t   cookie
+ ** @param xcb_generic_error_t                   **e
+ ** @returns xcb_xinerama_get_screen_size_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_size_reply_t *
+xcb_xinerama_get_screen_size_reply (xcb_connection_t                       *c  /**< */,
+                                    xcb_xinerama_get_screen_size_cookie_t   cookie  /**< */,
+                                    xcb_generic_error_t                   **e  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_is_active_cookie_t xcb_xinerama_is_active
+ **
+ ** @param xcb_connection_t *c
+ ** @returns xcb_xinerama_is_active_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_is_active_cookie_t
+xcb_xinerama_is_active (xcb_connection_t *c  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ * This form can be used only if the request will cause
+ * a reply to be generated. Any returned error will be
+ * placed in the event queue.
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_is_active_cookie_t xcb_xinerama_is_active_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @returns xcb_xinerama_is_active_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_is_active_cookie_t
+xcb_xinerama_is_active_unchecked (xcb_connection_t *c  /**< */);
+
+/**
+ * Return the reply
+ * @param c      The connection
+ * @param cookie The cookie
+ * @param e      The xcb_generic_error_t supplied
+ *
+ * Returns the reply of the request asked by
+ *
+ * The parameter @p e supplied to this function must be NULL if
+ * xcb_xinerama_is_active_unchecked(). is used.
+ * Otherwise, it stores the error if any.
+ *
+ * The returned value must be freed by the caller using free().
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_is_active_reply_t * xcb_xinerama_is_active_reply
+ **
+ ** @param xcb_connection_t                 *c
+ ** @param xcb_xinerama_is_active_cookie_t   cookie
+ ** @param xcb_generic_error_t             **e
+ ** @returns xcb_xinerama_is_active_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_is_active_reply_t *
+xcb_xinerama_is_active_reply (xcb_connection_t                 *c  /**< */,
+                              xcb_xinerama_is_active_cookie_t   cookie  /**< */,
+                              xcb_generic_error_t             **e  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_screens_cookie_t xcb_xinerama_query_screens
+ **
+ ** @param xcb_connection_t *c
+ ** @returns xcb_xinerama_query_screens_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_screens_cookie_t
+xcb_xinerama_query_screens (xcb_connection_t *c  /**< */);
+
+/**
+ * Delivers a request to the X server
+ * @param c The connection
+ * @return A cookie
+ *
+ * Delivers a request to the X server.
+ *
+ * This form can be used only if the request will cause
+ * a reply to be generated. Any returned error will be
+ * placed in the event queue.
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_screens_cookie_t xcb_xinerama_query_screens_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @returns xcb_xinerama_query_screens_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_screens_cookie_t
+xcb_xinerama_query_screens_unchecked (xcb_connection_t *c  /**< */);
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_screen_info_t * xcb_xinerama_query_screens_screen_info
+ **
+ ** @param const xcb_xinerama_query_screens_reply_t *R
+ ** @returns xcb_xinerama_screen_info_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_screen_info_t *
+xcb_xinerama_query_screens_screen_info (const xcb_xinerama_query_screens_reply_t *R  /**< */);
+
+
+/*****************************************************************************
+ **
+ ** int xcb_xinerama_query_screens_screen_info_length
+ **
+ ** @param const xcb_xinerama_query_screens_reply_t *R
+ ** @returns int
+ **
+ *****************************************************************************/
+
+int
+xcb_xinerama_query_screens_screen_info_length (const xcb_xinerama_query_screens_reply_t *R  /**< */);
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_screen_info_iterator_t xcb_xinerama_query_screens_screen_info_iterator
+ **
+ ** @param const xcb_xinerama_query_screens_reply_t *R
+ ** @returns xcb_xinerama_screen_info_iterator_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_screen_info_iterator_t
+xcb_xinerama_query_screens_screen_info_iterator (const xcb_xinerama_query_screens_reply_t *R  /**< */);
+
+/**
+ * Return the reply
+ * @param c      The connection
+ * @param cookie The cookie
+ * @param e      The xcb_generic_error_t supplied
+ *
+ * Returns the reply of the request asked by
+ *
+ * The parameter @p e supplied to this function must be NULL if
+ * xcb_xinerama_query_screens_unchecked(). is used.
+ * Otherwise, it stores the error if any.
+ *
+ * The returned value must be freed by the caller using free().
+ */
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_screens_reply_t * xcb_xinerama_query_screens_reply
+ **
+ ** @param xcb_connection_t                     *c
+ ** @param xcb_xinerama_query_screens_cookie_t   cookie
+ ** @param xcb_generic_error_t                 **e
+ ** @returns xcb_xinerama_query_screens_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_screens_reply_t *
+xcb_xinerama_query_screens_reply (xcb_connection_t                     *c  /**< */,
+                                  xcb_xinerama_query_screens_cookie_t   cookie  /**< */,
+                                  xcb_generic_error_t                 **e  /**< */);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+/**
+ * @}
+ */
diff --git a/src/3rdparty/xcb/libxcb/xinerama.c b/src/3rdparty/xcb/libxcb/xinerama.c
new file mode 100644
index 0000000000000000000000000000000000000000..05b6b7370787bb05f4e567c060eb8e97ba6718d4
--- /dev/null
+++ b/src/3rdparty/xcb/libxcb/xinerama.c
@@ -0,0 +1,655 @@
+/*
+ * This file generated automatically from xinerama.xml by c_client.py.
+ * Edit at your peril.
+ */
+
+#include <string.h>
+#include <assert.h>
+#include "xcbext.h"
+#include "xinerama.h"
+#include "xproto.h"
+
+xcb_extension_t xcb_xinerama_id = { "XINERAMA", 0 };
+
+
+/*****************************************************************************
+ **
+ ** void xcb_xinerama_screen_info_next
+ **
+ ** @param xcb_xinerama_screen_info_iterator_t *i
+ ** @returns void
+ **
+ *****************************************************************************/
+
+void
+xcb_xinerama_screen_info_next (xcb_xinerama_screen_info_iterator_t *i  /**< */)
+{
+    --i->rem;
+    ++i->data;
+    i->index += sizeof(xcb_xinerama_screen_info_t);
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_generic_iterator_t xcb_xinerama_screen_info_end
+ **
+ ** @param xcb_xinerama_screen_info_iterator_t i
+ ** @returns xcb_generic_iterator_t
+ **
+ *****************************************************************************/
+
+xcb_generic_iterator_t
+xcb_xinerama_screen_info_end (xcb_xinerama_screen_info_iterator_t i  /**< */)
+{
+    xcb_generic_iterator_t ret;
+    ret.data = i.data + i.rem;
+    ret.index = i.index + ((char *) ret.data - (char *) i.data);
+    ret.rem = 0;
+    return ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_version_cookie_t xcb_xinerama_query_version
+ **
+ ** @param xcb_connection_t *c
+ ** @param uint8_t           major
+ ** @param uint8_t           minor
+ ** @returns xcb_xinerama_query_version_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_version_cookie_t
+xcb_xinerama_query_version (xcb_connection_t *c  /**< */,
+                            uint8_t           major  /**< */,
+                            uint8_t           minor  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_QUERY_VERSION,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_query_version_cookie_t xcb_ret;
+    xcb_xinerama_query_version_request_t xcb_out;
+
+    xcb_out.major = major;
+    xcb_out.minor = minor;
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, XCB_REQUEST_CHECKED, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_version_cookie_t xcb_xinerama_query_version_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @param uint8_t           major
+ ** @param uint8_t           minor
+ ** @returns xcb_xinerama_query_version_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_version_cookie_t
+xcb_xinerama_query_version_unchecked (xcb_connection_t *c  /**< */,
+                                      uint8_t           major  /**< */,
+                                      uint8_t           minor  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_QUERY_VERSION,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_query_version_cookie_t xcb_ret;
+    xcb_xinerama_query_version_request_t xcb_out;
+
+    xcb_out.major = major;
+    xcb_out.minor = minor;
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, 0, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_version_reply_t * xcb_xinerama_query_version_reply
+ **
+ ** @param xcb_connection_t                     *c
+ ** @param xcb_xinerama_query_version_cookie_t   cookie
+ ** @param xcb_generic_error_t                 **e
+ ** @returns xcb_xinerama_query_version_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_version_reply_t *
+xcb_xinerama_query_version_reply (xcb_connection_t                     *c  /**< */,
+                                  xcb_xinerama_query_version_cookie_t   cookie  /**< */,
+                                  xcb_generic_error_t                 **e  /**< */)
+{
+    return (xcb_xinerama_query_version_reply_t *) xcb_wait_for_reply(c, cookie.sequence, e);
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_state_cookie_t xcb_xinerama_get_state
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @returns xcb_xinerama_get_state_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_state_cookie_t
+xcb_xinerama_get_state (xcb_connection_t *c  /**< */,
+                        xcb_window_t      window  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_GET_STATE,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_get_state_cookie_t xcb_ret;
+    xcb_xinerama_get_state_request_t xcb_out;
+
+    xcb_out.window = window;
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, XCB_REQUEST_CHECKED, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_state_cookie_t xcb_xinerama_get_state_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @returns xcb_xinerama_get_state_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_state_cookie_t
+xcb_xinerama_get_state_unchecked (xcb_connection_t *c  /**< */,
+                                  xcb_window_t      window  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_GET_STATE,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_get_state_cookie_t xcb_ret;
+    xcb_xinerama_get_state_request_t xcb_out;
+
+    xcb_out.window = window;
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, 0, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_state_reply_t * xcb_xinerama_get_state_reply
+ **
+ ** @param xcb_connection_t                 *c
+ ** @param xcb_xinerama_get_state_cookie_t   cookie
+ ** @param xcb_generic_error_t             **e
+ ** @returns xcb_xinerama_get_state_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_state_reply_t *
+xcb_xinerama_get_state_reply (xcb_connection_t                 *c  /**< */,
+                              xcb_xinerama_get_state_cookie_t   cookie  /**< */,
+                              xcb_generic_error_t             **e  /**< */)
+{
+    return (xcb_xinerama_get_state_reply_t *) xcb_wait_for_reply(c, cookie.sequence, e);
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_count_cookie_t xcb_xinerama_get_screen_count
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @returns xcb_xinerama_get_screen_count_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_count_cookie_t
+xcb_xinerama_get_screen_count (xcb_connection_t *c  /**< */,
+                               xcb_window_t      window  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_GET_SCREEN_COUNT,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_get_screen_count_cookie_t xcb_ret;
+    xcb_xinerama_get_screen_count_request_t xcb_out;
+
+    xcb_out.window = window;
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, XCB_REQUEST_CHECKED, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_count_cookie_t xcb_xinerama_get_screen_count_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @returns xcb_xinerama_get_screen_count_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_count_cookie_t
+xcb_xinerama_get_screen_count_unchecked (xcb_connection_t *c  /**< */,
+                                         xcb_window_t      window  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_GET_SCREEN_COUNT,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_get_screen_count_cookie_t xcb_ret;
+    xcb_xinerama_get_screen_count_request_t xcb_out;
+
+    xcb_out.window = window;
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, 0, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_count_reply_t * xcb_xinerama_get_screen_count_reply
+ **
+ ** @param xcb_connection_t                        *c
+ ** @param xcb_xinerama_get_screen_count_cookie_t   cookie
+ ** @param xcb_generic_error_t                    **e
+ ** @returns xcb_xinerama_get_screen_count_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_count_reply_t *
+xcb_xinerama_get_screen_count_reply (xcb_connection_t                        *c  /**< */,
+                                     xcb_xinerama_get_screen_count_cookie_t   cookie  /**< */,
+                                     xcb_generic_error_t                    **e  /**< */)
+{
+    return (xcb_xinerama_get_screen_count_reply_t *) xcb_wait_for_reply(c, cookie.sequence, e);
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_size_cookie_t xcb_xinerama_get_screen_size
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @param uint32_t          screen
+ ** @returns xcb_xinerama_get_screen_size_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_size_cookie_t
+xcb_xinerama_get_screen_size (xcb_connection_t *c  /**< */,
+                              xcb_window_t      window  /**< */,
+                              uint32_t          screen  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_GET_SCREEN_SIZE,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_get_screen_size_cookie_t xcb_ret;
+    xcb_xinerama_get_screen_size_request_t xcb_out;
+
+    xcb_out.window = window;
+    xcb_out.screen = screen;
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, XCB_REQUEST_CHECKED, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_size_cookie_t xcb_xinerama_get_screen_size_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @param xcb_window_t      window
+ ** @param uint32_t          screen
+ ** @returns xcb_xinerama_get_screen_size_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_size_cookie_t
+xcb_xinerama_get_screen_size_unchecked (xcb_connection_t *c  /**< */,
+                                        xcb_window_t      window  /**< */,
+                                        uint32_t          screen  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_GET_SCREEN_SIZE,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_get_screen_size_cookie_t xcb_ret;
+    xcb_xinerama_get_screen_size_request_t xcb_out;
+
+    xcb_out.window = window;
+    xcb_out.screen = screen;
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, 0, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_get_screen_size_reply_t * xcb_xinerama_get_screen_size_reply
+ **
+ ** @param xcb_connection_t                       *c
+ ** @param xcb_xinerama_get_screen_size_cookie_t   cookie
+ ** @param xcb_generic_error_t                   **e
+ ** @returns xcb_xinerama_get_screen_size_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_get_screen_size_reply_t *
+xcb_xinerama_get_screen_size_reply (xcb_connection_t                       *c  /**< */,
+                                    xcb_xinerama_get_screen_size_cookie_t   cookie  /**< */,
+                                    xcb_generic_error_t                   **e  /**< */)
+{
+    return (xcb_xinerama_get_screen_size_reply_t *) xcb_wait_for_reply(c, cookie.sequence, e);
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_is_active_cookie_t xcb_xinerama_is_active
+ **
+ ** @param xcb_connection_t *c
+ ** @returns xcb_xinerama_is_active_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_is_active_cookie_t
+xcb_xinerama_is_active (xcb_connection_t *c  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_IS_ACTIVE,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_is_active_cookie_t xcb_ret;
+    xcb_xinerama_is_active_request_t xcb_out;
+
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, XCB_REQUEST_CHECKED, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_is_active_cookie_t xcb_xinerama_is_active_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @returns xcb_xinerama_is_active_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_is_active_cookie_t
+xcb_xinerama_is_active_unchecked (xcb_connection_t *c  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_IS_ACTIVE,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_is_active_cookie_t xcb_ret;
+    xcb_xinerama_is_active_request_t xcb_out;
+
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, 0, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_is_active_reply_t * xcb_xinerama_is_active_reply
+ **
+ ** @param xcb_connection_t                 *c
+ ** @param xcb_xinerama_is_active_cookie_t   cookie
+ ** @param xcb_generic_error_t             **e
+ ** @returns xcb_xinerama_is_active_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_is_active_reply_t *
+xcb_xinerama_is_active_reply (xcb_connection_t                 *c  /**< */,
+                              xcb_xinerama_is_active_cookie_t   cookie  /**< */,
+                              xcb_generic_error_t             **e  /**< */)
+{
+    return (xcb_xinerama_is_active_reply_t *) xcb_wait_for_reply(c, cookie.sequence, e);
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_screens_cookie_t xcb_xinerama_query_screens
+ **
+ ** @param xcb_connection_t *c
+ ** @returns xcb_xinerama_query_screens_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_screens_cookie_t
+xcb_xinerama_query_screens (xcb_connection_t *c  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_QUERY_SCREENS,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_query_screens_cookie_t xcb_ret;
+    xcb_xinerama_query_screens_request_t xcb_out;
+
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, XCB_REQUEST_CHECKED, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_screens_cookie_t xcb_xinerama_query_screens_unchecked
+ **
+ ** @param xcb_connection_t *c
+ ** @returns xcb_xinerama_query_screens_cookie_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_screens_cookie_t
+xcb_xinerama_query_screens_unchecked (xcb_connection_t *c  /**< */)
+{
+    static const xcb_protocol_request_t xcb_req = {
+        /* count */ 2,
+        /* ext */ &xcb_xinerama_id,
+        /* opcode */ XCB_XINERAMA_QUERY_SCREENS,
+        /* isvoid */ 0
+    };
+
+    struct iovec xcb_parts[4];
+    xcb_xinerama_query_screens_cookie_t xcb_ret;
+    xcb_xinerama_query_screens_request_t xcb_out;
+
+
+    xcb_parts[2].iov_base = (char *) &xcb_out;
+    xcb_parts[2].iov_len = sizeof(xcb_out);
+    xcb_parts[3].iov_base = 0;
+    xcb_parts[3].iov_len = -xcb_parts[2].iov_len & 3;
+    xcb_ret.sequence = xcb_send_request(c, 0, xcb_parts + 2, &xcb_req);
+    return xcb_ret;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_screen_info_t * xcb_xinerama_query_screens_screen_info
+ **
+ ** @param const xcb_xinerama_query_screens_reply_t *R
+ ** @returns xcb_xinerama_screen_info_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_screen_info_t *
+xcb_xinerama_query_screens_screen_info (const xcb_xinerama_query_screens_reply_t *R  /**< */)
+{
+    return (xcb_xinerama_screen_info_t *) (R + 1);
+}
+
+
+/*****************************************************************************
+ **
+ ** int xcb_xinerama_query_screens_screen_info_length
+ **
+ ** @param const xcb_xinerama_query_screens_reply_t *R
+ ** @returns int
+ **
+ *****************************************************************************/
+
+int
+xcb_xinerama_query_screens_screen_info_length (const xcb_xinerama_query_screens_reply_t *R  /**< */)
+{
+    return R->number;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_screen_info_iterator_t xcb_xinerama_query_screens_screen_info_iterator
+ **
+ ** @param const xcb_xinerama_query_screens_reply_t *R
+ ** @returns xcb_xinerama_screen_info_iterator_t
+ **
+ *****************************************************************************/
+
+xcb_xinerama_screen_info_iterator_t
+xcb_xinerama_query_screens_screen_info_iterator (const xcb_xinerama_query_screens_reply_t *R  /**< */)
+{
+    xcb_xinerama_screen_info_iterator_t i;
+    i.data = (xcb_xinerama_screen_info_t *) (R + 1);
+    i.rem = R->number;
+    i.index = (char *) i.data - (char *) R;
+    return i;
+}
+
+
+/*****************************************************************************
+ **
+ ** xcb_xinerama_query_screens_reply_t * xcb_xinerama_query_screens_reply
+ **
+ ** @param xcb_connection_t                     *c
+ ** @param xcb_xinerama_query_screens_cookie_t   cookie
+ ** @param xcb_generic_error_t                 **e
+ ** @returns xcb_xinerama_query_screens_reply_t *
+ **
+ *****************************************************************************/
+
+xcb_xinerama_query_screens_reply_t *
+xcb_xinerama_query_screens_reply (xcb_connection_t                     *c  /**< */,
+                                  xcb_xinerama_query_screens_cookie_t   cookie  /**< */,
+                                  xcb_generic_error_t                 **e  /**< */)
+{
+    return (xcb_xinerama_query_screens_reply_t *) xcb_wait_for_reply(c, cookie.sequence, e);
+}
+
diff --git a/src/3rdparty/zlib/zlib.h b/src/3rdparty/zlib/zlib.h
index 5229707f526be1c0989e7a361748ee64f89247f5..d0908ab6e9d6363b325ad8aaf4c1da1a03ae9b73 100644
--- a/src/3rdparty/zlib/zlib.h
+++ b/src/3rdparty/zlib/zlib.h
@@ -34,13 +34,8 @@
 #include "zconf.h"
 
 #include <qglobal.h>
-#if defined(QT_VISIBILITY_AVAILABLE)
-# undef ZEXTERN
-# define ZEXTERN __attribute__((visibility("default")))
-#else
-# undef ZEXTERN
-# define ZEXTERN Q_DECL_EXPORT
-#endif
+#undef ZEXTERN
+#define ZEXTERN Q_CORE_EXPORT
 
 #ifdef __cplusplus
 extern "C" {
diff --git a/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java b/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
index 4575d8a1d30c29587f17e59a486612725eefc477..dd5a7b4fec0a5169172244cd33cc55cdc6ad1bc6 100644
--- a/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
+++ b/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
@@ -919,6 +919,7 @@ public class QtActivityDelegate
     public void onDestroy()
     {
         if (m_quitApp) {
+            QtNative.terminateQt();
             if (m_debuggerProcess != null)
                 m_debuggerProcess.destroy();
             System.exit(0);// FIXME remove it or find a better way
diff --git a/src/android/jar/src/org/qtproject/qt5/android/QtNative.java b/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
index 8880c003e7d28933b8392a3fbcd1cf90b7ee7935..2349ea6db1003e25372ece17ee60f8f743ef56ef 100644
--- a/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
+++ b/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
@@ -294,7 +294,12 @@ public class QtNative
 
     private static void quitApp()
     {
-        m_activity.finish();
+        runAction(new Runnable() {
+            @Override
+            public void run() {
+                m_activity.finish();
+            }
+        });
     }
 
     //@ANDROID-9
diff --git a/src/angle/angle.pro b/src/angle/angle.pro
index c454fee8f9701172b9d659ebb9d5eb5f812b2a2a..8fae66dfb93ac8b0e868815e2e01e8a0bad65995 100644
--- a/src/angle/angle.pro
+++ b/src/angle/angle.pro
@@ -6,5 +6,6 @@ SUBDIRS += src
 #  2) If we made a 'QtANGLE' module, the include directory would be flattened which won't work since
 #     we need to support "#include <GLES2/gl2.h>"
 CONFIG += minimal_syncqt
-QMAKE_SYNCQT_OPTIONS = -module QtANGLE/KHR -module QtANGLE/EGL -module QtANGLE/GLES2 -module QtANGLE/GLES3 -version none
+MODULE_INCNAME = QtANGLE/KHR QtANGLE/EGL QtANGLE/GLES2 QtANGLE/GLES3
+VERSION = none
 load(qt_module_headers)
diff --git a/src/angle/src/config.pri b/src/angle/src/config.pri
index 085913ac83b1957e15ab00af5955edba11202536..fddb395ab25f796fad24cdab2b70478a089f872b 100644
--- a/src/angle/src/config.pri
+++ b/src/angle/src/config.pri
@@ -16,13 +16,14 @@ equals(QMAKE_HOST.os, Windows) {
     gnutools.value = $$absolute_path(../../../../gnuwin32/bin)
     exists($$gnutools.value/gperf.exe) {
         gnutools.name = PATH
-        gnutools.CONFIG = prepend
+        gnutools.CONFIG = always_prepend
     }
 }
 
 defineReplace(addGnuPath) {
     gnuPath = $$1
     !isEmpty(gnuPath):!isEmpty(gnutools.name) {
+        QT_TOOL_NAME = $$1
         qtAddToolEnv(gnuPath, gnutools)
         silent: gnuPath = @echo generating sources from ${QMAKE_FILE_IN} && $$gnuPath
     }
diff --git a/src/corelib/Qt5CoreConfigExtras.cmake.in b/src/corelib/Qt5CoreConfigExtras.cmake.in
index 65fd1f93838c1f7318cc97cb2a78192d9bddff27..91a4eb619a11241a7ac9e87c8f2bd1f2412d5d1d 100644
--- a/src/corelib/Qt5CoreConfigExtras.cmake.in
+++ b/src/corelib/Qt5CoreConfigExtras.cmake.in
@@ -70,7 +70,14 @@ set(_qt5_corelib_extra_includes)
 # Qt5_POSITION_INDEPENDENT_CODE variable is used in the # qt5_use_module
 # macro to add it.
 set(Qt5_POSITION_INDEPENDENT_CODE True)
-set(Qt5Core_EXECUTABLE_COMPILE_FLAGS \"-fPIC\")
+
+# On x86 and x86-64 systems with ELF binaries (especially Linux), due to
+# a new optimization in GCC 5.x in combination with a recent version of
+# GNU binutils, compiling Qt applications with -fPIE is no longer
+# enough.
+# Applications now need to be compiled with the -fPIC option if the Qt option
+# \"reduce relocations\" is active. For backward compatibility only, Qt accepts
+# the use of -fPIE for GCC 4.x versions.
 if (CMAKE_VERSION VERSION_LESS 2.8.12
         AND (NOT CMAKE_CXX_COMPILER_ID STREQUAL \"GNU\"
         OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0))
@@ -79,6 +86,20 @@ else()
     set_property(TARGET Qt5::Core APPEND PROPERTY INTERFACE_COMPILE_OPTIONS $$QMAKE_CXXFLAGS_APP)
 endif()
 
+# Applications using qmake or cmake >= 2.8.12 as their build system will
+# adapt automatically. Applications using an older release of cmake in
+# combination with GCC 5.x need to change their CMakeLists.txt to add
+# Qt5Core_EXECUTABLE_COMPILE_FLAGS to CMAKE_CXX_FLAGS. In particular,
+# applications using cmake >= 2.8.9 and < 2.8.11 will continue to build
+# with the -fPIE option and invoke the special compatibility mode if using
+# GCC 4.x.
+set(Qt5Core_EXECUTABLE_COMPILE_FLAGS \"\")
+if (CMAKE_VERSION VERSION_LESS 2.8.12
+        AND (CMAKE_CXX_COMPILER_ID STREQUAL \"GNU\"
+        AND NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0))
+    set(Qt5Core_EXECUTABLE_COMPILE_FLAGS \"-fPIC\")
+endif()
+
 !!IF !isEmpty(QT_NAMESPACE)
 list(APPEND Qt5Core_DEFINITIONS -DQT_NAMESPACE=$$QT_NAMESPACE)
 list(APPEND Qt5Core_COMPILE_DEFINITIONS QT_NAMESPACE=$$QT_NAMESPACE)
diff --git a/src/corelib/Qt5CoreMacros.cmake b/src/corelib/Qt5CoreMacros.cmake
index 18563764ad4160d84dedbffbeaebcf4ce059a903..9fab04fb26d19780ef941661db49f55d6f97518c 100644
--- a/src/corelib/Qt5CoreMacros.cmake
+++ b/src/corelib/Qt5CoreMacros.cmake
@@ -94,7 +94,7 @@ endmacro()
 
 
 # helper macro to set up a moc rule
-macro(QT5_CREATE_MOC_COMMAND infile outfile moc_flags moc_options moc_target)
+macro(QT5_CREATE_MOC_COMMAND infile outfile moc_flags moc_options moc_target moc_depends)
     # Pass the parameters in a file.  Set the working directory to
     # be that containing the parameters file and reference it by
     # just the file name.  This is necessary because the moc tool on
@@ -131,7 +131,7 @@ macro(QT5_CREATE_MOC_COMMAND infile outfile moc_flags moc_options moc_target)
     set(_moc_extra_parameters_file @${_moc_parameters_file})
     add_custom_command(OUTPUT ${outfile}
                        COMMAND ${Qt5Core_MOC_EXECUTABLE} ${_moc_extra_parameters_file}
-                       DEPENDS ${infile}
+                       DEPENDS ${infile} ${moc_depends}
                        ${_moc_working_dir}
                        VERBATIM)
 endmacro()
@@ -151,7 +151,7 @@ function(QT5_GENERATE_MOC infile outfile )
         endif()
         set(moc_target ${ARGV3})
     endif()
-    qt5_create_moc_command(${abs_infile} ${_outfile} "${moc_flags}" "" "${moc_target}")
+    qt5_create_moc_command(${abs_infile} ${_outfile} "${moc_flags}" "" "${moc_target}" "")
     set_source_files_properties(${outfile} PROPERTIES SKIP_AUTOMOC TRUE)  # dont run automoc on this file
 endfunction()
 
@@ -164,13 +164,14 @@ function(QT5_WRAP_CPP outfiles )
 
     set(options)
     set(oneValueArgs TARGET)
-    set(multiValueArgs OPTIONS)
+    set(multiValueArgs OPTIONS DEPENDS)
 
     cmake_parse_arguments(_WRAP_CPP "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
 
     set(moc_files ${_WRAP_CPP_UNPARSED_ARGUMENTS})
     set(moc_options ${_WRAP_CPP_OPTIONS})
     set(moc_target ${_WRAP_CPP_TARGET})
+    set(moc_depends ${_WRAP_CPP_DEPENDS})
 
     if (moc_target AND CMAKE_VERSION VERSION_LESS 2.8.12)
         message(FATAL_ERROR "The TARGET parameter to qt5_wrap_cpp is only available when using CMake 2.8.12 or later.")
@@ -178,7 +179,7 @@ function(QT5_WRAP_CPP outfiles )
     foreach(it ${moc_files})
         get_filename_component(it ${it} ABSOLUTE)
         qt5_make_output_file(${it} moc_ cpp outfile)
-        qt5_create_moc_command(${it} ${outfile} "${moc_flags}" "${moc_options}" "${moc_target}")
+        qt5_create_moc_command(${it} ${outfile} "${moc_flags}" "${moc_options}" "${moc_target}" "${moc_depends}")
         list(APPEND ${outfiles} ${outfile})
     endforeach()
     set(${outfiles} ${${outfiles}} PARENT_SCOPE)
@@ -335,7 +336,7 @@ if (NOT CMAKE_VERSION VERSION_LESS 2.8.9)
             set_property(TARGET ${_target} APPEND PROPERTY COMPILE_DEFINITIONS_MINSIZEREL QT_NO_DEBUG)
             if (Qt5_POSITION_INDEPENDENT_CODE
                     AND (CMAKE_VERSION VERSION_LESS 2.8.12
-                        AND (NOT CMAKE_CXX_COMPILER_ID STREQUAL \"GNU\"
+                        AND (NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU"
                         OR CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0)))
                 set_property(TARGET ${_target} PROPERTY POSITION_INDEPENDENT_CODE ${Qt5_POSITION_INDEPENDENT_CODE})
             endif()
diff --git a/src/corelib/global/qglobal.cpp b/src/corelib/global/qglobal.cpp
index 38ea7b07be4880b8832f11e34fead16c3bb1daf1..3bebdc6c40dbc4adcf71dbacb00f4dbaa1bb27b2 100644
--- a/src/corelib/global/qglobal.cpp
+++ b/src/corelib/global/qglobal.cpp
@@ -66,18 +66,8 @@
 #endif
 
 #ifdef Q_OS_WINRT
-#include <wrl.h>
-#include <windows.networking.h>
-#include <windows.networking.sockets.h>
-#include <windows.networking.connectivity.h>
-using namespace Microsoft::WRL;
-using namespace Microsoft::WRL::Wrappers;
-using namespace ABI::Windows::Foundation;
-using namespace ABI::Windows::Foundation::Collections;
-using namespace ABI::Windows::Networking;
-using namespace ABI::Windows::Networking::Connectivity;
-using namespace ABI::Windows::Networking::Sockets;
-#endif
+#include <Ws2tcpip.h>
+#endif // Q_OS_WINRT
 
 #if defined(Q_OS_VXWORKS) && defined(_WRS_KERNEL)
 #  include <envLib.h>
@@ -1882,8 +1872,6 @@ QT_BEGIN_INCLUDE_NAMESPACE
 #include "qt_windows.h"
 QT_END_INCLUDE_NAMESPACE
 
-#ifndef Q_OS_WINRT
-
 #  ifndef QT_BOOTSTRAPPED
 class QWindowsSockInit
 {
@@ -1914,8 +1902,6 @@ QWindowsSockInit::~QWindowsSockInit()
 Q_GLOBAL_STATIC(QWindowsSockInit, winsockInit)
 #  endif // QT_BOOTSTRAPPED
 
-#endif // !Q_OS_WINRT
-
 #ifdef Q_OS_WINRT
 static inline HMODULE moduleHandleForFunction(LPCVOID address)
 {
@@ -2809,42 +2795,6 @@ QString QSysInfo::machineHostName()
     struct utsname u;
     if (uname(&u) == 0)
         return QString::fromLocal8Bit(u.nodename);
-#elif defined(Q_OS_WINRT)
-    ComPtr<INetworkInformationStatics> statics;
-    GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Connectivity_NetworkInformation).Get(), &statics);
-
-    ComPtr<IVectorView<HostName *>> hostNames;
-    statics->GetHostNames(&hostNames);
-    if (!hostNames)
-        return QString();
-
-    unsigned int size;
-    hostNames->get_Size(&size);
-    if (size == 0)
-        return QString();
-
-    for (unsigned int i = 0; i < size; ++i) {
-        ComPtr<IHostName> hostName;
-        hostNames->GetAt(i, &hostName);
-        HostNameType type;
-        hostName->get_Type(&type);
-        if (type != HostNameType_DomainName)
-            continue;
-
-        HString name;
-        hostName->get_CanonicalName(name.GetAddressOf());
-        UINT32 length;
-        PCWSTR rawString = name.GetRawBuffer(&length);
-        return QString::fromWCharArray(rawString, length);
-    }
-    ComPtr<IHostName> firstHost;
-    hostNames->GetAt(0, &firstHost);
-
-    HString name;
-    firstHost->get_CanonicalName(name.GetAddressOf());
-    UINT32 length;
-    PCWSTR rawString = name.GetRawBuffer(&length);
-    return QString::fromWCharArray(rawString, length);
 #else
 #  ifdef Q_OS_WIN
     // Important: QtNetwork depends on machineHostName() initializing ws2_32.dll
diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h
index 28fd2942647304f9085b8d2f78f514bafe619a5e..1f184f8c4005a95de2a2f040e457dafdef7f5267 100644
--- a/src/corelib/global/qglobal.h
+++ b/src/corelib/global/qglobal.h
@@ -611,7 +611,6 @@ class QDataStream;
 
 #if defined(Q_OS_WINRT)
 #  define QT_NO_FILESYSTEMWATCHER
-#  define QT_NO_GETADDRINFO
 #  define QT_NO_NETWORKPROXY
 #  define QT_NO_PROCESS
 #  define QT_NO_SOCKETNOTIFIER
diff --git a/src/corelib/global/qnamespace.qdoc b/src/corelib/global/qnamespace.qdoc
index 502d6acd9fd0a73ae5669c823e6d733b887927bb..7c5263ddbd37045d7a6f88d310a524c4bdfd4875 100644
--- a/src/corelib/global/qnamespace.qdoc
+++ b/src/corelib/global/qnamespace.qdoc
@@ -144,9 +144,7 @@
            to be consistent in pixels-per-point across devices rather than
            defining 1 point as 1/72 inch.
 
-    \value AA_X11InitThreads Calls \c XInitThreads() as part of the QApplication
-           construction in order to make Xlib calls thread-safe. This
-           attribute must be set before QApplication is constructed.
+    \value AA_X11InitThreads This value is obsolete and has no effect.
 
     \value AA_SynthesizeTouchForUnhandledMouseEvents All mouse events
            that are not accepted by the application will be translated
@@ -1704,8 +1702,8 @@
     \value Key_unknown
 
     \value Key_Call     A key to answer or initiate a call (see Qt::Key_ToggleCallHangup for a key to toggle current call state)
-    \value Key_Camera   A key to activate the camera shutter
-    \value Key_CameraFocus  A key to focus the camera
+    \value Key_Camera   A key to activate the camera shutter. On Windows Runtime, the environment variable QT_QPA_ENABLE_CAMERA_KEYS must be set to receive the event.
+    \value Key_CameraFocus  A key to focus the camera. On Windows Runtime, the environment variable QT_QPA_ENABLE_CAMERA_KEYS must be set to receive the event.
     \value Key_Context1
     \value Key_Context2
     \value Key_Context3
diff --git a/src/corelib/global/qprocessordetection.h b/src/corelib/global/qprocessordetection.h
index 4b75872bb6258797eda9ef61e8583456b1593664..f80e9c15356516d5ec71a1cd4ae74d0432b81ae2 100644
--- a/src/corelib/global/qprocessordetection.h
+++ b/src/corelib/global/qprocessordetection.h
@@ -88,44 +88,51 @@
     auto-detection implemented below.
 */
 #if defined(__arm__) || defined(__TARGET_ARCH_ARM) || defined(_M_ARM) || defined(__aarch64__)
-#  define Q_PROCESSOR_ARM
 #  if defined(__aarch64__)
 #    define Q_PROCESSOR_ARM_64
 #    define Q_PROCESSOR_WORDSIZE 8
 #  else
 #    define Q_PROCESSOR_ARM_32
 #  endif
-#  if defined(__ARM64_ARCH_8__)
-#    define Q_PROCESSOR_ARM_V8
-#    define Q_PROCESSOR_ARM_V7
-#    define Q_PROCESSOR_ARM_V6
-#    define Q_PROCESSOR_ARM_V5
+#  if defined(__ARM_ARCH) && __ARM_ARCH > 1
+#    define Q_PROCESSOR_ARM __ARM_ARCH
+#  elif defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM > 1
+#    define Q_PROCESSOR_ARM __TARGET_ARCH_ARM
+#  elif defined(_M_ARM) && _M_ARM > 1
+#    define Q_PROCESSOR_ARM _M_ARM
+#  elif defined(__ARM64_ARCH_8__)
+#    define Q_PROCESSOR_ARM 8
 #  elif defined(__ARM_ARCH_7__) \
       || defined(__ARM_ARCH_7A__) \
       || defined(__ARM_ARCH_7R__) \
       || defined(__ARM_ARCH_7M__) \
       || defined(__ARM_ARCH_7S__) \
-      || defined(_ARM_ARCH_7) \
-      || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM-0 >= 7) \
-      || (defined(_M_ARM) && _M_ARM-0 >= 7)
-#    define Q_PROCESSOR_ARM_V7
-#    define Q_PROCESSOR_ARM_V6
-#    define Q_PROCESSOR_ARM_V5
+      || defined(_ARM_ARCH_7)
+#    define Q_PROCESSOR_ARM 7
 #  elif defined(__ARM_ARCH_6__) \
       || defined(__ARM_ARCH_6J__) \
       || defined(__ARM_ARCH_6T2__) \
       || defined(__ARM_ARCH_6Z__) \
       || defined(__ARM_ARCH_6K__) \
       || defined(__ARM_ARCH_6ZK__) \
-      || defined(__ARM_ARCH_6M__) \
-      || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM-0 >= 6) \
-      || (defined(_M_ARM) && _M_ARM-0 >= 6)
-#    define Q_PROCESSOR_ARM_V6
-#    define Q_PROCESSOR_ARM_V5
+      || defined(__ARM_ARCH_6M__)
+#    define Q_PROCESSOR_ARM 6
 #  elif defined(__ARM_ARCH_5TEJ__) \
-        || defined(__ARM_ARCH_5TE__) \
-        || (defined(__TARGET_ARCH_ARM) && __TARGET_ARCH_ARM-0 >= 5) \
-        || (defined(_M_ARM) && _M_ARM-0 >= 5)
+        || defined(__ARM_ARCH_5TE__)
+#    define Q_PROCESSOR_ARM 5
+#  else
+#    define Q_PROCESSOR_ARM 0
+#  endif
+#  if Q_PROCESSOR_ARM >= 8
+#    define Q_PROCESSOR_ARM_V8
+#  endif
+#  if Q_PROCESSOR_ARM >= 7
+#    define Q_PROCESSOR_ARM_V7
+#  endif
+#  if Q_PROCESSOR_ARM >= 6
+#    define Q_PROCESSOR_ARM_V6
+#  endif
+#  if Q_PROCESSOR_ARM >= 5
 #    define Q_PROCESSOR_ARM_V5
 #  endif
 #  if defined(__ARMEL__)
diff --git a/src/corelib/io/qprocess_wince.cpp b/src/corelib/io/qprocess_wince.cpp
index 9b63ece15c85a6cd8d6b38d847d6954956b0a14e..acacdb85403ab4b2c3d2c488f40e23014a62567c 100644
--- a/src/corelib/io/qprocess_wince.cpp
+++ b/src/corelib/io/qprocess_wince.cpp
@@ -235,20 +235,14 @@ bool QProcessPrivate::waitForFinished(int msecs)
     qDebug("QProcessPrivate::waitForFinished(%d)", msecs);
 #endif
 
-    QIncrementalSleepTimer timer(msecs);
-
-    forever {
-        if (!pid)
-            return true;
-
-        if (WaitForSingleObject(pid->hProcess, timer.nextSleepTime()) == WAIT_OBJECT_0) {
-            _q_processDied();
-            return true;
-        }
+    if (!pid)
+        return true;
 
-        if (timer.hasTimedOut())
-            break;
+    if (WaitForSingleObject(pid->hProcess, msecs == -1 ? INFINITE : msecs) == WAIT_OBJECT_0) {
+        _q_processDied();
+        return true;
     }
+
     setError(QProcess::Timedout);
     return false;
 }
diff --git a/src/corelib/io/qstandardpaths_unix.cpp b/src/corelib/io/qstandardpaths_unix.cpp
index ed2faa742aafcc48bd79a9adb241723d9f074768..78f75482ea086cf05e2368d529e51a1a5cf7046e 100644
--- a/src/corelib/io/qstandardpaths_unix.cpp
+++ b/src/corelib/io/qstandardpaths_unix.cpp
@@ -113,21 +113,33 @@ QString QStandardPaths::writableLocation(StandardLocation type)
     {
         const uid_t myUid = geteuid();
         // http://standards.freedesktop.org/basedir-spec/latest/
+        QFileInfo fileInfo;
         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()) {
+            fileInfo.setFile(xdgRuntimeDir);
+            if (!fileInfo.isDir()) {
                 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));
+        } else {
+            fileInfo.setFile(xdgRuntimeDir);
+            if (!fileInfo.exists()) {
+                qWarning("QStandardPaths: XDG_RUNTIME_DIR points to non-existing path '%s', "
+                         "please create it with 0700 permissions.", qPrintable(xdgRuntimeDir));
+                return QString();
+            }
+            if (!fileInfo.isDir()) {
+                qWarning("QStandardPaths: XDG_RUNTIME_DIR points to '%s' which is not a directory",
+                         qPrintable(xdgRuntimeDir));
+                return QString();
+            }
         }
         // "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);
@@ -135,13 +147,15 @@ QString QStandardPaths::writableLocation(StandardLocation type)
         }
         // "and he MUST be the only one having read and write access to it. Its Unix access mode MUST be 0700."
         // since the current user is the owner, set both xxxUser and xxxOwner
-        QFile file(xdgRuntimeDir);
         const QFile::Permissions wantedPerms = QFile::ReadUser | QFile::WriteUser | QFile::ExeUser
                                                | QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner;
-        if (file.permissions() != wantedPerms && !file.setPermissions(wantedPerms)) {
-            qWarning("QStandardPaths: could not set correct permissions on runtime directory %s: %s",
-                     qPrintable(xdgRuntimeDir), qPrintable(file.errorString()));
-            return QString();
+        if (fileInfo.permissions() != wantedPerms) {
+            QFile file(xdgRuntimeDir);
+            if (!file.setPermissions(wantedPerms)) {
+                qWarning("QStandardPaths: could not set correct permissions on runtime directory %s: %s",
+                         qPrintable(xdgRuntimeDir), qPrintable(file.errorString()));
+                return QString();
+            }
         }
         return xdgRuntimeDir;
     }
diff --git a/src/corelib/io/qurl.cpp b/src/corelib/io/qurl.cpp
index 9bf359222a4294a5971390b6dc2781f084fcee1c..775a870a27175929df754462ac385ae355b004a4 100644
--- a/src/corelib/io/qurl.cpp
+++ b/src/corelib/io/qurl.cpp
@@ -2470,8 +2470,10 @@ void QUrl::setPath(const QString &path, ParsingMode mode)
         mode = TolerantMode;
     }
 
-    data = qt_normalizePathSegments(data, false);
-    d->setPath(data, 0, data.length());
+    int from = 0;
+    while (from < data.length() - 2 && data.midRef(from, 2) == QLatin1String("//"))
+        ++from;
+    d->setPath(data, from, data.length());
 
     // optimized out, since there is no path delimiter
 //    if (path.isNull())
diff --git a/src/corelib/io/qurlquery.h b/src/corelib/io/qurlquery.h
index ae3a79c1196061412dfcbc35a2b02cc875d736e8..8fcc1b13d58aa6bc7a6973ca28c349dbd98a805e 100644
--- a/src/corelib/io/qurlquery.h
+++ b/src/corelib/io/qurlquery.h
@@ -121,7 +121,7 @@ inline QStringList QUrl::allQueryItemValues(const QString &key) const
 inline void QUrl::removeQueryItem(const QString &key)
 { QUrlQuery q(*this); q.removeQueryItem(key); setQuery(q); }
 inline void QUrl::removeAllQueryItems(const QString &key)
-{ QUrlQuery q(*this); q.removeAllQueryItems(key); }
+{ QUrlQuery q(*this); q.removeAllQueryItems(key); setQuery(q); }
 
 inline void QUrl::addEncodedQueryItem(const QByteArray &key, const QByteArray &value)
 { QUrlQuery q(*this); q.addQueryItem(fromEncodedComponent_helper(key), fromEncodedComponent_helper(value)); setQuery(q); }
@@ -132,7 +132,7 @@ inline QByteArray QUrl::encodedQueryItemValue(const QByteArray &key) const
 inline void QUrl::removeEncodedQueryItem(const QByteArray &key)
 { QUrlQuery q(*this); q.removeQueryItem(fromEncodedComponent_helper(key)); setQuery(q); }
 inline void QUrl::removeAllEncodedQueryItems(const QByteArray &key)
-{ QUrlQuery q(*this); q.removeAllQueryItems(fromEncodedComponent_helper(key)); }
+{ QUrlQuery q(*this); q.removeAllQueryItems(fromEncodedComponent_helper(key)); setQuery(q); }
 
 inline void QUrl::setEncodedQueryItems(const QList<QPair<QByteArray, QByteArray> > &qry)
 {
diff --git a/src/corelib/io/qwinoverlappedionotifier.cpp b/src/corelib/io/qwinoverlappedionotifier.cpp
index c6ce15c2c9adf09dec63c54da91afbf98b92322b..c9de6671f7f6ff9fb727a9232198289abc796481 100644
--- a/src/corelib/io/qwinoverlappedionotifier.cpp
+++ b/src/corelib/io/qwinoverlappedionotifier.cpp
@@ -102,7 +102,8 @@ public:
 
     OVERLAPPED *waitForAnyNotified(int msecs);
     void notify(DWORD numberOfBytes, DWORD errorCode, OVERLAPPED *overlapped);
-    OVERLAPPED *_q_notified();
+    void _q_notified();
+    OVERLAPPED *dispatchNextIoResult();
 
     static QWinIoCompletionPort *iocp;
     static HANDLE iocpInstanceLock;
@@ -302,8 +303,7 @@ OVERLAPPED *QWinOverlappedIoNotifierPrivate::waitForAnyNotified(int msecs)
     const DWORD wfso = WaitForSingleObject(hSemaphore, msecs == -1 ? INFINITE : DWORD(msecs));
     switch (wfso) {
     case WAIT_OBJECT_0:
-        ReleaseSemaphore(hSemaphore, 1, NULL);
-        return _q_notified();
+        return dispatchNextIoResult();
     case WAIT_TIMEOUT:
         return 0;
     default:
@@ -385,17 +385,20 @@ void QWinOverlappedIoNotifierPrivate::notify(DWORD numberOfBytes, DWORD errorCod
         emit q->_q_notify();
 }
 
-OVERLAPPED *QWinOverlappedIoNotifierPrivate::_q_notified()
+void QWinOverlappedIoNotifierPrivate::_q_notified()
+{
+    if (WaitForSingleObject(hSemaphore, 0) == WAIT_OBJECT_0)
+        dispatchNextIoResult();
+}
+
+OVERLAPPED *QWinOverlappedIoNotifierPrivate::dispatchNextIoResult()
 {
     Q_Q(QWinOverlappedIoNotifier);
-    if (WaitForSingleObject(hSemaphore, 0) == WAIT_OBJECT_0) {
-        WaitForSingleObject(hResultsMutex, INFINITE);
-        IOResult ioresult = results.dequeue();
-        ReleaseMutex(hResultsMutex);
-        emit q->notified(ioresult.numberOfBytes, ioresult.errorCode, ioresult.overlapped);
-        return ioresult.overlapped;
-    }
-    return 0;
+    WaitForSingleObject(hResultsMutex, INFINITE);
+    IOResult ioresult = results.dequeue();
+    ReleaseMutex(hResultsMutex);
+    emit q->notified(ioresult.numberOfBytes, ioresult.errorCode, ioresult.overlapped);
+    return ioresult.overlapped;
 }
 
 QT_END_NAMESPACE
diff --git a/src/corelib/io/qwinoverlappedionotifier_p.h b/src/corelib/io/qwinoverlappedionotifier_p.h
index 863f87353e3a678e12d94e6f69876d009f48c13b..41945d655606b092d6b51884178d77925b8de8dd 100644
--- a/src/corelib/io/qwinoverlappedionotifier_p.h
+++ b/src/corelib/io/qwinoverlappedionotifier_p.h
@@ -58,7 +58,7 @@ class Q_CORE_EXPORT QWinOverlappedIoNotifier : public QObject
     Q_OBJECT
     Q_DISABLE_COPY(QWinOverlappedIoNotifier)
     Q_DECLARE_PRIVATE(QWinOverlappedIoNotifier)
-    Q_PRIVATE_SLOT(d_func(), OVERLAPPED *_q_notified())
+    Q_PRIVATE_SLOT(d_func(), void _q_notified())
     friend class QWinIoCompletionPort;
 public:
     QWinOverlappedIoNotifier(QObject *parent = 0);
diff --git a/src/corelib/json/qjsonvalue.cpp b/src/corelib/json/qjsonvalue.cpp
index 328e07d18e75248268f903989db0020d391ff331..76e5ae562fba2547583a7dbdd43f0645236ccbcd 100644
--- a/src/corelib/json/qjsonvalue.cpp
+++ b/src/corelib/json/qjsonvalue.cpp
@@ -420,6 +420,18 @@ QJsonValue QJsonValue::fromVariant(const QVariant &variant)
         return QJsonValue(QJsonObject::fromVariantMap(variant.toMap()));
     case QVariant::Hash:
         return QJsonValue(QJsonObject::fromVariantHash(variant.toHash()));
+#ifndef QT_BOOTSTRAPPED
+    case QMetaType::QJsonValue:
+        return variant.toJsonValue();
+    case QMetaType::QJsonObject:
+        return variant.toJsonObject();
+    case QMetaType::QJsonArray:
+        return variant.toJsonArray();
+    case QMetaType::QJsonDocument: {
+        QJsonDocument doc = variant.toJsonDocument();
+        return doc.isArray() ? QJsonValue(doc.array()) : QJsonValue(doc.object());
+    }
+#endif
     default:
         break;
     }
diff --git a/src/corelib/kernel/qfunctions_fake_env_p.h b/src/corelib/kernel/qfunctions_fake_env_p.h
index 8b1ab446963fac1bab82e264dae5dd22ecd34803..b4c5ffb079ecddfb45774f49eea40d013f8182b3 100644
--- a/src/corelib/kernel/qfunctions_fake_env_p.h
+++ b/src/corelib/kernel/qfunctions_fake_env_p.h
@@ -46,51 +46,72 @@
 //
 
 #include "qbytearray.h"
-#include "qhash.h"
+#include "qvector.h"
 
 QT_BEGIN_NAMESPACE
 
 // Environment ------------------------------------------------------
-Q_CORE_EXPORT QHash<QByteArray, QByteArray> &qt_app_environment()
-{
-    static QHash<QByteArray, QByteArray> internalEnvironment;
-    return internalEnvironment;
-}
+struct Variable {
+    Variable() { }
+
+    Variable(const QByteArray &name, const QByteArray &value)
+        : name(name), value(value) { }
+
+    QByteArray name;
+    QByteArray value;
+};
+
+Q_DECLARE_TYPEINFO(Variable, Q_MOVABLE_TYPE);
+
+struct NameEquals {
+    typedef bool result_type;
+    const char *name;
+    explicit NameEquals(const char *name) Q_DECL_NOTHROW : name(name) {}
+    result_type operator()(const Variable &other) const Q_DECL_NOTHROW
+    { return qstrcmp(other.name, name) == 0; }
+};
+
+Q_GLOBAL_STATIC(QVector<Variable>, qt_app_environment)
 
 errno_t qt_fake_getenv_s(size_t *sizeNeeded, char *buffer, size_t bufferSize, const char *varName)
 {
     if (!sizeNeeded)
         return EINVAL;
 
-    QHash<QByteArray, QByteArray>::const_iterator iterator = qt_app_environment().constFind(varName);
-    if (iterator == qt_app_environment().constEnd()) {
+    QVector<Variable>::const_iterator end = qt_app_environment->constEnd();
+    QVector<Variable>::const_iterator iterator = std::find_if(qt_app_environment->constBegin(),
+                                                              end,
+                                                              NameEquals(varName));
+    if (iterator == end) {
         if (buffer)
             buffer[0] = '\0';
         return ENOENT;
     }
 
-    const int size = iterator->size() + 1;
+    const int size = iterator->value.size() + 1;
     if (bufferSize < size_t(size)) {
         *sizeNeeded = size;
         return ERANGE;
     }
 
-    qstrcpy(buffer, iterator->constData());
+    qstrcpy(buffer, iterator->value.constData());
     return 0;
 }
 
 errno_t qt_fake__putenv_s(const char *varName, const char *value)
 {
-    QHash<QByteArray, QByteArray>::iterator iterator = qt_app_environment().find(varName);
-    QHash<QByteArray, QByteArray>::iterator end = qt_app_environment().end();
+    QVector<Variable>::iterator end = qt_app_environment->end();
+    QVector<Variable>::iterator iterator = std::find_if(qt_app_environment->begin(),
+                                                        end,
+                                                        NameEquals(varName));
     if (!value || !*value) {
         if (iterator != end)
-            qt_app_environment().erase(iterator);
+            qt_app_environment->erase(iterator);
     } else {
         if (iterator == end)
-            qt_app_environment()[varName] = QByteArray(value);
+            qt_app_environment->append(Variable(varName, value));
         else
-            (*iterator) = value;
+            iterator->value = value;
     }
 
     return 0;
diff --git a/src/corelib/kernel/qfunctions_winrt.h b/src/corelib/kernel/qfunctions_winrt.h
index ee4e050793729732331e169497ee7b17ea2c1f0c..dc1cbe0adefdc337691dc085059180fa8e04da90 100644
--- a/src/corelib/kernel/qfunctions_winrt.h
+++ b/src/corelib/kernel/qfunctions_winrt.h
@@ -40,6 +40,7 @@
 
 #include <QtCore/QThread>
 #include <QtCore/QAbstractEventDispatcher>
+#include <QtCore/QElapsedTimer>
 #include <QtCore/qt_windows.h>
 
 // Convenience macros for handling HRESULT values
@@ -160,7 +161,7 @@ enum AwaitStyle
 };
 
 template <typename T>
-static inline HRESULT _await_impl(const Microsoft::WRL::ComPtr<T> &asyncOp, AwaitStyle awaitStyle)
+static inline HRESULT _await_impl(const Microsoft::WRL::ComPtr<T> &asyncOp, AwaitStyle awaitStyle, uint timeout)
 {
     Microsoft::WRL::ComPtr<IAsyncInfo> asyncInfo;
     HRESULT hr = asyncOp.As(&asyncInfo);
@@ -168,22 +169,34 @@ static inline HRESULT _await_impl(const Microsoft::WRL::ComPtr<T> &asyncOp, Awai
         return hr;
 
     AsyncStatus status;
+    QElapsedTimer t;
+    if (timeout)
+        t.start();
     switch (awaitStyle) {
     case ProcessMainThreadEvents:
-        while (SUCCEEDED(hr = asyncInfo->get_Status(&status)) && status == Started)
+        while (SUCCEEDED(hr = asyncInfo->get_Status(&status)) && status == Started) {
             QCoreApplication::processEvents();
+            if (timeout && t.hasExpired(timeout))
+                return ERROR_TIMEOUT;
+        }
         break;
     case ProcessThreadEvents:
         if (QAbstractEventDispatcher *dispatcher = QThread::currentThread()->eventDispatcher()) {
-            while (SUCCEEDED(hr = asyncInfo->get_Status(&status)) && status == Started)
+            while (SUCCEEDED(hr = asyncInfo->get_Status(&status)) && status == Started) {
                 dispatcher->processEvents(QEventLoop::AllEvents);
+                if (timeout && t.hasExpired(timeout))
+                    return ERROR_TIMEOUT;
+            }
             break;
         }
         // fall through
     default:
     case YieldThread:
-        while (SUCCEEDED(hr = asyncInfo->get_Status(&status)) && status == Started)
+        while (SUCCEEDED(hr = asyncInfo->get_Status(&status)) && status == Started) {
             QThread::yieldCurrentThread();
+            if (timeout && t.hasExpired(timeout))
+                return ERROR_TIMEOUT;
+        }
         break;
     }
 
@@ -199,9 +212,9 @@ static inline HRESULT _await_impl(const Microsoft::WRL::ComPtr<T> &asyncOp, Awai
 }
 
 template <typename T>
-static inline HRESULT await(const Microsoft::WRL::ComPtr<T> &asyncOp, AwaitStyle awaitStyle = YieldThread)
+static inline HRESULT await(const Microsoft::WRL::ComPtr<T> &asyncOp, AwaitStyle awaitStyle = YieldThread, uint timeout = 0)
 {
-    HRESULT hr = _await_impl(asyncOp, awaitStyle);
+    HRESULT hr = _await_impl(asyncOp, awaitStyle, timeout);
     if (FAILED(hr))
         return hr;
 
@@ -209,9 +222,9 @@ static inline HRESULT await(const Microsoft::WRL::ComPtr<T> &asyncOp, AwaitStyle
 }
 
 template <typename T, typename U>
-static inline HRESULT await(const Microsoft::WRL::ComPtr<T> &asyncOp, U *results, AwaitStyle awaitStyle = YieldThread)
+static inline HRESULT await(const Microsoft::WRL::ComPtr<T> &asyncOp, U *results, AwaitStyle awaitStyle = YieldThread, uint timeout = 0)
 {
-    HRESULT hr = _await_impl(asyncOp, awaitStyle);
+    HRESULT hr = _await_impl(asyncOp, awaitStyle, timeout);
     if (FAILED(hr))
         return hr;
 
diff --git a/src/corelib/kernel/qsharedmemory_win.cpp b/src/corelib/kernel/qsharedmemory_win.cpp
index ac4ef39e8f2a437e535352fa43e8fc612e2fc5cc..f90763d308ff0eddfe8d887d69f9ef6c378334b5 100644
--- a/src/corelib/kernel/qsharedmemory_win.cpp
+++ b/src/corelib/kernel/qsharedmemory_win.cpp
@@ -58,7 +58,7 @@ void QSharedMemoryPrivate::setErrorString(QLatin1String function)
         errorString = QSharedMemory::tr("%1: already exists").arg(function);
     break;
     case ERROR_FILE_NOT_FOUND:
-#ifdef Q_OS_WINCE
+#if defined(Q_OS_WINCE) || (defined(Q_OS_WINRT) && _MSC_VER < 1900)
         // This happens on CE only if no file is present as CreateFileMappingW
         // bails out with this error code
     case ERROR_INVALID_PARAMETER:
diff --git a/src/corelib/kernel/qvariant.cpp b/src/corelib/kernel/qvariant.cpp
index fdcbdb1c4543b78e838ae180aaaaaddc73ee1c76..3e6aefab2aae4f89eb48391623d69c9cb061122a 100644
--- a/src/corelib/kernel/qvariant.cpp
+++ b/src/corelib/kernel/qvariant.cpp
@@ -3448,7 +3448,7 @@ static int numericCompare(const QVariant::Private *d1, const QVariant::Private *
     Q_ASSERT(ok);
     qreal r2 = qConvertToRealNumber(d2, &ok);
     Q_ASSERT(ok);
-    if (qFuzzyCompare(r1, r2))
+    if (r1 == r2 || qFuzzyCompare(r1, r2))
         return 0;
     return r1 < r2 ? -1 : 1;
 }
diff --git a/src/corelib/kernel/qvariant_p.h b/src/corelib/kernel/qvariant_p.h
index d84d702982d1ef79a68c2b4a55931a67fa89b754..337e1406eca2c441ab6e642d8dec6ef685bb9040 100644
--- a/src/corelib/kernel/qvariant_p.h
+++ b/src/corelib/kernel/qvariant_p.h
@@ -1,6 +1,7 @@
 /****************************************************************************
 **
 ** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2016 Intel Corporation.
 ** Contact: http://www.qt.io/licensing/
 **
 ** This file is part of the QtCore module of the Qt Toolkit.
@@ -59,6 +60,7 @@ struct QVariantIntegrator
 {
     static const bool CanUseInternalSpace = sizeof(T) <= sizeof(QVariant::Private::Data)
                                             && ((QTypeInfoQuery<T>::isRelocatable) || Q_IS_ENUM(T));
+    typedef QtPrivate::integral_constant<bool, CanUseInternalSpace> CanUseInternalSpace_t;
 };
 Q_STATIC_ASSERT(QVariantIntegrator<double>::CanUseInternalSpace);
 Q_STATIC_ASSERT(QVariantIntegrator<long int>::CanUseInternalSpace);
@@ -109,31 +111,49 @@ private:
     T m_t;
 };
 
-// constructs a new variant if copy is 0, otherwise copy-constructs
 template <class T>
-inline void v_construct(QVariant::Private *x, const void *copy, T * = 0)
+inline void v_construct_helper(QVariant::Private *x, const T &t, QtPrivate::true_type)
 {
-    if (!QVariantIntegrator<T>::CanUseInternalSpace) {
-        x->data.shared = copy ? new QVariantPrivateSharedEx<T>(*static_cast<const T *>(copy))
-                              : new QVariantPrivateSharedEx<T>;
-        x->is_shared = true;
-    } else {
-        if (copy)
-            new (&x->data.ptr) T(*static_cast<const T *>(copy));
-        else
-            new (&x->data.ptr) T;
-    }
+    new (&x->data) T(t);
+    x->is_shared = false;
+}
+
+template <class T>
+inline void v_construct_helper(QVariant::Private *x, const T &t, QtPrivate::false_type)
+{
+    x->data.shared = new QVariantPrivateSharedEx<T>(t);
+    x->is_shared = true;
+}
+
+template <class T>
+inline void v_construct_helper(QVariant::Private *x, QtPrivate::true_type)
+{
+    new (&x->data) T();
+    x->is_shared = false;
+}
+
+template <class T>
+inline void v_construct_helper(QVariant::Private *x, QtPrivate::false_type)
+{
+    x->data.shared = new QVariantPrivateSharedEx<T>;
+    x->is_shared = true;
 }
 
 template <class T>
 inline void v_construct(QVariant::Private *x, const T &t)
 {
-    if (!QVariantIntegrator<T>::CanUseInternalSpace) {
-        x->data.shared = new QVariantPrivateSharedEx<T>(t);
-        x->is_shared = true;
-    } else {
-        new (&x->data.ptr) T(t);
-    }
+    // dispatch
+    v_construct_helper(x, t, typename QVariantIntegrator<T>::CanUseInternalSpace_t());
+}
+
+// constructs a new variant if copy is 0, otherwise copy-constructs
+template <class T>
+inline void v_construct(QVariant::Private *x, const void *copy, T * = 0)
+{
+    if (copy)
+        v_construct<T>(x, *static_cast<const T *>(copy));
+    else
+        v_construct_helper<T>(x, typename QVariantIntegrator<T>::CanUseInternalSpace_t());
 }
 
 // deletes the internal structures
@@ -327,39 +347,11 @@ protected:
 template<class Filter>
 class QVariantConstructor
 {
-    template<typename T, bool CanUseInternalSpace = QVariantIntegrator<T>::CanUseInternalSpace>
-    struct CallConstructor {};
-
-    template<typename T>
-    struct CallConstructor<T, /* CanUseInternalSpace = */ true>
-    {
-        CallConstructor(const QVariantConstructor &tc)
-        {
-            if (tc.m_copy)
-                new (&tc.m_x->data.ptr) T(*static_cast<const T*>(tc.m_copy));
-            else
-                new (&tc.m_x->data.ptr) T();
-            tc.m_x->is_shared = false;
-        }
-    };
-
-    template<typename T>
-    struct CallConstructor<T, /* CanUseInternalSpace = */ false>
-    {
-        CallConstructor(const QVariantConstructor &tc)
-        {
-            Q_STATIC_ASSERT(QTypeInfo<T>::isComplex || sizeof(T) > sizeof(QVariant::Private::Data));
-            tc.m_x->data.shared = tc.m_copy ? new QVariantPrivateSharedEx<T>(*static_cast<const T*>(tc.m_copy))
-                                      : new QVariantPrivateSharedEx<T>;
-            tc.m_x->is_shared = true;
-        }
-    };
-
     template<typename T, bool IsAcceptedType = Filter::template Acceptor<T>::IsAccepted>
     struct FilteredConstructor {
         FilteredConstructor(const QVariantConstructor &tc)
         {
-            CallConstructor<T> tmp(tc);
+            v_construct<T>(tc.m_x, tc.m_copy);
             tc.m_x->is_null = !tc.m_copy;
         }
     };
diff --git a/src/corelib/mimetypes/qmimedatabase.cpp b/src/corelib/mimetypes/qmimedatabase.cpp
index c1e17b9fc4da9fdeb3ea6c1b6bef24f6b4d3f83a..fd11dbc787b1bd21b1a9721ef5b4ce97dcf6c753 100644
--- a/src/corelib/mimetypes/qmimedatabase.cpp
+++ b/src/corelib/mimetypes/qmimedatabase.cpp
@@ -354,9 +354,10 @@ QMimeType QMimeDatabase::mimeTypeForFile(const QFileInfo &fileInfo, MatchMode mo
 
 #ifdef Q_OS_UNIX
     // Cannot access statBuf.st_mode from the filesystem engine, so we have to stat again.
+    // In addition we want to follow symlinks.
     const QByteArray nativeFilePath = QFile::encodeName(file.fileName());
     QT_STATBUF statBuffer;
-    if (QT_LSTAT(nativeFilePath.constData(), &statBuffer) == 0) {
+    if (QT_STAT(nativeFilePath.constData(), &statBuffer) == 0) {
         if (S_ISCHR(statBuffer.st_mode))
             return d->mimeTypeForName(QLatin1String("inode/chardevice"));
         if (S_ISBLK(statBuffer.st_mode))
diff --git a/src/corelib/plugin/qfactoryloader.cpp b/src/corelib/plugin/qfactoryloader.cpp
index 60026ef56ab7be7ac5ef57acc25a7ca1f1853e83..bfa2ef7efa3894f60cbcc8216994ce204dc1c16f 100644
--- a/src/corelib/plugin/qfactoryloader.cpp
+++ b/src/corelib/plugin/qfactoryloader.cpp
@@ -79,8 +79,6 @@ public:
     QString suffix;
     Qt::CaseSensitivity cs;
     QStringList loadedPaths;
-
-    void unloadPath(const QString &path);
 };
 
 QFactoryLoaderPrivate::~QFactoryLoaderPrivate()
diff --git a/src/corelib/thread/qexception.h b/src/corelib/thread/qexception.h
index b15ae5095ab98e5063eca117be248b299c6aa994..dc988f9020f187a611fbe35d9a4cea97bf6ae531 100644
--- a/src/corelib/thread/qexception.h
+++ b/src/corelib/thread/qexception.h
@@ -86,7 +86,7 @@ class Q_CORE_EXPORT ExceptionHolder
 public:
     ExceptionHolder(QException *exception = Q_NULLPTR);
     ExceptionHolder(const ExceptionHolder &other);
-    void operator=(const ExceptionHolder &other);
+    void operator=(const ExceptionHolder &other); // ### Qt6: copy-assign operator shouldn't return void. Remove this method and the copy-ctor, they are unneeded.
     ~ExceptionHolder();
     QException *exception() const;
     QExplicitlySharedDataPointer<Base> base;
diff --git a/src/corelib/thread/qthread_win.cpp b/src/corelib/thread/qthread_win.cpp
index 1a4b41fee4d10fdfadebe21ca17cb924f90c480b..32e8a52a281b35fcfc06691e951f860d5cbac87b 100644
--- a/src/corelib/thread/qthread_win.cpp
+++ b/src/corelib/thread/qthread_win.cpp
@@ -69,6 +69,30 @@
 #ifndef QT_NO_THREAD
 QT_BEGIN_NAMESPACE
 
+#ifdef Q_OS_WINRT
+inline DWORD qWinRTTlsAlloc() {
+    return FlsAlloc(0);
+}
+
+inline bool qWinRTTlsFree(DWORD dwTlsIndex) {
+    return FlsFree(dwTlsIndex);
+}
+
+inline LPVOID qWinRTTlsGetValue(DWORD dwTlsIndex) {
+    return FlsGetValue(dwTlsIndex);
+}
+
+inline bool qWinRTTlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue) {
+    return FlsSetValue(dwTlsIndex, lpTlsValue);
+}
+
+#define TlsAlloc qWinRTTlsAlloc
+#define TlsFree qWinRTTlsFree
+#define TlsSetValue qWinRTTlsSetValue
+#define TlsGetValue qWinRTTlsGetValue
+
+#endif // Q_OS_WINRT
+
 void qt_watch_adopted_thread(const HANDLE adoptedThreadHandle, QThread *qthread);
 DWORD WINAPI qt_adopted_thread_watcher_function(LPVOID);
 
diff --git a/src/corelib/thread/qthreadpool.cpp b/src/corelib/thread/qthreadpool.cpp
index b6b3be8d923e364e5c9519051f8f3694475b73ae..e4a53682810ffceb99ed90d2fd8c7624e9035ad6 100644
--- a/src/corelib/thread/qthreadpool.cpp
+++ b/src/corelib/thread/qthreadpool.cpp
@@ -204,8 +204,8 @@ void QThreadPoolPrivate::enqueueTask(QRunnable *runnable, int priority)
         ++runnable->ref;
 
     // put it on the queue
-    QList<QPair<QRunnable *, int> >::const_iterator begin = queue.constBegin();
-    QList<QPair<QRunnable *, int> >::const_iterator it = queue.constEnd();
+    QVector<QPair<QRunnable *, int> >::const_iterator begin = queue.constBegin();
+    QVector<QPair<QRunnable *, int> >::const_iterator it = queue.constEnd();
     if (it != begin && priority > (*(it - 1)).second)
         it = std::upper_bound(begin, --it, priority);
     queue.insert(it - begin, qMakePair(runnable, priority));
@@ -299,7 +299,7 @@ bool QThreadPoolPrivate::waitForDone(int msecs)
 void QThreadPoolPrivate::clear()
 {
     QMutexLocker locker(&mutex);
-    for (QList<QPair<QRunnable *, int> >::const_iterator it = queue.constBegin();
+    for (QVector<QPair<QRunnable *, int> >::const_iterator it = queue.constBegin();
          it != queue.constEnd(); ++it) {
         QRunnable* r = it->first;
         if (r->autoDelete() && !--r->ref)
@@ -319,8 +319,8 @@ bool QThreadPoolPrivate::stealRunnable(QRunnable *runnable)
         return false;
     {
         QMutexLocker locker(&mutex);
-        QList<QPair<QRunnable *, int> >::iterator it = queue.begin();
-        QList<QPair<QRunnable *, int> >::iterator end = queue.end();
+        QVector<QPair<QRunnable *, int> >::iterator it = queue.begin();
+        QVector<QPair<QRunnable *, int> >::iterator end = queue.end();
 
         while (it != end) {
             if (it->first == runnable) {
diff --git a/src/corelib/thread/qthreadpool_p.h b/src/corelib/thread/qthreadpool_p.h
index 34728ed3e2c3ce4710cb03849f1bd55284add6d9..b03eefcc9421538a3f0e5d21c2fdf2a204f70886 100644
--- a/src/corelib/thread/qthreadpool_p.h
+++ b/src/corelib/thread/qthreadpool_p.h
@@ -83,7 +83,7 @@ public:
     QSet<QThreadPoolThread *> allThreads;
     QQueue<QThreadPoolThread *> waitingThreads;
     QQueue<QThreadPoolThread *> expiredThreads;
-    QList<QPair<QRunnable *, int> > queue;
+    QVector<QPair<QRunnable *, int> > queue;
     QWaitCondition noActiveThreads;
 
     bool isExiting;
diff --git a/src/corelib/tools/qcommandlineparser.cpp b/src/corelib/tools/qcommandlineparser.cpp
index 15c7a0646fb15144a1624d73a92122a22cf285f3..2bc60c5b9ee7a3571e6186ef1e75e94a24986997 100644
--- a/src/corelib/tools/qcommandlineparser.cpp
+++ b/src/corelib/tools/qcommandlineparser.cpp
@@ -540,7 +540,13 @@ static inline bool displayMessageBox()
 
 static void showParserMessage(const QString &message, MessageType type)
 {
-#if defined(Q_OS_WIN) && !defined(QT_BOOTSTRAPPED) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
+#if defined(Q_OS_WINRT)
+    if (type == UsageMessage)
+        qInfo(qPrintable(message));
+    else
+        qCritical(qPrintable(message));
+    return;
+#elif defined(Q_OS_WIN) && !defined(QT_BOOTSTRAPPED) && !defined(Q_OS_WINCE)
     if (displayMessageBox()) {
         const UINT flags = MB_OK | MB_TOPMOST | MB_SETFOREGROUND
             | (type == UsageMessage ? MB_ICONINFORMATION : MB_ICONERROR);
@@ -553,7 +559,7 @@ static void showParserMessage(const QString &message, MessageType type)
                     reinterpret_cast<const wchar_t *>(title.utf16()), flags);
         return;
     }
-#endif // Q_OS_WIN && !QT_BOOTSTRAPPED && !Q_OS_WIN && !Q_OS_WINRT
+#endif // Q_OS_WIN && !QT_BOOTSTRAPPED && !Q_OS_WINCE
     fputs(qPrintable(message), type == UsageMessage ? stdout : stderr);
 }
 
diff --git a/src/corelib/tools/qdatetime.cpp b/src/corelib/tools/qdatetime.cpp
index 6494990435ff9e83fe17925049d0bea61f22efb5..8943c8c6cd511a403acb41c124b73551f31e933c 100644
--- a/src/corelib/tools/qdatetime.cpp
+++ b/src/corelib/tools/qdatetime.cpp
@@ -586,7 +586,7 @@ int QDate::weekNumber(int *yearNumber) const
         Q_ASSERT(week == 52 || week == 53);
     } else if (week == 53) {
         // maybe first week of next year
-        int w = (yday - 365 - (QDate::isLeapYear(year + 1) ? 1 : 0) - wday + 10) / 7;
+        int w = (yday - 365 - (QDate::isLeapYear(year) ? 1 : 0) - wday + 10) / 7;
         if (w > 0) {
             ++year;
             week = w;
@@ -3662,6 +3662,40 @@ QString QDateTime::toString(const QString& format) const
 }
 #endif //QT_NO_DATESTRING
 
+static void massageAdjustedDateTime(Qt::TimeSpec spec,
+#ifndef QT_BOOTSTRAPPED
+                                    const QTimeZone &zone,
+#endif // QT_BOOTSTRAPPED
+                                    QDate *date,
+                                    QTime *time)
+{
+    /*
+      If we have just adjusted to a day with a DST transition, our given time
+      may lie in the transition hour (either missing or duplicated).  For any
+      other time, telling mktime (deep in the bowels of localMSecsToEpochMSecs)
+      we don't know its DST-ness will produce no adjustment (just a decision as
+      to its DST-ness); but for a time in spring's missing hour it'll adjust the
+      time while picking a DST-ness.  (Handling of autumn is trickier, as either
+      DST-ness is valid, without adjusting the time.  We might want to propagate
+      d->daylightStatus() in that case, but it's hard to do so without breaking
+      (far more common) other cases; and it makes little difference, as the two
+      answers do then differ only in DST-ness.)
+    */
+    if (spec == Qt::LocalTime) {
+        QDateTimePrivate::DaylightStatus status = QDateTimePrivate::UnknownDaylightTime;
+        localMSecsToEpochMSecs(timeToMSecs(*date, *time), &status, date, time);
+#ifndef QT_BOOTSTRAPPED
+    } else if (spec == Qt::TimeZone) {
+        QDateTimePrivate::zoneMSecsToEpochMSecs(timeToMSecs(*date, *time), zone, date, time);
+#endif // QT_BOOTSTRAPPED
+    }
+}
+#ifdef QT_BOOTSTRAPPED // Avoid duplicate #if-ery in uses.
+#define MASSAGEADJUSTEDDATETIME(s, z, d, t) massageAdjustedDateTime(s, d, t)
+#else
+#define MASSAGEADJUSTEDDATETIME(s, z, d, t) massageAdjustedDateTime(s, z, d, t)
+#endif // QT_BOOTSTRAPPED
+
 /*!
     Returns a QDateTime object containing a datetime \a ndays days
     later than the datetime of this object (or earlier if \a ndays is
@@ -3683,16 +3717,7 @@ QDateTime QDateTime::addDays(qint64 ndays) const
     QDate &date = p.first;
     QTime &time = p.second;
     date = date.addDays(ndays);
-    // Result might fall into "missing" DaylightTime transition hour,
-    // so call conversion and use the adjusted returned time
-    if (d->m_spec == Qt::LocalTime) {
-        QDateTimePrivate::DaylightStatus status = d->daylightStatus();
-        localMSecsToEpochMSecs(timeToMSecs(date, time), &status, &date, &time);
-#ifndef QT_BOOTSTRAPPED
-    } else if (d->m_spec == Qt::TimeZone) {
-        QDateTimePrivate::zoneMSecsToEpochMSecs(timeToMSecs(date, time), d->m_timeZone, &date, &time);
-#endif // QT_BOOTSTRAPPED
-    }
+    MASSAGEADJUSTEDDATETIME(d->m_spec, d->m_timeZone, &date, &time);
     dt.d->setDateTime(date, time);
     return dt;
 }
@@ -3718,16 +3743,7 @@ QDateTime QDateTime::addMonths(int nmonths) const
     QDate &date = p.first;
     QTime &time = p.second;
     date = date.addMonths(nmonths);
-    // Result might fall into "missing" DaylightTime transition hour,
-    // so call conversion and use the adjusted returned time
-    if (d->m_spec == Qt::LocalTime) {
-        QDateTimePrivate::DaylightStatus status = d->daylightStatus();
-        localMSecsToEpochMSecs(timeToMSecs(date, time), &status, &date, &time);
-#ifndef QT_BOOTSTRAPPED
-    } else if (d->m_spec == Qt::TimeZone) {
-        QDateTimePrivate::zoneMSecsToEpochMSecs(timeToMSecs(date, time), d->m_timeZone, &date, &time);
-#endif // QT_BOOTSTRAPPED
-    }
+    MASSAGEADJUSTEDDATETIME(d->m_spec, d->m_timeZone, &date, &time);
     dt.d->setDateTime(date, time);
     return dt;
 }
@@ -3753,19 +3769,11 @@ QDateTime QDateTime::addYears(int nyears) const
     QDate &date = p.first;
     QTime &time = p.second;
     date = date.addYears(nyears);
-    // Result might fall into "missing" DaylightTime transition hour,
-    // so call conversion and use the adjusted returned time
-    if (d->m_spec == Qt::LocalTime) {
-        QDateTimePrivate::DaylightStatus status = d->daylightStatus();
-        localMSecsToEpochMSecs(timeToMSecs(date, time), &status, &date, &time);
-#ifndef QT_BOOTSTRAPPED
-    } else if (d->m_spec == Qt::TimeZone) {
-        QDateTimePrivate::zoneMSecsToEpochMSecs(timeToMSecs(date, time), d->m_timeZone, &date, &time);
-#endif // QT_BOOTSTRAPPED
-    }
+    MASSAGEADJUSTEDDATETIME(d->m_spec, d->m_timeZone, &date, &time);
     dt.d->setDateTime(date, time);
     return dt;
 }
+#undef MASSAGEADJUSTEDDATETIME
 
 /*!
     Returns a QDateTime object containing a datetime \a s seconds
diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp
index 221027e18d25c58b7fd590c1c2d91d23e2da5c61..88ad9ed3dfc4161ca0564ae0dbefbc9924e5951d 100644
--- a/src/corelib/tools/qlocale.cpp
+++ b/src/corelib/tools/qlocale.cpp
@@ -116,6 +116,13 @@ QLocale::Language QLocalePrivate::codeToLanguage(const QString &code)
         Q_STATIC_ASSERT(QLocale::Moldavian == QLocale::Romanian);
         return QLocale::Moldavian;
     }
+    // Android uses the following deprecated codes
+    if (uc1 == 'i' && uc2 == 'w' && uc3 == 0) // iw -> he
+        return QLocale::Hebrew;
+    if (uc1 == 'i' && uc2 == 'n' && uc3 == 0) // in -> id
+        return QLocale::Indonesian;
+    if (uc1 == 'j' && uc2 == 'i' && uc3 == 0) // ji -> yi
+        return QLocale::Yiddish;
 
     return QLocale::C;
 }
diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp
index 8c06ec4045814130277aa97b7b8edb24ba3bf096..89d9889b2f0a482bcff462d6985a741d8acbb0c9 100644
--- a/src/corelib/tools/qstring.cpp
+++ b/src/corelib/tools/qstring.cpp
@@ -1676,20 +1676,11 @@ void QString::resize(int size)
         return;
     }
 
-    if (size == 0 && !d->capacityReserved) {
-        Data *x = Data::allocate(0);
-        if (!d->ref.deref())
-            Data::deallocate(d);
-        d = x;
-    } else {
-        if (d->ref.isShared() || uint(size) + 1u > d->alloc
-                || (!d->capacityReserved && size < d->size
-                    && uint(size) + 1u < uint(d->alloc >> 1)))
-            reallocData(uint(size) + 1u, true);
-        if (d->alloc) {
-            d->size = size;
-            d->data()[size] = '\0';
-        }
+    if (d->ref.isShared() || uint(size) + 1u > d->alloc)
+        reallocData(uint(size) + 1u, true);
+    if (d->alloc) {
+        d->size = size;
+        d->data()[size] = '\0';
     }
 }
 
diff --git a/src/corelib/tools/qstring.h b/src/corelib/tools/qstring.h
index 1d04bcb457fcdb0c4cfe48f5920a6e34b7ef9076..1fbcff35d1a9f66ae95cb4bf14a826ff62aeb3e6 100644
--- a/src/corelib/tools/qstring.h
+++ b/src/corelib/tools/qstring.h
@@ -86,7 +86,7 @@ public:
     Q_DECL_CONSTEXPR inline QLatin1String() Q_DECL_NOTHROW : m_size(0), m_data(Q_NULLPTR) {}
     Q_DECL_CONSTEXPR inline explicit QLatin1String(const char *s) Q_DECL_NOTHROW : m_size(s ? int(strlen(s)) : 0), m_data(s) {}
     Q_DECL_CONSTEXPR inline explicit QLatin1String(const char *s, int sz) Q_DECL_NOTHROW : m_size(sz), m_data(s) {}
-    inline explicit QLatin1String(const QByteArray &s) Q_DECL_NOTHROW : m_size(s.size()), m_data(s.constData()) {}
+    inline explicit QLatin1String(const QByteArray &s) Q_DECL_NOTHROW : m_size(int(qstrnlen(s.constData(), s.size()))), m_data(s.constData()) {}
 
     Q_DECL_CONSTEXPR const char *latin1() const Q_DECL_NOTHROW { return m_data; }
     Q_DECL_CONSTEXPR int size() const Q_DECL_NOTHROW { return m_size; }
@@ -539,11 +539,11 @@ public:
         return fromLocal8Bit_helper(str, (str && size == -1) ? int(strlen(str)) : size);
     }
     static inline QString fromLatin1(const QByteArray &str)
-    { return str.isNull() ? QString() : fromLatin1(str.data(), str.size()); }
+    { return str.isNull() ? QString() : fromLatin1(str.data(), qstrnlen(str.constData(), str.size())); }
     static inline QString fromUtf8(const QByteArray &str)
-    { return str.isNull() ? QString() : fromUtf8(str.data(), str.size()); }
+    { return str.isNull() ? QString() : fromUtf8(str.data(), qstrnlen(str.constData(), str.size())); }
     static inline QString fromLocal8Bit(const QByteArray &str)
-    { return str.isNull() ? QString() : fromLocal8Bit(str.data(), str.size()); }
+    { return str.isNull() ? QString() : fromLocal8Bit(str.data(), qstrnlen(str.constData(), str.size())); }
     static QString fromUtf16(const ushort *, int size = -1);
     static QString fromUcs4(const uint *, int size = -1);
     static QString fromRawData(const QChar *, int size);
@@ -655,7 +655,7 @@ public:
         : d(fromAscii_helper(ch, ch ? int(strlen(ch)) : -1))
     {}
     inline QT_ASCII_CAST_WARN QString(const QByteArray &a)
-        : d(fromAscii_helper(a.constData(), a.size()))
+        : d(fromAscii_helper(a.constData(), qstrnlen(a.constData(), a.size())))
     {}
     inline QT_ASCII_CAST_WARN QString &operator=(const char *ch)
     { return (*this = fromUtf8(ch)); }
@@ -1223,9 +1223,9 @@ inline QT_ASCII_CAST_WARN bool QLatin1String::operator>=(const QByteArray &s) co
 { return QString::fromUtf8(s) <= *this; }
 
 inline QT_ASCII_CAST_WARN bool QString::operator==(const QByteArray &s) const
-{ return QString::compare_helper(constData(), size(), s.constData(), s.size()) == 0; }
+{ return QString::compare_helper(constData(), size(), s.constData(), qstrnlen(s.constData(), s.size())) == 0; }
 inline QT_ASCII_CAST_WARN bool QString::operator!=(const QByteArray &s) const
-{ return QString::compare_helper(constData(), size(), s.constData(), s.size()) != 0; }
+{ return QString::compare_helper(constData(), size(), s.constData(), qstrnlen(s.constData(), s.size())) != 0; }
 inline QT_ASCII_CAST_WARN bool QString::operator<(const QByteArray &s) const
 { return QString::compare_helper(constData(), size(), s.constData(), s.size()) < 0; }
 inline QT_ASCII_CAST_WARN bool QString::operator>(const QByteArray &s) const
@@ -1236,9 +1236,9 @@ inline QT_ASCII_CAST_WARN bool QString::operator>=(const QByteArray &s) const
 { return QString::compare_helper(constData(), size(), s.constData(), s.size()) >= 0; }
 
 inline bool QByteArray::operator==(const QString &s) const
-{ return QString::compare_helper(s.constData(), s.size(), constData(), size()) == 0; }
+{ return QString::compare_helper(s.constData(), s.size(), constData(), qstrnlen(constData(), size())) == 0; }
 inline bool QByteArray::operator!=(const QString &s) const
-{ return QString::compare_helper(s.constData(), s.size(), constData(), size()) != 0; }
+{ return QString::compare_helper(s.constData(), s.size(), constData(), qstrnlen(constData(), size())) != 0; }
 inline bool QByteArray::operator<(const QString &s) const
 { return QString::compare_helper(s.constData(), s.size(), constData(), size()) > 0; }
 inline bool QByteArray::operator>(const QString &s) const
diff --git a/src/dbus/qdbusconnection.cpp b/src/dbus/qdbusconnection.cpp
index e9196173ad53b9435978bc6e941135cd0d59e865..0f2d799b9226f2fc7e4b0b7c864bb2884eb754e0 100644
--- a/src/dbus/qdbusconnection.cpp
+++ b/src/dbus/qdbusconnection.cpp
@@ -38,6 +38,7 @@
 #include <qdebug.h>
 #include <qcoreapplication.h>
 #include <qstringlist.h>
+#include <qtimer.h>
 #include <qthread.h>
 
 #include "qdbusconnectioninterface.h"
@@ -59,6 +60,24 @@ QT_BEGIN_NAMESPACE
 
 Q_GLOBAL_STATIC(QDBusConnectionManager, _q_manager)
 
+// can be replaced with a lambda in Qt 5.7
+class QDBusConnectionDispatchEnabler : public QObject
+{
+    Q_OBJECT
+    QDBusConnectionPrivate *con;
+public:
+    QDBusConnectionDispatchEnabler(QDBusConnectionPrivate *con) : con(con) {}
+
+public slots:
+    void execute()
+    {
+        con->setDispatchEnabled(true);
+        if (!con->ref.deref())
+            con->deleteLater();
+        deleteLater();
+    }
+};
+
 struct QDBusConnectionManager::ConnectionRequestData
 {
     enum RequestType {
@@ -74,6 +93,8 @@ struct QDBusConnectionManager::ConnectionRequestData
     const QString *name;
 
     QDBusConnectionPrivate *result;
+
+    bool suspendedDelivery;
 };
 
 QDBusConnectionPrivate *QDBusConnectionManager::busConnection(QDBusConnection::BusType type)
@@ -84,6 +105,10 @@ QDBusConnectionPrivate *QDBusConnectionManager::busConnection(QDBusConnection::B
     if (!qdbus_loadLibDBus())
         return 0;
 
+    // we'll start in suspended delivery mode if we're in the main thread
+    // (the event loop will resume delivery)
+    bool suspendedDelivery = qApp && qApp->thread() == QThread::currentThread();
+
     QMutexLocker lock(&defaultBusMutex);
     if (defaultBuses[type])
         return defaultBuses[type];
@@ -91,7 +116,7 @@ QDBusConnectionPrivate *QDBusConnectionManager::busConnection(QDBusConnection::B
     QString name = QStringLiteral("qt_default_session_bus");
     if (type == QDBusConnection::SystemBus)
         name = QStringLiteral("qt_default_system_bus");
-    return defaultBuses[type] = connectToBus(type, name);
+    return defaultBuses[type] = connectToBus(type, name, suspendedDelivery);
 }
 
 QDBusConnectionPrivate *QDBusConnectionManager::connection(const QString &name) const
@@ -169,14 +194,22 @@ void QDBusConnectionManager::run()
     moveToThread(Q_NULLPTR);
 }
 
-QDBusConnectionPrivate *QDBusConnectionManager::connectToBus(QDBusConnection::BusType type, const QString &name)
+QDBusConnectionPrivate *QDBusConnectionManager::connectToBus(QDBusConnection::BusType type, const QString &name,
+                                                             bool suspendedDelivery)
 {
     ConnectionRequestData data;
     data.type = ConnectionRequestData::ConnectToStandardBus;
     data.busType = type;
     data.name = &name;
+    data.suspendedDelivery = suspendedDelivery;
 
     emit connectionRequested(&data);
+    if (suspendedDelivery) {
+        data.result->ref.ref();
+        QDBusConnectionDispatchEnabler *o = new QDBusConnectionDispatchEnabler(data.result);
+        QTimer::singleShot(0, o, SLOT(execute()));
+        o->moveToThread(qApp->thread());    // qApp was checked in the caller
+    }
     return data.result;
 }
 
@@ -186,6 +219,7 @@ QDBusConnectionPrivate *QDBusConnectionManager::connectToBus(const QString &addr
     data.type = ConnectionRequestData::ConnectToBusByAddress;
     data.busAddress = &address;
     data.name = &name;
+    data.suspendedDelivery = false;
 
     emit connectionRequested(&data);
     return data.result;
@@ -197,6 +231,7 @@ QDBusConnectionPrivate *QDBusConnectionManager::connectToPeer(const QString &add
     data.type = ConnectionRequestData::ConnectToPeerByAddress;
     data.busAddress = &address;
     data.name = &name;
+    data.suspendedDelivery = false;
 
     emit connectionRequested(&data);
     return data.result;
@@ -252,6 +287,8 @@ void QDBusConnectionManager::executeConnectionRequest(QDBusConnectionManager::Co
         // will lock in QDBusConnectionPrivate::connectRelay()
         d->setConnection(c, error);
         d->createBusService();
+        if (data->suspendedDelivery)
+            d->setDispatchEnabled(false);
     }
 }
 
@@ -456,7 +493,7 @@ QDBusConnection QDBusConnection::connectToBus(BusType type, const QString &name)
         QDBusConnectionPrivate *d = 0;
         return QDBusConnection(d);
     }
-    return QDBusConnection(_q_manager()->connectToBus(type, name));
+    return QDBusConnection(_q_manager()->connectToBus(type, name, false));
 }
 
 /*!
@@ -1232,4 +1269,6 @@ QByteArray QDBusConnection::localMachineId()
 
 QT_END_NAMESPACE
 
+#include "qdbusconnection.moc"
+
 #endif // QT_NO_DBUS
diff --git a/src/dbus/qdbusconnection_p.h b/src/dbus/qdbusconnection_p.h
index 91824c5c79c586d96940bb92178851e1efffe13a..f030a3ff8c007f3a8d65928d54551967103b92a9 100644
--- a/src/dbus/qdbusconnection_p.h
+++ b/src/dbus/qdbusconnection_p.h
@@ -169,12 +169,12 @@ public:
     // typedefs
     typedef QMultiHash<int, Watcher> WatcherHash;
     typedef QHash<int, DBusTimeout *> TimeoutHash;
-    typedef QVector<QPair<DBusTimeout *, int> > PendingTimeoutList;
+    typedef QVector<QDBusMessage> PendingMessageList;
 
     typedef QMultiHash<QString, SignalHook> SignalHookHash;
     typedef QHash<QString, QDBusMetaObject* > MetaObjectHash;
     typedef QHash<QByteArray, int> MatchRefCountHash;
-    typedef QList<QDBusPendingCallPrivate*> PendingCallList;
+    typedef QVector<QDBusPendingCallPrivate*> PendingCallList;
 
     struct WatchedServiceData {
         WatchedServiceData() : refcount(0) {}
@@ -192,6 +192,7 @@ public:
     ~QDBusConnectionPrivate();
 
     void createBusService();
+    void setDispatchEnabled(bool enable);
     void setPeer(DBusConnection *connection, const QDBusErrorInternal &error);
     void setConnection(DBusConnection *connection, const QDBusErrorInternal &error);
     void setServer(QDBusServer *object, DBusServer *server, const QDBusErrorInternal &error);
@@ -309,7 +310,7 @@ public:
     };
     WatcherHash watchers;
     TimeoutHash timeouts;
-    PendingTimeoutList timeoutsPendingAdd;
+    PendingMessageList pendingMessages;
 
     // the master lock protects our own internal state
     QReadWriteLock lock;
@@ -324,6 +325,7 @@ public:
     PendingCallList pendingCalls;
 
     bool anonymousAuthenticationAllowed;
+    bool dispatchEnabled;               // protected by the dispatch lock, not the main lock
 
 public:
     // static methods
diff --git a/src/dbus/qdbusconnectionmanager_p.h b/src/dbus/qdbusconnectionmanager_p.h
index 3f815fdcd76a9891bdd3746ee74c5220a0f21a7a..c0ab48e4ee66bc52c8345c74bfae26e425dc896f 100644
--- a/src/dbus/qdbusconnectionmanager_p.h
+++ b/src/dbus/qdbusconnectionmanager_p.h
@@ -67,7 +67,7 @@ public:
     QDBusConnectionPrivate *connection(const QString &name) const;
     void removeConnection(const QString &name);
     void setConnection(const QString &name, QDBusConnectionPrivate *c);
-    QDBusConnectionPrivate *connectToBus(QDBusConnection::BusType type, const QString &name);
+    QDBusConnectionPrivate *connectToBus(QDBusConnection::BusType type, const QString &name, bool suspendedDelivery);
     QDBusConnectionPrivate *connectToBus(const QString &address, const QString &name);
     QDBusConnectionPrivate *connectToPeer(const QString &address, const QString &name);
 
diff --git a/src/dbus/qdbuserror.cpp b/src/dbus/qdbuserror.cpp
index 40e97ae48394e8a5304c6c6010febe5a474dbc77..d6a329cfe810bbfc5bdafff41930f237cc4e05d0 100644
--- a/src/dbus/qdbuserror.cpp
+++ b/src/dbus/qdbuserror.cpp
@@ -130,11 +130,11 @@ static const int errorMessages_indices[] = {
     0,    6,   40,   76,  118,  153,  191,  231,
     273,  313,  349,  384,  421,  461,  501,  540,
     581,  617,  661,  705,  746,  789,  833,  874,
-    916,  961, 1005,   -1
+    916,  961, 1005
 };
 
 static const int errorMessages_count = sizeof errorMessages_indices /
-                                       sizeof errorMessages_indices[0] - 1;
+                                       sizeof errorMessages_indices[0];
 
 static inline const char *get(QDBusError::ErrorType code)
 {
diff --git a/src/dbus/qdbusintegrator.cpp b/src/dbus/qdbusintegrator.cpp
index c465706913f97bf2182c43081e8038972851d6c6..f6221d51b6f91c413379cd72de70991c454eefb4 100644
--- a/src/dbus/qdbusintegrator.cpp
+++ b/src/dbus/qdbusintegrator.cpp
@@ -496,6 +496,11 @@ bool QDBusConnectionPrivate::handleMessage(const QDBusMessage &amsg)
 
     if (!ref.load())
         return false;
+    if (!dispatchEnabled && !QDBusMessagePrivate::isLocal(amsg)) {
+        // queue messages only, we'll handle them later
+        pendingMessages << amsg;
+        return amsg.type() == QDBusMessage::MethodCallMessage;
+    }
 
     switch (amsg.type()) {
     case QDBusMessage::SignalMessage:
@@ -690,6 +695,20 @@ static int findSlot(const QMetaObject *mo, const QByteArray &name, int flags,
     return -1;
 }
 
+/*!
+    \internal
+    Enables or disables the delivery of incoming method calls and signals. If
+    \a enable is true, this will also cause any queued, pending messages to be
+    delivered.
+ */
+void QDBusConnectionPrivate::setDispatchEnabled(bool enable)
+{
+    QDBusDispatchLocker locker(SetDispatchEnabledAction, this);
+    dispatchEnabled = enable;
+    if (enable)
+        emit dispatchStatusChanged();
+}
+
 static QDBusCallDeliveryEvent * const DIRECT_DELIVERY = (QDBusCallDeliveryEvent *)1;
 
 QDBusCallDeliveryEvent* QDBusConnectionPrivate::prepareReply(QDBusConnectionPrivate *target,
@@ -946,7 +965,8 @@ QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *p)
     : QObject(p), ref(1), capabilities(0), mode(InvalidMode), busService(0),
       dispatchLock(QMutex::Recursive), connection(0),
       rootNode(QString(QLatin1Char('/'))),
-      anonymousAuthenticationAllowed(false)
+      anonymousAuthenticationAllowed(false),
+      dispatchEnabled(true)
 {
     static const bool threads = q_dbus_threads_init_default();
     if (::isDebugging == -1)
@@ -1066,8 +1086,17 @@ void QDBusConnectionPrivate::timerEvent(QTimerEvent *e)
 void QDBusConnectionPrivate::doDispatch()
 {
     QDBusDispatchLocker locker(DoDispatchAction, this);
-    if (mode == ClientMode || mode == PeerMode)
+    if (mode == ClientMode || mode == PeerMode) {
         while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS) ;
+        if (dispatchEnabled && !pendingMessages.isEmpty()) {
+            // dispatch previously queued messages
+            PendingMessageList::Iterator it = pendingMessages.begin();
+            PendingMessageList::Iterator end = pendingMessages.end();
+            for ( ; it != end; ++it)
+                handleMessage(qMove(*it));
+            pendingMessages.clear();
+        }
+    }
 }
 
 void QDBusConnectionPrivate::socketRead(int fd)
diff --git a/src/dbus/qdbuspendingcall.h b/src/dbus/qdbuspendingcall.h
index 3bcacffd224808ab52305622552e8b373c47a662..d7d68825be6b087d2a135f5d584f7634889f26ec 100644
--- a/src/dbus/qdbuspendingcall.h
+++ b/src/dbus/qdbuspendingcall.h
@@ -106,7 +106,7 @@ public:
     void waitForFinished();     // non-virtual override
 
 Q_SIGNALS:
-    void finished(QDBusPendingCallWatcher *self);
+    void finished(QDBusPendingCallWatcher *self = Q_NULLPTR);
 
 private:
     Q_DECLARE_PRIVATE(QDBusPendingCallWatcher)
diff --git a/src/dbus/qdbusthreaddebug_p.h b/src/dbus/qdbusthreaddebug_p.h
index eace25478d6f91c5fe32faf96b3c59c058130571..420f06261516f1c7457b3d45c6442442e343e414 100644
--- a/src/dbus/qdbusthreaddebug_p.h
+++ b/src/dbus/qdbusthreaddebug_p.h
@@ -83,7 +83,7 @@ enum ThreadAction {
     HandleObjectCallPostEventAction = 22,
     HandleObjectCallSemaphoreAction = 23,
     DoDispatchAction = 24,
-    // unused: 25,
+    SetDispatchEnabledAction = 25,
     MessageResultReceivedAction = 26,
     ActivateSignalAction = 27,
     PendingCallBlockAction = 28,
diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp
index a992ad6feabb245148611e70ca6a4dd6072092f4..6ec1eecfb1457e02da39213c4e5b6d369bbce975 100644
--- a/src/gui/image/qimage.cpp
+++ b/src/gui/image/qimage.cpp
@@ -4623,32 +4623,7 @@ QImage QImage::transformed(const QTransform &matrix, Qt::TransformationMode mode
 
     if (complex_xform || mode == Qt::SmoothTransformation) {
         if (d->format < QImage::Format_RGB32 || !hasAlphaChannel()) {
-            switch(d->format) {
-            case QImage::Format_RGB16:
-                target_format = Format_ARGB8565_Premultiplied;
-                break;
-            case QImage::Format_RGB555:
-                target_format = Format_ARGB8555_Premultiplied;
-                break;
-            case QImage::Format_RGB666:
-                target_format = Format_ARGB6666_Premultiplied;
-                break;
-            case QImage::Format_RGB444:
-                target_format = Format_ARGB4444_Premultiplied;
-                break;
-            case QImage::Format_RGBX8888:
-                target_format = Format_RGBA8888_Premultiplied;
-                break;
-            case QImage::Format_BGR30:
-                target_format = Format_A2BGR30_Premultiplied;
-                break;
-            case QImage::Format_RGB30:
-                target_format = Format_A2RGB30_Premultiplied;
-                break;
-            default:
-                target_format = Format_ARGB32_Premultiplied;
-                break;
-            }
+            target_format = qt_alphaVersion(d->format);
         }
     }
 
diff --git a/src/gui/image/qimage_conversions.cpp b/src/gui/image/qimage_conversions.cpp
index cbdcf49da7594375573f6e393d9650be9e8c8df0..cc79e73534cc6f797e1cbb35d8853be3fd7ee02f 100644
--- a/src/gui/image/qimage_conversions.cpp
+++ b/src/gui/image/qimage_conversions.cpp
@@ -2967,15 +2967,6 @@ static void qInitImageConversions()
 #endif
 }
 
-class QImageConversionsInitializer {
-public:
-    QImageConversionsInitializer()
-    {
-        qInitImageConversions();
-    }
-};
-
-// Ensure initialization if this object file is linked.
-static QImageConversionsInitializer qImageConversionsInitializer;
+Q_CONSTRUCTOR_FUNCTION(qInitImageConversions);
 
 QT_END_NAMESPACE
diff --git a/src/gui/image/qimage_p.h b/src/gui/image/qimage_p.h
index 3badda08642812a83c3a044d04f65ab16211ad4e..f9ad6c0ac0d66135afc5cd7a0896ebf2b9048825 100644
--- a/src/gui/image/qimage_p.h
+++ b/src/gui/image/qimage_p.h
@@ -161,10 +161,45 @@ inline int qt_depthForFormat(QImage::Format format)
     }
     return depth;
 }
+
 #if defined(_M_ARM)
 #pragma optimize("", on)
 #endif
 
+inline QImage::Format qt_alphaVersion(QImage::Format format)
+{
+    switch (format) {
+    case QImage::Format_RGB16:
+        return QImage::Format_ARGB8565_Premultiplied;
+    case QImage::Format_RGB555:
+        return QImage::Format_ARGB8555_Premultiplied;
+    case QImage::Format_RGB666:
+        return QImage::Format_ARGB6666_Premultiplied;
+    case QImage::Format_RGB444:
+        return QImage::Format_ARGB4444_Premultiplied;
+    case QImage::Format_RGBX8888:
+        return QImage::Format_RGBA8888_Premultiplied;
+    case QImage::Format_BGR30:
+        return QImage::Format_A2BGR30_Premultiplied;
+    case QImage::Format_RGB30:
+        return QImage::Format_A2RGB30_Premultiplied;
+    default:
+        break;
+    }
+    return QImage::Format_ARGB32_Premultiplied;
+}
+
+inline QImage::Format qt_alphaVersionForPainting(QImage::Format format)
+{
+    QImage::Format toFormat = qt_alphaVersion(format);
+#if defined(__ARM_NEON__) || defined(__SSE2__)
+    // If we are switching depth anyway and we have optimized ARGB32PM routines, upgrade to that.
+    if (qt_depthForFormat(format) != qt_depthForFormat(toFormat))
+        toFormat = QImage::Format_ARGB32_Premultiplied;
+#endif
+    return toFormat;
+}
+
 QT_END_NAMESPACE
 
 #endif // QIMAGE_P_H
diff --git a/src/gui/image/qpixmap_raster.cpp b/src/gui/image/qpixmap_raster.cpp
index a2b84b358e2d21ba4de99141e8bd027386b4c74f..bbdf77355e1a4ea5105d05f7a5a3981bcd20421b 100644
--- a/src/gui/image/qpixmap_raster.cpp
+++ b/src/gui/image/qpixmap_raster.cpp
@@ -178,20 +178,7 @@ void QRasterPlatformPixmap::fill(const QColor &color)
         int alpha = color.alpha();
         if (alpha != 255) {
             if (!image.hasAlphaChannel()) {
-                QImage::Format toFormat;
-#if !(defined(__ARM_NEON__) || defined(__SSE2__))
-                if (image.format() == QImage::Format_RGB16)
-                    toFormat = QImage::Format_ARGB8565_Premultiplied;
-                else if (image.format() == QImage::Format_RGB666)
-                    toFormat = QImage::Format_ARGB6666_Premultiplied;
-                else if (image.format() == QImage::Format_RGB555)
-                    toFormat = QImage::Format_ARGB8555_Premultiplied;
-                else if (image.format() == QImage::Format_RGB444)
-                    toFormat = QImage::Format_ARGB4444_Premultiplied;
-                else
-#endif
-                    toFormat = QImage::Format_ARGB32_Premultiplied;
-
+                QImage::Format toFormat = qt_alphaVersionForPainting(image.format());
                 if (!image.isNull() && qt_depthForFormat(image.format()) == qt_depthForFormat(toFormat)) {
                     image.detach();
                     image.d->format = toFormat;
@@ -314,17 +301,7 @@ void QRasterPlatformPixmap::createPixmapForImage(QImage &sourceImage, Qt::ImageC
                     : QImage::Format_RGB32;
         } else {
             QImage::Format opaqueFormat = QNativeImage::systemFormat();
-            QImage::Format alphaFormat = QImage::Format_ARGB32_Premultiplied;
-
-#if !defined(__ARM_NEON__) && !defined(__SSE2__)
-            switch (opaqueFormat) {
-            case QImage::Format_RGB16:
-                alphaFormat = QImage::Format_ARGB8565_Premultiplied;
-                break;
-            default: // We don't care about the others...
-                break;
-            }
-#endif
+            QImage::Format alphaFormat = qt_alphaVersionForPainting(opaqueFormat);
 
             if (!sourceImage.hasAlphaChannel()) {
                 format = opaqueFormat;
diff --git a/src/gui/kernel/qguiapplication.cpp b/src/gui/kernel/qguiapplication.cpp
index fd99f9383871104d05bcadac38c1ddc82799735f..a387b3ac7672c8d5a2bc3c9e2d726ac7ba261c7c 100644
--- a/src/gui/kernel/qguiapplication.cpp
+++ b/src/gui/kernel/qguiapplication.cpp
@@ -964,18 +964,38 @@ qreal QGuiApplication::devicePixelRatio() const
 */
 QWindow *QGuiApplication::topLevelAt(const QPoint &pos)
 {
-    QList<QScreen *> screens = QGuiApplication::screens();
-    QList<QScreen *>::const_iterator screen = screens.constBegin();
-    QList<QScreen *>::const_iterator end = screens.constEnd();
-
-    while (screen != end) {
-        if ((*screen)->geometry().contains(pos)) {
-            const QPoint devicePosition = QHighDpi::toNativePixels(pos, *screen);
-            return (*screen)->handle()->topLevelAt(devicePosition);
+    const QList<QScreen *> screens = QGuiApplication::screens();
+    if (!screens.isEmpty()) {
+        const QList<QScreen *> primaryScreens = screens.first()->virtualSiblings();
+        QScreen *windowScreen = Q_NULLPTR;
+
+        // Find the window on the primary virtual desktop first
+        foreach (QScreen *screen, primaryScreens) {
+            if (screen->geometry().contains(pos)) {
+                windowScreen = screen;
+                break;
+            }
+        }
+
+        // If the window is not found on primary virtual desktop, find it on all screens
+        // except the first which was for sure in the previous loop. Some other screens
+        // may repeat. Find only when there is more than one virtual desktop.
+        if (!windowScreen && screens.count() != primaryScreens.count()) {
+            for (int i = 1; i < screens.size(); ++i) {
+                QScreen *screen = screens[i];
+                if (screen->geometry().contains(pos)) {
+                    windowScreen = screen;
+                    break;
+                }
+            }
+        }
+
+        if (windowScreen) {
+            const QPoint devicePosition = QHighDpi::toNativePixels(pos, windowScreen);
+            return windowScreen->handle()->topLevelAt(devicePosition);
         }
-        ++screen;
     }
-    return 0;
+    return Q_NULLPTR;
 }
 
 /*!
@@ -2077,10 +2097,12 @@ void QGuiApplicationPrivate::processWindowStateChangedEvent(QWindowSystemInterfa
 void QGuiApplicationPrivate::processWindowScreenChangedEvent(QWindowSystemInterfacePrivate::WindowScreenChangedEvent *wse)
 {
     if (QWindow *window  = wse->window.data()) {
-        if (QScreen *screen = wse->screen.data())
-            window->d_func()->setTopLevelScreen(screen, false /* recreate */);
-        else // Fall back to default behavior, and try to find some appropriate screen
-            window->setScreen(0);
+        if (window->isTopLevel()) {
+            if (QScreen *screen = wse->screen.data())
+                window->d_func()->setTopLevelScreen(screen, false /* recreate */);
+            else // Fall back to default behavior, and try to find some appropriate screen
+                window->setScreen(0);
+        }
         // we may have changed scaling, so trigger resize event if needed
         if (window->handle()) {
             QWindowSystemInterfacePrivate::GeometryChangeEvent gce(window, QHighDpi::fromNativePixels(window->handle()->geometry(), window), QRect());
diff --git a/src/gui/kernel/qhighdpiscaling.cpp b/src/gui/kernel/qhighdpiscaling.cpp
index a3201aa23f780f61ade9bcbb92ef956665d77400..b0ef2a284fea0da4e165ea6003d5f463d80e07e4 100644
--- a/src/gui/kernel/qhighdpiscaling.cpp
+++ b/src/gui/kernel/qhighdpiscaling.cpp
@@ -173,7 +173,7 @@ static inline qreal initialGlobalScaleFactor()
         include X11, Windows, and Android.
 
         There are two APIs for enabling or disabling this behavior:
-            - The QT_AUTO_SCALE_FACTOR environment variable.
+            - The QT_AUTO_SCREEN_SCALE_FACTOR environment variable.
             - The AA_EnableHighDpiScaling and AA_DisableHighDpiScaling
               application attributes
 
diff --git a/src/gui/kernel/qopenglcontext.cpp b/src/gui/kernel/qopenglcontext.cpp
index 85d05959defafde741783a68225027f9e1922b5a..3c033ea39e1998f859016dc566861da9a5988e20 100644
--- a/src/gui/kernel/qopenglcontext.cpp
+++ b/src/gui/kernel/qopenglcontext.cpp
@@ -1459,11 +1459,11 @@ void QOpenGLContextGroupPrivate::deletePendingResources(QOpenGLContext *ctx)
 {
     QMutexLocker locker(&m_mutex);
 
-    QList<QOpenGLSharedResource *> pending = m_pendingDeletion;
+    const QList<QOpenGLSharedResource *> pending = m_pendingDeletion;
     m_pendingDeletion.clear();
 
-    QList<QOpenGLSharedResource *>::iterator it = pending.begin();
-    QList<QOpenGLSharedResource *>::iterator end = pending.end();
+    QList<QOpenGLSharedResource *>::const_iterator it = pending.begin();
+    QList<QOpenGLSharedResource *>::const_iterator end = pending.end();
     while (it != end) {
         (*it)->freeResource(ctx);
         delete *it;
diff --git a/src/gui/kernel/qshortcutmap.cpp b/src/gui/kernel/qshortcutmap.cpp
index 9c8218b7b54800c38093dbe2bae668cd464c7924..3941f7233f440307629d124ae76db91974f87a4d 100644
--- a/src/gui/kernel/qshortcutmap.cpp
+++ b/src/gui/kernel/qshortcutmap.cpp
@@ -336,12 +336,16 @@ bool QShortcutMap::tryShortcut(QKeyEvent *e)
         // For a partial match we don't know yet if we will handle the shortcut
         // but we need to say we did, so that we get the follow-up key-presses.
         return true;
-    case QKeySequence::ExactMatch:
+    case QKeySequence::ExactMatch: {
+        // Save number of identical matches before dispatching
+        // to keep QShortcutMap and tryShortcut reentrant.
+        const int identicalMatches = d->identicals.count();
         resetState();
         dispatchEvent(e);
         // If there are no identicals we've only found disabled shortcuts, and
         // shouldn't say that we handled the event.
-        return d->identicals.count() > 0;
+        return identicalMatches > 0;
+    }
     default:
         Q_UNREACHABLE();
     }
diff --git a/src/gui/kernel/qwindow.cpp b/src/gui/kernel/qwindow.cpp
index e728d32e4b28e5a27629b904944f08e755e66b01..21734f16198d6f1799e86ecb7c3f1d1310c53868 100644
--- a/src/gui/kernel/qwindow.cpp
+++ b/src/gui/kernel/qwindow.cpp
@@ -609,6 +609,8 @@ void QWindow::setParent(QWindow *parent)
     }
 
     QObject::setParent(parent);
+    d->parentWindow = parent;
+
     if (parent)
         d->disconnectFromScreen();
     else
@@ -622,8 +624,6 @@ void QWindow::setParent(QWindow *parent)
         }
     }
 
-    d->parentWindow = parent;
-
     QGuiApplicationPrivate::updateBlockedStatus(this);
 }
 
diff --git a/src/gui/kernel/qwindowsysteminterface.cpp b/src/gui/kernel/qwindowsysteminterface.cpp
index d70e81483801fc23c02fe9a3ed635107f83413a3..16c0aeb27556fa9398d3e85886d614da16ca03a6 100644
--- a/src/gui/kernel/qwindowsysteminterface.cpp
+++ b/src/gui/kernel/qwindowsysteminterface.cpp
@@ -275,8 +275,10 @@ bool QWindowSystemInterface::handleExtendedKeyEvent(QWindow *tlw, ulong timestam
                                                     const QString& text, bool autorep,
                                                     ushort count, bool tryShortcutOverride)
 {
-    if (tryShortcutOverride && type == QEvent::KeyPress && QWindowSystemInterface::handleShortcutEvent(tlw, timestamp, key, modifiers, 0, 0, 0, text, autorep, count))
+    if (tryShortcutOverride && type == QEvent::KeyPress && QWindowSystemInterface::handleShortcutEvent(tlw,
+            timestamp, key, modifiers, nativeScanCode, nativeVirtualKey, nativeModifiers, text, autorep, count)) {
         return true;
+    }
 
     QWindowSystemInterfacePrivate::KeyEvent * e =
             new QWindowSystemInterfacePrivate::KeyEvent(tlw, timestamp, type, key, modifiers,
diff --git a/src/gui/opengl/qopengltexture.cpp b/src/gui/opengl/qopengltexture.cpp
index 301b2ad13dc985cf218586a48ef87569ea022f95..02dee5a90a98318b466ed252bda33aa520a21368 100644
--- a/src/gui/opengl/qopengltexture.cpp
+++ b/src/gui/opengl/qopengltexture.cpp
@@ -97,9 +97,11 @@ QOpenGLTexturePrivate::QOpenGLTexturePrivate(QOpenGLTexture::Target textureTarge
         break;
     case QOpenGLTexture::TargetCubeMap:
         bindingTarget = QOpenGLTexture::BindingTargetCubeMap;
+        faces = 6;
         break;
     case QOpenGLTexture::TargetCubeMapArray:
         bindingTarget = QOpenGLTexture::BindingTargetCubeMapArray;
+        faces = 6;
         break;
     case QOpenGLTexture::Target2DMultisample:
         bindingTarget = QOpenGLTexture::BindingTarget2DMultisample;
@@ -175,7 +177,7 @@ bool QOpenGLTexturePrivate::create()
 
 void QOpenGLTexturePrivate::destroy()
 {
-    if (!context) {
+    if (!textureId) {
         // not created or already destroyed
         return;
     }
diff --git a/src/gui/opengl/qopengltexture_p.h b/src/gui/opengl/qopengltexture_p.h
index ac9d44db421a99985bf1832a37a6a06fd5f6555c..40ceb1936c9680c103c89e3b063f691e4af0fec4 100644
--- a/src/gui/opengl/qopengltexture_p.h
+++ b/src/gui/opengl/qopengltexture_p.h
@@ -156,7 +156,6 @@ public:
     bool autoGenerateMipMaps;
     bool storageAllocated;
 
-    QPair<int, int> glVersion;
     QOpenGLTextureHelper *texFuncs;
 
     QOpenGLTexture::Features features;
diff --git a/src/gui/opengl/qopengltexturehelper.cpp b/src/gui/opengl/qopengltexturehelper.cpp
index c5fa2163b3f7c5f7c9bca53f80e5aae916954917..1ef0b3ef17159712e0952e8735f6f001fa3925db 100644
--- a/src/gui/opengl/qopengltexturehelper.cpp
+++ b/src/gui/opengl/qopengltexturehelper.cpp
@@ -453,260 +453,192 @@ void QOpenGLTextureHelper::dsa_CompressedTextureImage3D(GLuint texture, GLenum t
     CompressedTextureImage3DEXT(texture, target, level, internalFormat, width, height, depth, border, imageSize, bits);
 }
 
+namespace {
+
+class TextureBinder
+{
+public:
+    TextureBinder(QOpenGLTextureHelper *textureFunctions, GLuint texture, GLenum target, GLenum bindingTarget)
+    : m_textureFunctions(textureFunctions)
+    {
+        // For cubemaps we can't use the standard DSA emulation as it is illegal to
+        // try to bind a texture to one of the cubemap face targets. So we force the
+        // target and binding target to the cubemap values in this case.
+        switch (target) {
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+            bindingTarget = GL_TEXTURE_BINDING_CUBE_MAP;
+            m_target = GL_TEXTURE_CUBE_MAP;
+            break;
+
+        default:
+            m_target = target;
+            break;
+        }
+
+        m_textureFunctions->glGetIntegerv(bindingTarget, &m_oldTexture);
+        m_textureFunctions->glBindTexture(m_target, texture);
+    }
+
+    ~TextureBinder()
+    {
+        m_textureFunctions->glBindTexture(m_target, m_oldTexture);
+    }
+
+private:
+    QOpenGLTextureHelper *m_textureFunctions;
+    GLenum m_target;
+    GLint m_oldTexture;
+};
+
+} // namespace
+
 void QOpenGLTextureHelper::qt_TextureParameteri(GLuint texture, GLenum target, GLenum bindingTarget, GLenum pname, GLint param)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexParameteri(target, pname, param);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureParameteriv(GLuint texture, GLenum target, GLenum bindingTarget, GLenum pname, const GLint *params)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexParameteriv(target, pname, params);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureParameterf(GLuint texture, GLenum target, GLenum bindingTarget, GLenum pname, GLfloat param)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexParameterf(target, pname, param);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureParameterfv(GLuint texture, GLenum target, GLenum bindingTarget, GLenum pname, const GLfloat *params)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexParameterfv(target, pname, params);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_GenerateTextureMipmap(GLuint texture, GLenum target, GLenum bindingTarget)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glGenerateMipmap(target);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureStorage3D(GLuint texture, GLenum target, GLenum bindingTarget, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexStorage3D(target, levels, internalFormat, width, height, depth);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureStorage2D(GLuint texture, GLenum target, GLenum bindingTarget, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexStorage2D(target, levels, internalFormat, width, height);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureStorage1D(GLuint texture, GLenum target, GLenum bindingTarget, GLsizei levels, GLenum internalFormat, GLsizei width)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexStorage1D(target, levels, internalFormat, width);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureStorage3DMultisample(GLuint texture, GLenum target, GLenum bindingTarget, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexStorage3DMultisample(target, samples, internalFormat, width, height, depth, fixedSampleLocations);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureStorage2DMultisample(GLuint texture, GLenum target, GLenum bindingTarget, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexStorage2DMultisample(target, samples, internalFormat, width, height, fixedSampleLocations);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureImage3D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexImage3D(target, level, internalFormat, width, height, depth, border, format, type, pixels);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureImage2D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
 {
-    // For cubemaps we can't use the standard DSA emulation as it is illegal to
-    // try to bind a texture to one of the cubemap face targets. So we force the
-    // target and binding target to the cubemap values in this case.
-    GLint oldTexture;
-
-    switch (target) {
-    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
-    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
-    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
-    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
-    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
-    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
-        glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &oldTexture);
-        glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
-        glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels);
-        glBindTexture(GL_TEXTURE_CUBE_MAP, oldTexture);
-        break;
-
-    default:
-        glGetIntegerv(bindingTarget, &oldTexture);
-        glBindTexture(target, texture);
-        glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels);
-        glBindTexture(target, oldTexture);
-        break;
-    }
+    TextureBinder binder(this, texture, target, bindingTarget);
+    glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels);
 }
 
 void QOpenGLTextureHelper::qt_TextureImage1D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLenum internalFormat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexImage1D(target, level, internalFormat, width, border, format, type, pixels);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureSubImage3D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureSubImage2D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)
 {
-    // For cubemaps we can't use the standard DSA emulation as it is illegal to
-    // try to bind a texture to one of the cubemap face targets. So we force the
-    // target and binding target to the cubemap values in this case.
-    GLint oldTexture;
-
-    switch (target) {
-    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
-    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
-    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
-    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
-    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
-    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
-        glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &oldTexture);
-        glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
-        glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
-        glBindTexture(GL_TEXTURE_CUBE_MAP, oldTexture);
-        break;
-
-    default:
-        glGetIntegerv(bindingTarget, &oldTexture);
-        glBindTexture(target, texture);
-        glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
-        glBindTexture(target, oldTexture);
-        break;
-    }
+    TextureBinder binder(this, texture, target, bindingTarget);
+    glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
 }
 
 void QOpenGLTextureHelper::qt_TextureSubImage1D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexSubImage1D(target, level, xoffset, width, format, type, pixels);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureImage3DMultisample(GLuint texture, GLenum target, GLenum bindingTarget, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexImage3DMultisample(target, samples, internalFormat, width, height, depth, fixedSampleLocations);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_TextureImage2DMultisample(GLuint texture, GLenum target, GLenum bindingTarget, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glTexImage2DMultisample(target, samples, internalFormat, width, height, fixedSampleLocations);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_CompressedTextureSubImage1D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glCompressedTexSubImage1D(target, level, xoffset, width, format, imageSize, bits);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_CompressedTextureSubImage2D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, bits);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_CompressedTextureSubImage3D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *bits)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, bits);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_CompressedTextureImage1D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLenum internalFormat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *bits)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glCompressedTexImage1D(target, level, internalFormat, width, border, imageSize, bits);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_CompressedTextureImage2D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glCompressedTexImage2D(target, level, internalFormat, width, height, border, imageSize, bits);
-    glBindTexture(target, oldTexture);
 }
 
 void QOpenGLTextureHelper::qt_CompressedTextureImage3D(GLuint texture, GLenum target, GLenum bindingTarget, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits)
 {
-    GLint oldTexture;
-    glGetIntegerv(bindingTarget, &oldTexture);
-    glBindTexture(target, texture);
+    TextureBinder binder(this, texture, target, bindingTarget);
     glCompressedTexImage3D(target, level, internalFormat, width, height, depth, border, imageSize, bits);
-    glBindTexture(target, oldTexture);
 }
 
 QT_END_NAMESPACE
diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp
index bf7a50e227b96c9d2afd1797d6c808a735aeddad..87ceb9a89dce16ccc66191a92416af393a90b9c4 100644
--- a/src/gui/painting/qdrawhelper.cpp
+++ b/src/gui/painting/qdrawhelper.cpp
@@ -6323,8 +6323,13 @@ void qt_memfill32(quint32 *dest, quint32 color, int count)
 template<QtPixelOrder> const uint *QT_FASTCALL convertA2RGB30PMFromARGB32PM_sse4(uint *buffer, const uint *src, int count, const QPixelLayout *, const QRgb *);
 #endif
 
+extern void qInitBlendFunctions();
+
 static void qInitDrawhelperFunctions()
 {
+    // Set up basic blend function tables.
+    qInitBlendFunctions();
+
 #ifdef __SSE2__
     qDrawHelper[QImage::Format_RGB32].bitmapBlit = qt_bitmapblit32_sse2;
     qDrawHelper[QImage::Format_ARGB32].bitmapBlit = qt_bitmapblit32_sse2;
@@ -6518,19 +6523,7 @@ static void qInitDrawhelperFunctions()
 #endif // QT_COMPILER_SUPPORTS_MIPS_DSP || QT_COMPILER_SUPPORTS_MIPS_DSPR2
 }
 
-extern void qInitBlendFunctions();
-class DrawHelperInitializer {
-public:
-    DrawHelperInitializer()
-    {
-        // Set up basic blend function tables.
-        qInitBlendFunctions();
-        // Set up architecture optimized methods for the current machine.
-        qInitDrawhelperFunctions();
-    }
-};
-
 // Ensure initialization if this object file is linked.
-static DrawHelperInitializer drawHelperInitializer;
+Q_CONSTRUCTOR_FUNCTION(qInitDrawhelperFunctions);
 
 QT_END_NAMESPACE
diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp
index 207e31d91ace60b4f38cd50f5fae063fda9466ac..05ccff5de001a3d607ce49ef35f3353c497d325b 100644
--- a/src/gui/painting/qpaintengine_raster.cpp
+++ b/src/gui/painting/qpaintengine_raster.cpp
@@ -4150,7 +4150,7 @@ public:
     inline const QRgba64 *getBuffer(const QGradient &gradient, int opacity) {
         quint64 hash_val = 0;
 
-        QGradientStops stops = gradient.stops();
+        const QGradientStops stops = gradient.stops();
         for (int i = 0; i < stops.size() && i <= 2; i++)
             hash_val += stops[i].second.rgba64();
 
@@ -4193,7 +4193,7 @@ protected:
 
 void QGradientCache::generateGradientColorTable(const QGradient& gradient, QRgba64 *colorTable, int size, int opacity) const
 {
-    QGradientStops stops = gradient.stops();
+    const QGradientStops stops = gradient.stops();
     int stopCount = stops.count();
     Q_ASSERT(stopCount > 0);
 
diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp
index e80c0130c3ff1714b2df5c3847a7c651a67e66e1..5dcab11f0a3806e90dc598ff610cddc20551da50 100644
--- a/src/gui/painting/qpainter.cpp
+++ b/src/gui/painting/qpainter.cpp
@@ -3154,7 +3154,7 @@ void QPainter::shear(qreal sh, qreal sv)
 /*!
     \fn void QPainter::rotate(qreal angle)
 
-    Rotates the coordinate system clockwise. The given \a angle parameter uses degree unit.
+    Rotates the coordinate system clockwise. The given \a angle parameter is in degrees.
 
     \sa setWorldTransform(), {QPainter#Coordinate Transformations}{Coordinate Transformations}
 */
diff --git a/src/gui/painting/qplatformbackingstore.cpp b/src/gui/painting/qplatformbackingstore.cpp
index cda2446a5ed6766c3b3321be7aba4fb5528c6e07..4b725fc79fac9a444ed3c02b4e64cef30fb9dd7f 100644
--- a/src/gui/painting/qplatformbackingstore.cpp
+++ b/src/gui/painting/qplatformbackingstore.cpp
@@ -371,17 +371,13 @@ void QPlatformBackingStore::composeAndFlush(QWindow *window, const QRegion &regi
     if (textureId) {
         if (d_ptr->needsSwizzle)
             d_ptr->blitter->setSwizzleRB(true);
-        // offset is usually (0, 0) unless we have native child widgets.
-        if (offset.isNull()) {
-            d_ptr->blitter->blit(textureId, QMatrix4x4(), origin);
-        } else {
-            // The backingstore is for the entire tlw. offset tells the position of the native child in the tlw.
-            const QRect srcRect = toBottomLeftRect(deviceWindowRect.translated(offset), d_ptr->textureSize.height());
-            const QMatrix3x3 source = QOpenGLTextureBlitter::sourceTransform(deviceRect(srcRect, window),
-                                                                             d_ptr->textureSize,
-                                                                             origin);
-            d_ptr->blitter->blit(textureId, QMatrix4x4(), source);
-        }
+        // The backingstore is for the entire tlw.
+        // In case of native children offset tells the position relative to the tlw.
+        const QRect srcRect = toBottomLeftRect(deviceWindowRect.translated(offset), d_ptr->textureSize.height());
+        const QMatrix3x3 source = QOpenGLTextureBlitter::sourceTransform(deviceRect(srcRect, window),
+                                                                         d_ptr->textureSize,
+                                                                         origin);
+        d_ptr->blitter->blit(textureId, QMatrix4x4(), source);
         if (d_ptr->needsSwizzle)
             d_ptr->blitter->setSwizzleRB(false);
     }
diff --git a/src/gui/text/qfontdatabase.cpp b/src/gui/text/qfontdatabase.cpp
index 80908122a89d11a1f3e5152bfe7e6cf56894693b..1b9852c20c22bd8468f1d91a69773daccc5a9539 100644
--- a/src/gui/text/qfontdatabase.cpp
+++ b/src/gui/text/qfontdatabase.cpp
@@ -47,6 +47,7 @@
 #include <qpa/qplatformfontdatabase.h>
 #include <qpa/qplatformtheme.h>
 
+#include <QtCore/qcache.h>
 #include <QtCore/qmath.h>
 
 #include <stdlib.h>
@@ -413,11 +414,45 @@ void QtFontFamily::ensurePopulated()
     Q_ASSERT_X(populated, Q_FUNC_INFO, qPrintable(name));
 }
 
+
+struct FallbacksCacheKey {
+    QString family;
+    QFont::Style style;
+    QFont::StyleHint styleHint;
+    QChar::Script script;
+};
+
+inline bool operator==(const FallbacksCacheKey &lhs, const FallbacksCacheKey &rhs) Q_DECL_NOTHROW
+{
+    return lhs.script == rhs.script &&
+            lhs.styleHint == rhs.styleHint &&
+            lhs.style == rhs.style &&
+            lhs.family == rhs.family;
+}
+
+inline bool operator!=(const FallbacksCacheKey &lhs, const FallbacksCacheKey &rhs) Q_DECL_NOTHROW
+{
+    return !operator==(lhs, rhs);
+}
+
+inline uint qHash(const FallbacksCacheKey &key, uint seed = 0) Q_DECL_NOTHROW
+{
+    QtPrivate::QHashCombine hash;
+    seed = hash(seed, key.family);
+    seed = hash(seed, int(key.style));
+    seed = hash(seed, int(key.styleHint));
+    seed = hash(seed, int(key.script));
+    return seed;
+}
+
+
 class QFontDatabasePrivate
 {
 public:
     QFontDatabasePrivate()
-        : count(0), families(0), reregisterAppFonts(false)
+        : count(0), families(0),
+          fallbacksCache(64),
+          reregisterAppFonts(false)
     { }
 
     ~QFontDatabasePrivate() {
@@ -443,6 +478,7 @@ public:
     int count;
     QtFontFamily **families;
 
+    QCache<FallbacksCacheKey, QStringList> fallbacksCache;
 
 
     struct ApplicationFont {
@@ -461,6 +497,8 @@ public:
 void QFontDatabasePrivate::invalidate()
 {
     QFontCache::instance()->clear();
+
+    fallbacksCache.clear();
     free();
     QGuiApplicationPrivate::platformIntegration()->fontDatabase()->invalidate();
     emit static_cast<QGuiApplication *>(QCoreApplication::instance())->fontDatabaseChanged();
@@ -680,8 +718,10 @@ Q_GLOBAL_STATIC_WITH_ARGS(QMutex, fontDatabaseMutex, (QMutex::Recursive))
 void qt_cleanupFontDatabase()
 {
     QFontDatabasePrivate *db = privateDb();
-    if (db)
+    if (db) {
+        db->fallbacksCache.clear();
         db->free();
+    }
 }
 
 // used in qfontengine_x11.cpp
@@ -800,9 +840,15 @@ QStringList QPlatformFontDatabase::fallbacksForFamily(const QString &family, QFo
 
 QStringList qt_fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script)
 {
+    QFontDatabasePrivate *db = privateDb();
+
+    const FallbacksCacheKey cacheKey = { family, style, styleHint, script };
+
+    if (const QStringList *fallbacks = db->fallbacksCache.object(cacheKey))
+        return *fallbacks;
+
     // make sure that the db has all fallback families
     QStringList retList = QGuiApplicationPrivate::platformIntegration()->fontDatabase()->fallbacksForFamily(family,style,styleHint,script);
-    QFontDatabasePrivate *db = privateDb();
 
     QStringList::iterator i;
     for (i = retList.begin(); i != retList.end(); ++i) {
@@ -818,6 +864,9 @@ QStringList qt_fallbacksForFamily(const QString &family, QFont::Style style, QFo
             --i;
         }
     }
+
+    db->fallbacksCache.insert(cacheKey, new QStringList(retList));
+
     return retList;
 }
 
diff --git a/src/gui/text/qzip.cpp b/src/gui/text/qzip.cpp
index be002167cbe7571a522e4dfdcc0499d71cd91baa..31ef8f87bea40259d55aeba8ba8fca632b356dcc 100644
--- a/src/gui/text/qzip.cpp
+++ b/src/gui/text/qzip.cpp
@@ -243,11 +243,11 @@ static QFile::Permissions modeToPermissions(quint32 mode)
 static quint32 permissionsToMode(QFile::Permissions perms)
 {
     quint32 mode = 0;
-    if (mode & (QFile::ReadOwner | QFile::ReadUser))
+    if (perms & (QFile::ReadOwner | QFile::ReadUser))
         mode |= UnixFileAttributes::ReadUser;
-    if (mode & (QFile::WriteOwner | QFile::WriteUser))
+    if (perms & (QFile::WriteOwner | QFile::WriteUser))
         mode |= UnixFileAttributes::WriteUser;
-    if (mode & (QFile::ExeOwner | QFile::ExeUser))
+    if (perms & (QFile::ExeOwner | QFile::ExeUser))
         mode |= UnixFileAttributes::WriteUser;
     if (perms & QFile::ReadGroup)
         mode |= UnixFileAttributes::ReadGroup;
diff --git a/src/network/access/qnetworkreplyhttpimpl.cpp b/src/network/access/qnetworkreplyhttpimpl.cpp
index ad8a5321b46e6ebd8242d5a5fddb41914ba6274c..04d391a14c9189dc1cfdd18207b51e9e54cdb312 100644
--- a/src/network/access/qnetworkreplyhttpimpl.cpp
+++ b/src/network/access/qnetworkreplyhttpimpl.cpp
@@ -1585,7 +1585,7 @@ QNetworkCacheMetaData QNetworkReplyHttpImplPrivate::fetchCacheMetaData(const QNe
         QByteArray maxAge = cacheControl.value("max-age");
         if (!maxAge.isEmpty()) {
             checkExpired = false;
-            QDateTime dt = QDateTime::currentDateTime();
+            QDateTime dt = QDateTime::currentDateTimeUtc();
             dt = dt.addSecs(maxAge.toInt());
             metaData.setExpirationDate(dt);
         }
diff --git a/src/network/kernel/kernel.pri b/src/network/kernel/kernel.pri
index 7c5038121bd180a79c3754c2c0ebdc82c5464b69..75029a9ba56387f082933fc2c5af6a2fe8051671 100644
--- a/src/network/kernel/kernel.pri
+++ b/src/network/kernel/kernel.pri
@@ -38,16 +38,16 @@ android {
 }
 
 win32: {
+    SOURCES += kernel/qhostinfo_win.cpp
+
     !winrt {
         SOURCES += kernel/qdnslookup_win.cpp \
-                   kernel/qhostinfo_win.cpp \
                    kernel/qnetworkinterface_win.cpp
         LIBS_PRIVATE += -ldnsapi -liphlpapi
         DEFINES += WINVER=0x0600 _WIN32_WINNT=0x0600
 
     } else {
         SOURCES += kernel/qdnslookup_winrt.cpp \
-                   kernel/qhostinfo_winrt.cpp \
                    kernel/qnetworkinterface_winrt.cpp
     }
 }
diff --git a/src/network/kernel/qdnslookup_winrt.cpp b/src/network/kernel/qdnslookup_winrt.cpp
index 8c6f9bfda5c24a60dcb17e27506203688350d5f0..8be63f1846634e2540ea87c037cc29d66a966c92 100644
--- a/src/network/kernel/qdnslookup_winrt.cpp
+++ b/src/network/kernel/qdnslookup_winrt.cpp
@@ -33,6 +33,7 @@
 
 #include "qdnslookup_p.h"
 
+#include <qfunctions_winrt.h>
 #include <qurl.h>
 #include <qdebug.h>
 
@@ -50,6 +51,8 @@ using namespace ABI::Windows::Networking;
 using namespace ABI::Windows::Networking::Connectivity;
 using namespace ABI::Windows::Networking::Sockets;
 
+#define E_NO_SUCH_HOST 0x80072af9
+
 QT_BEGIN_NAMESPACE
 
 void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestName, const QHostAddress &nameserver, QDnsLookupReply *reply)
@@ -83,40 +86,47 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
     }
     ComPtr<IHostName> host;
     HStringReference hostNameRef((const wchar_t*)aceHostname.utf16());
-    hostnameFactory->CreateHostName(hostNameRef.Get(), &host);
+    hr = hostnameFactory->CreateHostName(hostNameRef.Get(), &host);
+    Q_ASSERT_SUCCEEDED(hr);
 
     ComPtr<IDatagramSocketStatics> datagramSocketStatics;
-    GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);
+    hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);
+    Q_ASSERT_SUCCEEDED(hr);
 
     ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op;
-    datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
+    hr = datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
                                                  HString::MakeReference(L"0").Get(),
                                                  &op);
+    Q_ASSERT_SUCCEEDED(hr);
 
     ComPtr<IVectorView<EndpointPair *>> endpointPairs;
-    hr = op->GetResults(&endpointPairs);
-    int waitCount = 0;
-    while (hr == E_ILLEGAL_METHOD_CALL) {
-        WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE);
-        hr = op->GetResults(&endpointPairs);
-        if (++waitCount > 1200) // Wait for 1 minute max
-            return;
+    hr = QWinRTFunctions::await(op, endpointPairs.GetAddressOf(), QWinRTFunctions::YieldThread, 60 * 1000);
+    if (hr == E_NO_SUCH_HOST || !endpointPairs) {
+        reply->error = QDnsLookup::NotFoundError;
+        reply->errorString = tr("Host %1 could not be found.").arg(aceHostname);
+        return;
     }
-
-    if (!endpointPairs)
+    if (FAILED(hr)) {
+        reply->error = QDnsLookup::ServerFailureError;
+        reply->errorString = tr("Unknown error");
         return;
+    }
 
     unsigned int size;
-    endpointPairs->get_Size(&size);
+    hr = endpointPairs->get_Size(&size);
+    Q_ASSERT_SUCCEEDED(hr);
     // endpoint pairs might contain duplicates so we temporarily store addresses in a QSet
     QSet<QHostAddress> addresses;
     for (unsigned int i = 0; i < size; ++i) {
         ComPtr<IEndpointPair> endpointpair;
-        endpointPairs->GetAt(i, &endpointpair);
+        hr = endpointPairs->GetAt(i, &endpointpair);
+        Q_ASSERT_SUCCEEDED(hr);
         ComPtr<IHostName> remoteHost;
-        endpointpair->get_RemoteHostName(&remoteHost);
+        hr = endpointpair->get_RemoteHostName(&remoteHost);
+        Q_ASSERT_SUCCEEDED(hr);
         HostNameType type;
-        remoteHost->get_Type(&type);
+        hr = remoteHost->get_Type(&type);
+        Q_ASSERT_SUCCEEDED(hr);
         if (type == HostNameType_Bluetooth || type == HostNameType_DomainName
                 || (requestType != QDnsLookup::ANY
                 && ((type == HostNameType_Ipv4 && requestType == QDnsLookup::AAAA)
@@ -124,7 +134,8 @@ void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestN
             continue;
 
         HString name;
-        remoteHost->get_CanonicalName(name.GetAddressOf());
+        hr = remoteHost->get_CanonicalName(name.GetAddressOf());
+        Q_ASSERT_SUCCEEDED(hr);
         UINT32 length;
         PCWSTR rawString = name.GetRawBuffer(&length);
         addresses.insert(QHostAddress(QString::fromWCharArray(rawString, length)));
diff --git a/src/network/kernel/qhostaddress.cpp b/src/network/kernel/qhostaddress.cpp
index 249b1840a50e1247229771b2ee996d460d999685..6e588586587b1614dbe598d0684c1f238b295d74 100644
--- a/src/network/kernel/qhostaddress.cpp
+++ b/src/network/kernel/qhostaddress.cpp
@@ -420,7 +420,7 @@ void QNetmaskAddress::setPrefixLength(QAbstractSocket::NetworkLayerProtocol prot
     \value Any The dual stack any-address. A socket bound with this address will listen on both IPv4 and IPv6 interfaces.
 */
 
-/*!  Constructs a host address object with the IP address 0.0.0.0.
+/*!  Constructs a null host address object, i.e. an address which is not valid for any host or interface.
 
     \sa clear()
 */
diff --git a/src/network/kernel/qhostinfo_win.cpp b/src/network/kernel/qhostinfo_win.cpp
index da28cd48c1d57defc08ef24b05b7f2beb34f874c..7e45e9f94984e92af602f11805ba7feb32b380e9 100644
--- a/src/network/kernel/qhostinfo_win.cpp
+++ b/src/network/kernel/qhostinfo_win.cpp
@@ -34,7 +34,6 @@
 #include <winsock2.h>
 
 #include "qhostinfo_p.h"
-#include "private/qnativesocketengine_p.h"
 #include <ws2tcpip.h>
 #include <private/qsystemlibrary_p.h>
 #include <qmutex.h>
@@ -77,14 +76,18 @@ static void resolveLibrary()
 {
     // Attempt to resolve getaddrinfo(); without it we'll have to fall
     // back to gethostbyname(), which has no IPv6 support.
-#if !defined(Q_OS_WINCE)
-    local_getaddrinfo = (getaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "getaddrinfo");
-    local_freeaddrinfo = (freeaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "freeaddrinfo");
-    local_getnameinfo = (getnameinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "getnameinfo");
-#else
+#if defined(Q_OS_WINCE)
     local_getaddrinfo = (getaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2"), "getaddrinfo");
     local_freeaddrinfo = (freeaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2"), "freeaddrinfo");
     local_getnameinfo = (getnameinfoProto) QSystemLibrary::resolve(QLatin1String("ws2"), "getnameinfo");
+#elif defined (Q_OS_WINRT)
+    local_getaddrinfo = (getaddrinfoProto) &getaddrinfo;
+    local_freeaddrinfo = (freeaddrinfoProto) &freeaddrinfo;
+    local_getnameinfo = (getnameinfoProto) getnameinfo;
+#else
+    local_getaddrinfo = (getaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "getaddrinfo");
+    local_freeaddrinfo = (freeaddrinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "freeaddrinfo");
+    local_getnameinfo = (getnameinfoProto) QSystemLibrary::resolve(QLatin1String("ws2_32"), "getnameinfo");
 #endif
 }
 
diff --git a/src/network/kernel/qhostinfo_winrt.cpp b/src/network/kernel/qhostinfo_winrt.cpp
deleted file mode 100644
index 1840bebd3988b049fe29ff6dc5b34bc3d4439aaf..0000000000000000000000000000000000000000
--- a/src/network/kernel/qhostinfo_winrt.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL21$
-** 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qhostinfo_p.h"
-
-#include <qfunctions_winrt.h>
-#include <qurl.h>
-
-#include <wrl.h>
-#include <windows.networking.h>
-#include <windows.networking.sockets.h>
-#include <windows.networking.connectivity.h>
-using namespace Microsoft::WRL;
-using namespace Microsoft::WRL::Wrappers;
-using namespace ABI::Windows::Foundation;
-using namespace ABI::Windows::Foundation::Collections;
-using namespace ABI::Windows::Networking;
-using namespace ABI::Windows::Networking::Connectivity;
-using namespace ABI::Windows::Networking::Sockets;
-
-QT_BEGIN_NAMESPACE
-
-#define E_NO_SUCH_HOST 0x80072af9
-
-//#define QHOSTINFO_DEBUG
-
-QHostInfo QHostInfoAgent::fromName(const QString &hostName)
-{
-    QHostInfo results;
-
-    QHostAddress address;
-    if (address.setAddress(hostName)) {
-        // Reverse lookup
-        // TODO: is there a replacement for getnameinfo for winrt?
-        Q_UNIMPLEMENTED();
-        return results;
-    }
-
-    QByteArray aceHostname = QUrl::toAce(hostName);
-    results.setHostName(hostName);
-    if (aceHostname.isEmpty()) {
-        results.setError(QHostInfo::HostNotFound);
-        results.setErrorString(hostName.isEmpty() ? tr("No host name given") : tr("Invalid hostname"));
-        return results;
-    }
-
-    ComPtr<IHostNameFactory> hostnameFactory;
-    HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
-                                        IID_PPV_ARGS(&hostnameFactory));
-    Q_ASSERT_SUCCEEDED(hr);
-
-    ComPtr<IHostName> host;
-    HStringReference hostNameRef((const wchar_t*)hostName.utf16());
-    hr = hostnameFactory->CreateHostName(hostNameRef.Get(), &host);
-    Q_ASSERT_SUCCEEDED(hr);
-
-    ComPtr<IDatagramSocketStatics> datagramSocketStatics;
-    hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics);
-    Q_ASSERT_SUCCEEDED(hr);
-
-    ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op;
-    hr = datagramSocketStatics->GetEndpointPairsAsync(host.Get(),
-                                                 HString::MakeReference(L"0").Get(),
-                                                 &op);
-    Q_ASSERT_SUCCEEDED(hr);
-
-    ComPtr<IVectorView<EndpointPair *>> endpointPairs;
-    hr = op->GetResults(&endpointPairs);
-    int waitCount = 0;
-    while (hr == E_ILLEGAL_METHOD_CALL) {
-        WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE);
-        hr = op->GetResults(&endpointPairs);
-        if (++waitCount > 1200) // Wait for 1 minute max
-            return results;
-    }
-
-    if (hr == E_NO_SUCH_HOST || !endpointPairs) {
-        results.setError(QHostInfo::HostNotFound);
-        results.setErrorString(tr("Host %1 could not be found.").arg(hostName));
-        return results;
-    }
-    Q_ASSERT_SUCCEEDED(hr);
-
-    unsigned int size;
-    hr = endpointPairs->get_Size(&size);
-    Q_ASSERT_SUCCEEDED(hr);
-    QList<QHostAddress> addresses;
-    for (unsigned int i = 0; i < size; ++i) {
-        ComPtr<IEndpointPair> endpointpair;
-        hr = endpointPairs->GetAt(i, &endpointpair);
-        Q_ASSERT_SUCCEEDED(hr);
-        ComPtr<IHostName> remoteHost;
-        hr = endpointpair->get_RemoteHostName(&remoteHost);
-        Q_ASSERT_SUCCEEDED(hr);
-        if (!remoteHost)
-            continue;
-        HostNameType type;
-        hr = remoteHost->get_Type(&type);
-        Q_ASSERT_SUCCEEDED(hr);
-        if (type == HostNameType_DomainName)
-            continue;
-
-        HString name;
-        hr = remoteHost->get_CanonicalName(name.GetAddressOf());
-        Q_ASSERT_SUCCEEDED(hr);
-        UINT32 length;
-        PCWSTR rawString = name.GetRawBuffer(&length);
-        QHostAddress addr;
-        addr.setAddress(QString::fromWCharArray(rawString, length));
-        if (!addresses.contains(addr))
-            addresses.append(addr);
-    }
-    results.setAddresses(addresses);
-
-    return results;
-}
-
-// QString QHostInfo::localDomainName() defined in qnetworkinterface_win.cpp
-
-QT_END_NAMESPACE
diff --git a/src/network/socket/qabstractsocket.cpp b/src/network/socket/qabstractsocket.cpp
index 1831d2571857a9ace414e65b8e6f9ddacf5bdd5b..1c77d14b29d5b2c042054e7e00d01277a6692b6e 100644
--- a/src/network/socket/qabstractsocket.cpp
+++ b/src/network/socket/qabstractsocket.cpp
@@ -426,8 +426,8 @@
 
     \value ReuseAddressHint Provides a hint to QAbstractSocket that it should try
     to rebind the service even if the address and port are already bound by
-    another socket. On Windows, this is equivalent to the SO_REUSEADDR
-    socket option. On Unix, this option is ignored.
+    another socket. On Windows and Unix, this is equivalent to the SO_REUSEADDR
+    socket option.
 
     \value DefaultForPlatform The default option for the current platform.
     On Unix and OS X, this is equivalent to (DontShareAddress
diff --git a/src/network/socket/qnativesocketengine_unix.cpp b/src/network/socket/qnativesocketengine_unix.cpp
index 8626a6be0f3c635b079f8474214a44b40fca463c..6a740f4c30e06bdd827211a1338d88c63e2bf52f 100644
--- a/src/network/socket/qnativesocketengine_unix.cpp
+++ b/src/network/socket/qnativesocketengine_unix.cpp
@@ -994,7 +994,7 @@ qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 l
 #  elif defined(IP_SENDSRCADDR)
             struct in_addr *data = reinterpret_cast<in_addr *>(CMSG_DATA(cmsgptr));
             cmsgptr->cmsg_type = IP_SENDSRCADDR;
-            addr->s_addr = htonl(header.senderAddress.toIPv4Address());
+            data->s_addr = htonl(header.senderAddress.toIPv4Address());
 #  endif
             cmsgptr->cmsg_level = IPPROTO_IP;
             msg.msg_controllen += CMSG_SPACE(sizeof(*data));
diff --git a/src/network/socket/qsocks5socketengine.cpp b/src/network/socket/qsocks5socketengine.cpp
index 26543883cc133963c9bb1190e6d02c80b374871f..6868e8c73a3f603207b8438d513bb6a40016fa73 100644
--- a/src/network/socket/qsocks5socketengine.cpp
+++ b/src/network/socket/qsocks5socketengine.cpp
@@ -1111,14 +1111,16 @@ bool QSocks5SocketEngine::connectInternal()
         }
     }
 
-    if (d->socks5State == QSocks5SocketEnginePrivate::Uninitialized
-        && d->socketState != QAbstractSocket::ConnectingState) {
-        setState(QAbstractSocket::ConnectingState);
-        //limit buffer in internal socket, data is buffered in the external socket under application control
-        d->data->controlSocket->setReadBufferSize(65536);
+    if (d->socketState != QAbstractSocket::ConnectingState) {
+        if (d->socks5State == QSocks5SocketEnginePrivate::Uninitialized) {
+            setState(QAbstractSocket::ConnectingState);
+            //limit buffer in internal socket, data is buffered in the external socket under application control
+            d->data->controlSocket->setReadBufferSize(65536);
+        }
+
         d->data->controlSocket->connectToHost(d->proxyInfo.hostName(), d->proxyInfo.port());
-        return false;
     }
+
     return false;
 }
 
diff --git a/src/platformheaders/windowsfunctions/qwindowswindowfunctions.h b/src/platformheaders/windowsfunctions/qwindowswindowfunctions.h
index 4c6d01cc527c1d26dd110dbdae3bb56b88873bd7..720f7f31be7cd99b9cd45b3d0470f5947b3a80c2 100644
--- a/src/platformheaders/windowsfunctions/qwindowswindowfunctions.h
+++ b/src/platformheaders/windowsfunctions/qwindowswindowfunctions.h
@@ -60,6 +60,15 @@ public:
         if (func)
             func(window, type);
     }
+
+    typedef void (*SetHasBorderInFullScreen)(QWindow *window, bool border);
+    static const QByteArray setHasBorderInFullScreenIdentifier() { return QByteArrayLiteral("WindowsSetHasBorderInFullScreen"); }
+    static void setHasBorderInFullScreen(QWindow *window, bool border)
+    {
+        SetHasBorderInFullScreen func = reinterpret_cast<SetHasBorderInFullScreen>(QGuiApplication::platformFunction(setHasBorderInFullScreenIdentifier()));
+        if (func)
+            func(window, border);
+    }
 };
 
 Q_DECLARE_OPERATORS_FOR_FLAGS(QWindowsWindowFunctions::TouchWindowTouchTypes)
diff --git a/src/platformheaders/windowsfunctions/qwindowswindowfunctions.qdoc b/src/platformheaders/windowsfunctions/qwindowswindowfunctions.qdoc
index 84fae2f56dac30afb7ea93fed1bc57df540d0846..d6b8764e7b597c6b27c5c21fc6b1194442a32b1a 100644
--- a/src/platformheaders/windowsfunctions/qwindowswindowfunctions.qdoc
+++ b/src/platformheaders/windowsfunctions/qwindowswindowfunctions.qdoc
@@ -69,3 +69,29 @@
     This is a convenience function that can be used directly instead of resolving the function pointer.
     \a window and \a type will be relayed to the function retrieved by QGuiApplication
 */
+
+/*!
+    \typedef QWindowsWindowFunctions::SetHasBorderInFullScreen
+
+    This is the typedef for the function returned by QGuiApplication::platformFunction when passed setHasBorderInFullScreenIdentifier.
+*/
+
+/*!
+    \fn QByteArray QWindowsWindowFunctions::setHasBorderInFullScreenIdentifier()
+    \since 5.6
+
+    This function returns the bytearray that can be used to query
+    QGuiApplication::platformFunction to retrieve the SetHasBorderInFullScreen function.
+*/
+
+/*!
+    \fn void QWindowsWindowFunctions::setHasBorderInFullScreen(QWindow *window, bool border)
+    \since 5.6
+
+    This is a convenience function that can be used directly instead of resolving the function pointer.
+    \a window and \a border will be relayed to the function retrieved by QGuiApplication. When \a border
+    is true then it will enable the WS_BORDER flag in full screen mode to enable other top level windows
+    inside the application to appear on top when required.
+
+    See also \l [QtDoc] {Fullscreen OpenGL Based Windows}
+*/
diff --git a/src/platformsupport/clipboard/clipboard.pri b/src/platformsupport/clipboard/clipboard.pri
index 2532430f1e10993931ae6ff7adf57c36a0c4af29..cb8315d003c2567e2ccd5412291854640988453b 100644
--- a/src/platformsupport/clipboard/clipboard.pri
+++ b/src/platformsupport/clipboard/clipboard.pri
@@ -1,5 +1,7 @@
 mac {
     HEADERS += $$PWD/qmacmime_p.h
     OBJECTIVE_SOURCES += $$PWD/qmacmime.mm
+
+    osx: LIBS_PRIVATE += -framework AppKit
 }
 
diff --git a/src/plugins/platforms/android/androidjnimain.cpp b/src/plugins/platforms/android/androidjnimain.cpp
index f500d6e413473be50d0734fee8c1a2a42689129b..dd9154f8d2fc57e879fe0062fdb55e07b6e8d25a 100644
--- a/src/plugins/platforms/android/androidjnimain.cpp
+++ b/src/plugins/platforms/android/androidjnimain.cpp
@@ -34,6 +34,7 @@
 
 #include <dlfcn.h>
 #include <pthread.h>
+#include <semaphore.h>
 #include <qplugin.h>
 #include <qdebug.h>
 
@@ -91,6 +92,8 @@ extern "C" typedef int (*Main)(int, char **); //use the standard main method to
 static Main m_main = nullptr;
 static void *m_mainLibraryHnd = nullptr;
 static QList<QByteArray> m_applicationParams;
+pthread_t m_qtAppThread = 0;
+static sem_t m_exitSemaphore, m_terminateSemaphore;
 
 struct SurfaceData
 {
@@ -454,6 +457,10 @@ static void *startMainMethod(void */*data*/)
     if (vm != 0)
         vm->DetachCurrentThread();
 
+    sem_post(&m_terminateSemaphore);
+    sem_wait(&m_exitSemaphore);
+    sem_destroy(&m_exitSemaphore);
+
     // We must call exit() to ensure that all global objects will be destructed
     exit(ret);
     return 0;
@@ -503,8 +510,13 @@ static jboolean startQtApplication(JNIEnv *env, jobject /*object*/, jstring para
         return false;
     }
 
-    pthread_t appThread;
-    return pthread_create(&appThread, nullptr, startMainMethod, nullptr) == 0;
+    if (sem_init(&m_exitSemaphore, 0, 0) == -1)
+        return false;
+
+    if (sem_init(&m_terminateSemaphore, 0, 0) == -1)
+        return false;
+
+    return pthread_create(&m_qtAppThread, nullptr, startMainMethod, nullptr) == 0;
 }
 
 
@@ -518,6 +530,8 @@ static void quitQtAndroidPlugin(JNIEnv *env, jclass /*clazz*/)
 
 static void terminateQt(JNIEnv *env, jclass /*clazz*/)
 {
+    sem_wait(&m_terminateSemaphore);
+    sem_destroy(&m_terminateSemaphore);
     env->DeleteGlobalRef(m_applicationClass);
     env->DeleteGlobalRef(m_classLoaderObject);
     if (m_resourcesObj)
@@ -535,6 +549,8 @@ static void terminateQt(JNIEnv *env, jclass /*clazz*/)
     m_androidPlatformIntegration = nullptr;
     delete m_androidAssetsFileEngineHandler;
     m_androidAssetsFileEngineHandler = nullptr;
+    sem_post(&m_exitSemaphore);
+    pthread_join(m_qtAppThread, nullptr);
 }
 
 static void setSurface(JNIEnv *env, jobject /*thiz*/, jint id, jobject jSurface, jint w, jint h)
diff --git a/src/plugins/platforms/android/qandroidplatformscreen.cpp b/src/plugins/platforms/android/qandroidplatformscreen.cpp
index 209ce2f7db82991b8b68ec4c53065ae0206f7604..8152f1d53f2330e96a92f6c93dbad9860f8a44ca 100644
--- a/src/plugins/platforms/android/qandroidplatformscreen.cpp
+++ b/src/plugins/platforms/android/qandroidplatformscreen.cpp
@@ -111,9 +111,13 @@ QAndroidPlatformScreen::~QAndroidPlatformScreen()
 
 QWindow *QAndroidPlatformScreen::topWindow() const
 {
-    foreach (QAndroidPlatformWindow *w, m_windowStack)
-        if (w->window()->type() == Qt::Window || w->window()->type() == Qt::Dialog)
+    foreach (QAndroidPlatformWindow *w, m_windowStack) {
+        if (w->window()->type() == Qt::Window ||
+                w->window()->type() == Qt::Popup ||
+                w->window()->type() == Qt::Dialog) {
             return w->window();
+        }
+    }
     return 0;
 }
 
diff --git a/src/plugins/platforms/cocoa/qcocoahelpers.mm b/src/plugins/platforms/cocoa/qcocoahelpers.mm
index f51c21ee9ba1206bf6edcb7573219537e77c5066..7bc8d6585b549c93745c009acc11abca44379721 100644
--- a/src/plugins/platforms/cocoa/qcocoahelpers.mm
+++ b/src/plugins/platforms/cocoa/qcocoahelpers.mm
@@ -604,6 +604,7 @@ void qt_mac_cleanUpMacColorSpaces()
 CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice)
 {
 #ifdef QT_NO_WIDGETS
+    Q_UNUSED(paintDevice)
     return qt_mac_displayColorSpace(0);
 #else
     bool isWidget = (paintDevice->devType() == QInternal::Widget);
diff --git a/src/plugins/platforms/cocoa/qcocoanativeinterface.mm b/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
index 41ea1fa49cd45582c549f7b7a92b9fa33e593e30..baee4519031005e18988b3bee564a54eebb55921 100644
--- a/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
+++ b/src/plugins/platforms/cocoa/qcocoanativeinterface.mm
@@ -162,6 +162,7 @@ void *QCocoaNativeInterface::NSPrintInfoForPrintEngine(QPrintEngine *printEngine
         macPrintEnginePriv->initialize();
     return macPrintEnginePriv->printInfo;
 #else
+    Q_UNUSED(printEngine);
     qFatal("Printing is not supported when Qt is configured with -no-widgets");
     return 0;
 #endif
diff --git a/src/plugins/platforms/cocoa/qnsview.mm b/src/plugins/platforms/cocoa/qnsview.mm
index 3faa292ae0ea37929b89999fa5a2d2ff7e592b1f..0d80333e65ac2f250289ceed6ec4f286f7295ac6 100644
--- a/src/plugins/platforms/cocoa/qnsview.mm
+++ b/src/plugins/platforms/cocoa/qnsview.mm
@@ -440,16 +440,17 @@ QT_WARNING_PUSH
 QT_WARNING_DISABLE_CLANG("-Wobjc-method-access")
         enum { NSWindowOcclusionStateVisible = 1UL << 1 };
 #endif
-        if ((NSUInteger)[self.window occlusionState] & NSWindowOcclusionStateVisible) {
-            m_platformWindow->exposeWindow();
-        } else {
-            // Send Obscure events on window occlusion to stop animations. Several
-            // unit tests expect paint and/or expose events for windows that are
-            // sometimes (unpredictably) occlouded: Don't send Obscure events when
-            // running under QTestLib.
-            static bool onTestLib = qt_mac_resolveOption(false, "QT_QTESTLIB_RUNNING");
-            if (!onTestLib)
+        // Several unit tests expect paint and/or expose events for windows that are
+        // sometimes (unpredictably) occluded and some unit tests depend on QWindow::isExposed -
+        // don't send Expose/Obscure events when running under QTestLib.
+        static const bool onTestLib = qt_mac_resolveOption(false, "QT_QTESTLIB_RUNNING");
+        if (!onTestLib) {
+            if ((NSUInteger)[self.window occlusionState] & NSWindowOcclusionStateVisible) {
+                m_platformWindow->exposeWindow();
+            } else {
+                // Send Obscure events on window occlusion to stop animations.
                 m_platformWindow->obscureWindow();
+            }
         }
 #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_9
 QT_WARNING_POP
diff --git a/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp b/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp
index 8af48a893b125e9737a046dc3809ac0d1bf4af01..1fb6020d69b453f74440e6ebd5f21074a90ea742 100644
--- a/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp
+++ b/src/plugins/platforms/eglfs/qeglfsdeviceintegration.cpp
@@ -224,7 +224,7 @@ QDpi QEGLDeviceIntegration::logicalDpi() const
 
 qreal QEGLDeviceIntegration::pixelDensity() const
 {
-    return logicalDpi().first / qreal(100);
+    return qRound(logicalDpi().first / qreal(100));
 }
 
 Qt::ScreenOrientation QEGLDeviceIntegration::nativeOrientation() const
diff --git a/src/plugins/platforms/ios/qiosintegration.mm b/src/plugins/platforms/ios/qiosintegration.mm
index 0e3da8dce8e1f063ab4227ef19e850bbbc4073a5..85b5c477cc5549d630549d5b0b9a483dbe801349 100644
--- a/src/plugins/platforms/ios/qiosintegration.mm
+++ b/src/plugins/platforms/ios/qiosintegration.mm
@@ -105,8 +105,10 @@ QIOSIntegration::QIOSIntegration()
     m_touchDevice = new QTouchDevice;
     m_touchDevice->setType(QTouchDevice::TouchScreen);
     QTouchDevice::Capabilities touchCapabilities = QTouchDevice::Position | QTouchDevice::NormalizedPosition;
-    if (mainScreen.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)
-        touchCapabilities |= QTouchDevice::Pressure;
+    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_IOS_9_0) {
+        if (mainScreen.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)
+            touchCapabilities |= QTouchDevice::Pressure;
+    }
     m_touchDevice->setCapabilities(touchCapabilities);
     QWindowSystemInterface::registerTouchDevice(m_touchDevice);
     QMacInternalPasteboardMime::initializeMimeTypes();
diff --git a/src/plugins/platforms/ios/qiosmenu.mm b/src/plugins/platforms/ios/qiosmenu.mm
index 7aea3729fdc19f52d170291bf1f130dc0e0b7ead..612f8c43a27743546ca74058b4a71f8bef615d0d 100644
--- a/src/plugins/platforms/ios/qiosmenu.mm
+++ b/src/plugins/platforms/ios/qiosmenu.mm
@@ -61,11 +61,23 @@ static NSString *const kSelectorPrefix = @"_qtMenuItem_";
 {
     if (self = [super init]) {
         [self setVisibleMenuItems:visibleMenuItems];
+        [[NSNotificationCenter defaultCenter]
+            addObserver:self
+            selector:@selector(menuClosed)
+            name:UIMenuControllerDidHideMenuNotification object:nil];
     }
 
     return self;
 }
 
+-(void)dealloc
+{
+    [[NSNotificationCenter defaultCenter]
+        removeObserver:self
+        name:UIMenuControllerDidHideMenuNotification object:nil];
+    [super dealloc];
+}
+
 - (void)setVisibleMenuItems:(const QIOSMenuItemList &)visibleMenuItems
 {
     m_visibleMenuItems = visibleMenuItems;
@@ -85,6 +97,11 @@ static NSString *const kSelectorPrefix = @"_qtMenuItem_";
         [[UIMenuController sharedMenuController] setMenuVisible:YES animated:NO];
 }
 
+-(void)menuClosed
+{
+    QIOSMenu::currentMenu()->dismiss();
+}
+
 - (id)targetForAction:(SEL)action withSender:(id)sender
 {
     Q_UNUSED(sender);
diff --git a/src/plugins/platforms/ios/qiostextresponder.mm b/src/plugins/platforms/ios/qiostextresponder.mm
index 770dadd3e4140537b67603d581bf6f046d79ca84..320b1cac61d437f5e7a5550e048b120aa72a69c5 100644
--- a/src/plugins/platforms/ios/qiostextresponder.mm
+++ b/src/plugins/platforms/ios/qiostextresponder.mm
@@ -318,7 +318,11 @@
     // a regular responder transfer to another window. In the former case, iOS
     // will set the new first-responder to our next-responder, and in the latter
     // case we'll have an active responder candidate.
-    if ([UIResponder currentFirstResponder] == [self nextResponder]) {
+    if (![UIResponder currentFirstResponder]) {
+        // No first responder set anymore, sync this with Qt by clearing the
+        // focus object.
+        m_inputContext->clearCurrentFocusObject();
+    } else if ([UIResponder currentFirstResponder] == [self nextResponder]) {
         // We have resigned the keyboard, and transferred first responder back to the parent view
         Q_ASSERT(!FirstResponderCandidate::currentCandidate());
         if ([self currentImeState:Qt::ImEnabled].toBool()) {
@@ -613,7 +617,8 @@
 
 - (UITextPosition *)endOfDocument
 {
-    int endPosition = [self currentImeState:Qt::ImSurroundingText].toString().length();
+    QString surroundingText = [self currentImeState:Qt::ImSurroundingText].toString();
+    int endPosition = surroundingText.length() + m_markedText.length();
     return [QUITextPosition positionWithIndex:endPosition];
 }
 
@@ -644,9 +649,18 @@
 
 - (NSString *)textInRange:(UITextRange *)range
 {
+    QString text = [self currentImeState:Qt::ImSurroundingText].toString();
+    if (!m_markedText.isEmpty()) {
+        // [UITextInput textInRange] is sparsely documented, but it turns out that unconfirmed
+        // marked text should be seen as a part of the text document. This is different from
+        // ImSurroundingText, which excludes it.
+        int cursorPos = [self currentImeState:Qt::ImCursorPosition].toInt();
+        text = text.left(cursorPos) + m_markedText + text.mid(cursorPos);
+    }
+
     int s = static_cast<QUITextPosition *>([range start]).index;
     int e = static_cast<QUITextPosition *>([range end]).index;
-    return [self currentImeState:Qt::ImSurroundingText].toString().mid(s, e - s).toNSString();
+    return text.mid(s, e - s).toNSString();
 }
 
 - (void)setMarkedText:(NSString *)markedText selectedRange:(NSRange)selectedRange
@@ -915,6 +929,14 @@
     if ([text isEqualToString:@"\n"]) {
         [self sendKeyPressRelease:Qt::Key_Return modifiers:Qt::NoModifier];
 
+        // An onEnter handler of a TextInput might move to the next input by calling
+        // nextInput.forceActiveFocus() which changes the focusObject.
+        // In that case we don't want to hide the VKB.
+        if (focusObject != QGuiApplication::focusObject()) {
+            qImDebug() << "focusObject already changed, not resigning first responder.";
+            return;
+        }
+
         if (self.returnKeyType == UIReturnKeyDone || self.returnKeyType == UIReturnKeyGo
             || self.returnKeyType == UIReturnKeySend || self.returnKeyType == UIReturnKeySearch)
             [self resignFirstResponder];
diff --git a/src/plugins/platforms/ios/quiview.mm b/src/plugins/platforms/ios/quiview.mm
index 53b3d30327a01bea417773e17104bbff50b95ff0..4dd43be465f18516d452cebb86c98dae967961b2 100644
--- a/src/plugins/platforms/ios/quiview.mm
+++ b/src/plugins/platforms/ios/quiview.mm
@@ -286,10 +286,14 @@
 
     QTouchDevice *touchDevice = QIOSIntegration::instance()->touchDevice();
     QTouchDevice::Capabilities touchCapabilities = touchDevice->capabilities();
-    if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)
-        touchCapabilities |= QTouchDevice::Pressure;
-    else
-        touchCapabilities &= ~QTouchDevice::Pressure;
+
+    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_IOS_9_0) {
+        if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable)
+            touchCapabilities |= QTouchDevice::Pressure;
+        else
+            touchCapabilities &= ~QTouchDevice::Pressure;
+    }
+
     touchDevice->setCapabilities(touchCapabilities);
 }
 
diff --git a/src/plugins/platforms/windows/openglblacklists/default.json b/src/plugins/platforms/windows/openglblacklists/default.json
index 2672711d3aeaba4aa932c75e93959eb2d67485f6..767eac161cb253ec0666455e38189c7af4ae2580 100644
--- a/src/plugins/platforms/windows/openglblacklists/default.json
+++ b/src/plugins/platforms/windows/openglblacklists/default.json
@@ -1,6 +1,6 @@
 {
     "name": "Qt built-in GPU driver blacklist",
-    "version": "5.5",
+    "version": "5.6",
     "entries": [
         {
             "id": 1,
diff --git a/src/plugins/platforms/windows/qwindowscontext.cpp b/src/plugins/platforms/windows/qwindowscontext.cpp
index f2f6402889f9b4d33bfdba6ee647b774c2a354d9..4934b6c6e41bfff7a5e014ec8a5c5264268ad5a9 100644
--- a/src/plugins/platforms/windows/qwindowscontext.cpp
+++ b/src/plugins/platforms/windows/qwindowscontext.cpp
@@ -405,14 +405,29 @@ void QWindowsContext::setTabletAbsoluteRange(int a)
 #endif
 }
 
+int QWindowsContext::processDpiAwareness()
+{
+#ifndef Q_OS_WINCE
+    int result;
+    if (QWindowsContext::shcoredll.getProcessDpiAwareness
+        && SUCCEEDED(QWindowsContext::shcoredll.getProcessDpiAwareness(NULL, &result))) {
+        return result;
+    }
+#endif // !Q_OS_WINCE
+    return -1;
+}
+
 void QWindowsContext::setProcessDpiAwareness(QtWindows::ProcessDpiAwareness dpiAwareness)
 {
 #ifndef Q_OS_WINCE
     qCDebug(lcQpaWindows) << __FUNCTION__ << dpiAwareness;
     if (QWindowsContext::shcoredll.isValid()) {
         const HRESULT hr = QWindowsContext::shcoredll.setProcessDpiAwareness(dpiAwareness);
-        if (FAILED(hr))
-            qWarning() << "SetProcessDpiAwareness failed:" << QWindowsContext::comErrorString(hr);
+        if (FAILED(hr)) {
+            qWarning().noquote().nospace() << "SetProcessDpiAwareness("
+                << dpiAwareness << ") failed: " << QWindowsContext::comErrorString(hr)
+                << ", using " << QWindowsContext::processDpiAwareness();
+        }
     } else {
         if (dpiAwareness != QtWindows::ProcessDpiUnaware && QWindowsContext::user32dll.setProcessDPIAware) {
             if (!QWindowsContext::user32dll.setProcessDPIAware())
diff --git a/src/plugins/platforms/windows/qwindowscontext.h b/src/plugins/platforms/windows/qwindowscontext.h
index d08fc8f726a7b4a5eb1e8986669fc15bbd90e005..14baec96d8505093a66aec969ce28bf8817eda73 100644
--- a/src/plugins/platforms/windows/qwindowscontext.h
+++ b/src/plugins/platforms/windows/qwindowscontext.h
@@ -148,7 +148,7 @@ struct QWindowsShcoreDLL {
     void init();
     inline bool isValid() const { return getProcessDpiAwareness && setProcessDpiAwareness && getDpiForMonitor; }
 
-    typedef HRESULT (WINAPI *GetProcessDpiAwareness)(HANDLE,int);
+    typedef HRESULT (WINAPI *GetProcessDpiAwareness)(HANDLE,int *);
     typedef HRESULT (WINAPI *SetProcessDpiAwareness)(int);
     typedef HRESULT (WINAPI *GetDpiForMonitor)(HMONITOR,int,UINT *,UINT *);
 
@@ -219,6 +219,7 @@ public:
 
     void setTabletAbsoluteRange(int a);
     void setProcessDpiAwareness(QtWindows::ProcessDpiAwareness dpiAwareness);
+    static int processDpiAwareness();
 
     // Returns a combination of SystemInfoFlags
     unsigned systemInfo() const;
diff --git a/src/plugins/platforms/windows/qwindowsfontdatabase_ft.cpp b/src/plugins/platforms/windows/qwindowsfontdatabase_ft.cpp
index 1b6ee0f383a7f07896165db332d22331bdb8abea..684c44acf23cb071c718168e9512123f1792267e 100644
--- a/src/plugins/platforms/windows/qwindowsfontdatabase_ft.cpp
+++ b/src/plugins/platforms/windows/qwindowsfontdatabase_ft.cpp
@@ -310,7 +310,7 @@ static QStringList fontNamesFromTTCFile(const QString &filename)
         if (ttcTableHeader.majorVersion < 1 || ttcTableHeader.majorVersion > 2)
             return retVal;
         QVarLengthArray<quint32> offsetTable(ttcTableHeader.numFonts);
-        bytesToRead = sizeof(offsetTable) * ttcTableHeader.numFonts;
+        bytesToRead = sizeof(quint32) * ttcTableHeader.numFonts;
         bytesRead = f.read((char*)offsetTable.data(), bytesToRead);
         if (bytesToRead != bytesRead)
             return retVal;
diff --git a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp
index 593ac7d81038cf65beeeaa490f7a5afaec54e494..a50ee609750942158db0e4bef78c9c6cbc058fc5 100644
--- a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp
+++ b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp
@@ -50,6 +50,7 @@
 #include <QtCore/QtEndian>
 #include <QtCore/QVarLengthArray>
 #include <private/qstringiterator_p.h>
+#include <QtCore/private/qsystemlibrary_p.h>
 
 #include <dwrite.h>
 #include <d2d1.h>
@@ -485,9 +486,9 @@ qreal QWindowsFontEngineDirectWrite::maxCharWidth() const
     return 0;
 }
 
-QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition)
+QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t)
 {
-    QImage im = imageForGlyph(glyph, subPixelPosition, 0, QTransform());
+    QImage im = alphaRGBMapForGlyph(glyph, subPixelPosition, t);
 
     QImage alphaMap(im.width(), im.height(), QImage::Format_Alpha8);
 
@@ -504,6 +505,11 @@ QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed sub
     return alphaMap;
 }
 
+QImage QWindowsFontEngineDirectWrite::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition)
+{
+    return alphaMapForGlyph(glyph, subPixelPosition, QTransform());
+}
+
 bool QWindowsFontEngineDirectWrite::supportsSubPixelPositions() const
 {
     return true;
@@ -640,6 +646,16 @@ QFontEngine *QWindowsFontEngineDirectWrite::cloneWithSize(qreal pixelSize) const
     return fontEngine;
 }
 
+// Dynamically resolve GetUserDefaultLocaleName, which is available from Windows
+// Vista onwards. ### fixme 5.7: Consider reverting to direct linking.
+typedef int (WINAPI *GetUserDefaultLocaleNamePtr)(LPWSTR, int);
+
+static inline GetUserDefaultLocaleNamePtr resolveGetUserDefaultLocaleName()
+{
+    QSystemLibrary library(QStringLiteral("kernel32"));
+    return (GetUserDefaultLocaleNamePtr)library.resolve("GetUserDefaultLocaleName");
+}
+
 void QWindowsFontEngineDirectWrite::initFontInfo(const QFontDef &request,
                                                  int dpi, IDWriteFont *font)
 {
@@ -658,7 +674,9 @@ void QWindowsFontEngineDirectWrite::initFontInfo(const QFontDef &request,
         BOOL exists = false;
 
         wchar_t localeName[LOCALE_NAME_MAX_LENGTH];
-        int defaultLocaleSuccess = GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH);
+        static const GetUserDefaultLocaleNamePtr getUserDefaultLocaleName = resolveGetUserDefaultLocaleName();
+        const int defaultLocaleSuccess = getUserDefaultLocaleName
+            ? getUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH) : 0;
         if (defaultLocaleSuccess)
             hr = familyNames->FindLocaleName(localeName, &index, &exists);
 
@@ -709,9 +727,9 @@ QString QWindowsFontEngineDirectWrite::fontNameSubstitute(const QString &familyN
 glyph_metrics_t QWindowsFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph, QFixed pos, const QTransform &matrix, GlyphFormat format)
 {
     Q_UNUSED(pos);
-    int margin = 0;
-    if (format == QFontEngine::Format_A32 || format == QFontEngine::Format_ARGB)
-        margin = glyphMargin(QFontEngine::Format_A32);
+    Q_UNUSED(format);
+
+    int margin = glyphMargin(QFontEngine::Format_A32);
     glyph_metrics_t gm = QFontEngine::boundingBox(glyph, matrix);
     gm.width += margin * 2;
     gm.height += margin * 2;
diff --git a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h
index da772469e9b83c60d737e0d8cb5efc832a2f725a..cee8691d69b3ae72d5fd92c605100e5dc4b532ef 100644
--- a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h
+++ b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h
@@ -86,6 +86,7 @@ public:
     bool supportsSubPixelPositions() const;
 
     QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition);
+    QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t);
     QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, const QTransform &xform);
 
     QFontEngine *cloneWithSize(qreal pixelSize) const;
diff --git a/src/plugins/platforms/windows/qwindowsinputcontext.cpp b/src/plugins/platforms/windows/qwindowsinputcontext.cpp
index 7e1cc563cb28cd73cfaaadae1f47121abcf31f61..56b5561756f9d5a9340b7784033d3b235e357443 100644
--- a/src/plugins/platforms/windows/qwindowsinputcontext.cpp
+++ b/src/plugins/platforms/windows/qwindowsinputcontext.cpp
@@ -484,7 +484,8 @@ bool QWindowsInputContext::composition(HWND hwnd, LPARAM lParamIn)
     if (lParam & GCS_RESULTSTR) {
         // A fixed result, return the converted string
         event->setCommitString(getCompositionString(himc, GCS_RESULTSTR));
-        endContextComposition();
+        if (!(lParam & GCS_DELTASTART))
+            endContextComposition();
     }
     const bool result = QCoreApplication::sendEvent(m_compositionContext.focusObject, event.data());
     qCDebug(lcQpaInputMethods) << '<' << __FUNCTION__ << "sending markup="
diff --git a/src/plugins/platforms/windows/qwindowsintegration.cpp b/src/plugins/platforms/windows/qwindowsintegration.cpp
index 55e6d55e5b504cea7b3347f0d95e13adf537b580..bd2014b8f243b2371b05c3975fabc3204eedbf07 100644
--- a/src/plugins/platforms/windows/qwindowsintegration.cpp
+++ b/src/plugins/platforms/windows/qwindowsintegration.cpp
@@ -224,7 +224,8 @@ QWindowsIntegrationPrivate::QWindowsIntegrationPrivate(const QStringList &paramL
         dpiAwarenessSet = true;
     }
     qCDebug(lcQpaWindows)
-        << __FUNCTION__ << "DpiAwareness=" << dpiAwareness;
+        << __FUNCTION__ << "DpiAwareness=" << dpiAwareness
+        << "effective process DPI awareness=" << QWindowsContext::processDpiAwareness();
 
     m_context.initTouch(m_options);
 }
diff --git a/src/plugins/platforms/windows/qwindowskeymapper.cpp b/src/plugins/platforms/windows/qwindowskeymapper.cpp
index 4c0b94e6e7aba5827cf65ddeb55499a98e58da50..c5dff60114398b3e7030dff76f89fb3883eff16f 100644
--- a/src/plugins/platforms/windows/qwindowskeymapper.cpp
+++ b/src/plugins/platforms/windows/qwindowskeymapper.cpp
@@ -86,10 +86,15 @@ QT_BEGIN_NAMESPACE
     The code originates from \c qkeymapper_win.cpp.
 */
 
+static void clearKeyRecorderOnApplicationInActive(Qt::ApplicationState state);
+
 QWindowsKeyMapper::QWindowsKeyMapper()
     : m_useRTLExtensions(false), m_keyGrabber(0)
 {
     memset(keyLayout, 0, sizeof(keyLayout));
+    QGuiApplication *app = static_cast<QGuiApplication *>(QGuiApplication::instance());
+    QObject::connect(app, &QGuiApplication::applicationStateChanged,
+                     app, clearKeyRecorderOnApplicationInActive);
 }
 
 QWindowsKeyMapper::~QWindowsKeyMapper()
@@ -144,6 +149,12 @@ struct KeyRecorder
 };
 static KeyRecorder key_recorder;
 
+static void clearKeyRecorderOnApplicationInActive(Qt::ApplicationState state)
+{
+    if (state == Qt::ApplicationInactive)
+        key_recorder.clearKeys();
+}
+
 KeyRecord *KeyRecorder::findKey(int code, bool remove)
 {
     KeyRecord *result = 0;
diff --git a/src/plugins/platforms/windows/qwindowsnativeinterface.cpp b/src/plugins/platforms/windows/qwindowsnativeinterface.cpp
index db8b2ec0945535f76e279a172050764dae18d78f..659ef79c1878a2a0f9962a29e1fb367e1c33527a 100644
--- a/src/plugins/platforms/windows/qwindowsnativeinterface.cpp
+++ b/src/plugins/platforms/windows/qwindowsnativeinterface.cpp
@@ -234,6 +234,8 @@ QFunctionPointer QWindowsNativeInterface::platformFunction(const QByteArray &fun
 {
     if (function == QWindowsWindowFunctions::setTouchWindowTouchTypeIdentifier())
         return QFunctionPointer(QWindowsWindow::setTouchWindowTouchTypeStatic);
+    else if (function == QWindowsWindowFunctions::setHasBorderInFullScreenIdentifier())
+        return QFunctionPointer(QWindowsWindow::setHasBorderInFullScreenStatic);
     return Q_NULLPTR;
 }
 
diff --git a/src/plugins/platforms/windows/qwindowstheme.cpp b/src/plugins/platforms/windows/qwindowstheme.cpp
index 877bdfec17d6de3431a6be96ceb9769d3099de3a..cc367ff8013e5e67cd13363c2bb92b4fdbacaab5 100644
--- a/src/plugins/platforms/windows/qwindowstheme.cpp
+++ b/src/plugins/platforms/windows/qwindowstheme.cpp
@@ -131,7 +131,7 @@ static inline bool booleanSystemParametersInfo(UINT what, bool defaultValue)
     return defaultValue;
 }
 
-static inline bool dWordSystemParametersInfo(UINT what, DWORD defaultValue)
+static inline DWORD dWordSystemParametersInfo(UINT what, DWORD defaultValue)
 {
     DWORD result;
     if (SystemParametersInfo(what, 0, &result, 0))
@@ -394,7 +394,7 @@ QVariant QWindowsTheme::themeHint(ThemeHint hint) const
     case ContextMenuOnMouseRelease:
         return QVariant(true);
     case WheelScrollLines:
-        return dWordSystemParametersInfo(SPI_GETWHEELSCROLLLINES, 3);
+        return QVariant(int(dWordSystemParametersInfo(SPI_GETWHEELSCROLLLINES, 3)));
     default:
         break;
     }
diff --git a/src/plugins/platforms/windows/qwindowswindow.cpp b/src/plugins/platforms/windows/qwindowswindow.cpp
index 611d586b1945f589e6dc44ebdf584feb8f546116..cac8ec5ecca04d3e693761f4156b9db8538b9f28 100644
--- a/src/plugins/platforms/windows/qwindowswindow.cpp
+++ b/src/plugins/platforms/windows/qwindowswindow.cpp
@@ -1720,7 +1720,7 @@ void QWindowsWindow::setWindowState_sys(Qt::WindowState newState)
             if (!m_savedStyle) {
                 m_savedStyle = style();
 #ifndef Q_OS_WINCE
-                if (oldState == Qt::WindowMinimized) {
+                if (oldState == Qt::WindowMinimized || oldState == Qt::WindowMaximized) {
                     const QRect nf = normalFrameGeometry(m_data.hwnd);
                     if (nf.isValid())
                         m_savedFrameGeometry = nf;
@@ -1735,6 +1735,8 @@ void QWindowsWindow::setWindowState_sys(Qt::WindowState newState)
                 newStyle |= WS_SYSMENU;
             if (visible)
                 newStyle |= WS_VISIBLE;
+            if (testFlag(HasBorderInFullScreen))
+                newStyle |= WS_BORDER;
             setStyle(newStyle);
             // Use geometry of QWindow::screen() within creation or the virtual screen the
             // window is in (QTBUG-31166, QTBUG-30724).
@@ -1769,7 +1771,7 @@ void QWindowsWindow::setWindowState_sys(Qt::WindowState newState)
             // preserve maximized state
             if (visible) {
                 setFlag(WithinMaximize);
-                ShowWindow(m_data.hwnd, (newState == Qt::WindowMaximized) ? SW_MAXIMIZE : SW_SHOWNOACTIVATE);
+                ShowWindow(m_data.hwnd, (newState == Qt::WindowMaximized) ? SW_MAXIMIZE : SW_SHOWNA);
                 clearFlag(WithinMaximize);
             }
             m_savedStyle = 0;
@@ -2371,4 +2373,19 @@ void QWindowsWindow::aboutToMakeCurrent()
 #endif
 }
 
+void QWindowsWindow::setHasBorderInFullScreenStatic(QWindow *window, bool border)
+{
+    if (!window->handle())
+        return;
+    static_cast<QWindowsWindow *>(window->handle())->setHasBorderInFullScreen(border);
+}
+
+void QWindowsWindow::setHasBorderInFullScreen(bool border)
+{
+    if (border)
+        setFlag(HasBorderInFullScreen);
+    else
+        clearFlag(HasBorderInFullScreen);
+}
+
 QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowswindow.h b/src/plugins/platforms/windows/qwindowswindow.h
index 4172a3d8502e550e54024e84bbb9b4994ceed4fe..710cab859708e60db2c60bf0aedf60ac10948325 100644
--- a/src/plugins/platforms/windows/qwindowswindow.h
+++ b/src/plugins/platforms/windows/qwindowswindow.h
@@ -137,7 +137,8 @@ public:
         WithinMaximize = 0x40000,
         MaximizeToFullScreen = 0x80000,
         InputMethodDisabled = 0x100000,
-        Compositing = 0x200000
+        Compositing = 0x200000,
+        HasBorderInFullScreen = 0x400000
     };
 
     QWindowsWindow(QWindow *window, const QWindowsWindowData &data);
@@ -251,7 +252,8 @@ public:
 
     static void setTouchWindowTouchTypeStatic(QWindow *window, QWindowsWindowFunctions::TouchWindowTouchTypes touchTypes);
     void registerTouchWindow(QWindowsWindowFunctions::TouchWindowTouchTypes touchTypes = QWindowsWindowFunctions::NormalTouch);
-
+    static void setHasBorderInFullScreenStatic(QWindow *window, bool border);
+    void setHasBorderInFullScreen(bool border);
 private:
     inline void show_sys() const;
     inline void hide_sys() const;
diff --git a/src/plugins/platforms/winrt/qwinrteglcontext.cpp b/src/plugins/platforms/winrt/qwinrteglcontext.cpp
index 3fd0278360c7a819f7f404b3c95a6b0b27fd9e9d..bc77df566e43e18acfc2c909105e620a67cdf5df 100644
--- a/src/plugins/platforms/winrt/qwinrteglcontext.cpp
+++ b/src/plugins/platforms/winrt/qwinrteglcontext.cpp
@@ -46,6 +46,7 @@
 #define EGL_EGLEXT_PROTOTYPES
 #include <EGL/eglext.h>
 
+#include <QOffscreenSurface>
 #include <QOpenGLContext>
 #include <QtPlatformSupport/private/qeglconvenience_p.h>
 
@@ -54,9 +55,6 @@ QT_BEGIN_NAMESPACE
 struct WinRTEGLDisplay
 {
     WinRTEGLDisplay() {
-        eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
-        if (eglDisplay == EGL_NO_DISPLAY)
-            qCritical("Failed to initialize EGL display: 0x%x", eglGetError());
     }
     ~WinRTEGLDisplay() {
         eglTerminate(eglDisplay);
@@ -117,9 +115,17 @@ void QWinRTEGLContext::initialize()
     if (g->eglDisplay == EGL_NO_DISPLAY)
         qCritical("Failed to initialize EGL display: 0x%x", eglGetError());
 
-    if (!eglInitialize(g->eglDisplay, nullptr, nullptr))
-        qCritical("Failed to initialize EGL: 0x%x", eglGetError());
-
+    // eglInitialize checks for EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE
+    // which adds a suspending handler. This needs to be added from the Xaml
+    // thread itself, otherwise it will not be invoked. add_Suspending does
+    // not return an error unfortunately, so it silently fails and causes
+    // applications to not quit when the system wants to terminate the app
+    // after suspend.
+    hr = QEventDispatcherWinRT::runOnXamlThread([]() {
+        if (!eglInitialize(g->eglDisplay, nullptr, nullptr))
+            qCritical("Failed to initialize EGL: 0x%x", eglGetError());
+        return S_OK;
+    });
     d->eglConfig = q_configFromGLFormat(g->eglDisplay, d->format);
 
     const EGLint flags = d->format.testOption(QSurfaceFormat::DebugContext)
@@ -142,6 +148,9 @@ bool QWinRTEGLContext::makeCurrent(QPlatformSurface *windowSurface)
     Q_D(QWinRTEGLContext);
     Q_ASSERT(windowSurface->surface()->supportsOpenGL());
 
+    if (windowSurface->surface()->surfaceClass() == QSurface::Offscreen)
+        return false;
+
     QWinRTWindow *window = static_cast<QWinRTWindow *>(windowSurface);
     if (window->eglSurface() == EGL_NO_SURFACE)
         window->createEglSurface(g->eglDisplay, d->eglConfig);
diff --git a/src/plugins/platforms/winrt/qwinrtintegration.cpp b/src/plugins/platforms/winrt/qwinrtintegration.cpp
index 9db5df995ad5e0313c2ddd79b7e811205b5c3190..71e92f33ca518b078c0af742658d7005cf8dd268 100644
--- a/src/plugins/platforms/winrt/qwinrtintegration.cpp
+++ b/src/plugins/platforms/winrt/qwinrtintegration.cpp
@@ -49,6 +49,8 @@
 #include <QtGui/QOpenGLContext>
 #include <qfunctions_winrt.h>
 
+#include <qpa/qplatformoffscreensurface.h>
+
 #include <functional>
 #include <wrl.h>
 #include <windows.ui.xaml.h>
@@ -79,6 +81,7 @@ typedef IEventHandler<IInspectable *> ResumeHandler;
 typedef IEventHandler<SuspendingEventArgs *> SuspendHandler;
 #ifdef Q_OS_WINPHONE
 typedef IEventHandler<BackPressedEventArgs*> BackPressedHandler;
+typedef IEventHandler<CameraEventArgs*> CameraButtonHandler;
 #endif
 
 QT_BEGIN_NAMESPACE
@@ -88,6 +91,8 @@ uint qHash(CoreApplicationCallbackRemover key) { void *ptr = *(void **)(&key); r
 #ifdef Q_OS_WINPHONE
 typedef HRESULT (__stdcall IHardwareButtonsStatics::*HardwareButtonsCallbackRemover)(EventRegistrationToken);
 uint qHash(HardwareButtonsCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
+typedef HRESULT (__stdcall IHardwareButtonsStatics2::*HardwareButtons2CallbackRemover)(EventRegistrationToken);
+uint qHash(HardwareButtons2CallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
 #endif
 
 class QWinRTIntegrationPrivate
@@ -103,6 +108,10 @@ public:
 #ifdef Q_OS_WINPHONE
     ComPtr<IHardwareButtonsStatics> hardwareButtons;
     QHash<HardwareButtonsCallbackRemover, EventRegistrationToken> buttonsTokens;
+    ComPtr<IHardwareButtonsStatics2> cameraButtons;
+    QHash<HardwareButtons2CallbackRemover, EventRegistrationToken> cameraTokens;
+    bool cameraHalfPressed : 1;
+    bool cameraPressed : 1;
 #endif
 };
 
@@ -117,7 +126,7 @@ QWinRTIntegration::QWinRTIntegration() : d_ptr(new QWinRTIntegrationPrivate)
                                 IID_PPV_ARGS(&d->application));
     Q_ASSERT_SUCCEEDED(hr);
     hr = d->application->add_Suspending(Callback<SuspendHandler>(this, &QWinRTIntegration::onSuspended).Get(),
-                                        &d->applicationTokens[&ICoreApplication::remove_Resuming]);
+                                        &d->applicationTokens[&ICoreApplication::remove_Suspending]);
     Q_ASSERT_SUCCEEDED(hr);
     hr = d->application->add_Resuming(Callback<ResumeHandler>(this, &QWinRTIntegration::onResume).Get(),
                                       &d->applicationTokens[&ICoreApplication::remove_Resuming]);
@@ -130,6 +139,23 @@ QWinRTIntegration::QWinRTIntegration() : d_ptr(new QWinRTIntegrationPrivate)
     hr = d->hardwareButtons->add_BackPressed(Callback<BackPressedHandler>(this, &QWinRTIntegration::onBackButtonPressed).Get(),
                                              &d->buttonsTokens[&IHardwareButtonsStatics::remove_BackPressed]);
     Q_ASSERT_SUCCEEDED(hr);
+
+    hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Phone_UI_Input_HardwareButtons).Get(),
+                                IID_PPV_ARGS(&d->cameraButtons));
+    Q_ASSERT_SUCCEEDED(hr);
+    if (qEnvironmentVariableIntValue("QT_QPA_ENABLE_CAMERA_KEYS")) {
+        hr = d->cameraButtons->add_CameraPressed(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraPressed).Get(),
+                                                 &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraPressed]);
+        Q_ASSERT_SUCCEEDED(hr);
+        hr = d->cameraButtons->add_CameraHalfPressed(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraHalfPressed).Get(),
+                                                     &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraHalfPressed]);
+        Q_ASSERT_SUCCEEDED(hr);
+        hr = d->cameraButtons->add_CameraReleased(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraReleased).Get(),
+                                                  &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraReleased]);
+        Q_ASSERT_SUCCEEDED(hr);
+    }
+    d->cameraPressed = false;
+    d->cameraHalfPressed = false;
 #endif // Q_OS_WINPHONE
 
     QEventDispatcherWinRT::runOnXamlThread([d]() {
@@ -151,11 +177,20 @@ QWinRTIntegration::~QWinRTIntegration()
         hr = (d->hardwareButtons.Get()->*i.key())(i.value());
         Q_ASSERT_SUCCEEDED(hr);
     }
+    for (QHash<HardwareButtons2CallbackRemover, EventRegistrationToken>::const_iterator i = d->cameraTokens.begin(); i != d->cameraTokens.end(); ++i) {
+        hr = (d->cameraButtons.Get()->*i.key())(i.value());
+        Q_ASSERT_SUCCEEDED(hr);
+    }
 #endif
+    // Do not execute this on Windows Phone as the application is already
+    // shutting down and trying to unregister suspending/resume handler will
+    // cause exceptions and assert in debug mode
+#ifndef Q_OS_WINPHONE
     for (QHash<CoreApplicationCallbackRemover, EventRegistrationToken>::const_iterator i = d->applicationTokens.begin(); i != d->applicationTokens.end(); ++i) {
         hr = (d->application.Get()->*i.key())(i.value());
         Q_ASSERT_SUCCEEDED(hr);
     }
+#endif
     destroyScreen(d->mainScreen);
     Windows::Foundation::Uninitialize();
 }
@@ -268,6 +303,42 @@ HRESULT QWinRTIntegration::onBackButtonPressed(IInspectable *, IBackPressedEvent
     args->put_Handled(pressed || released);
     return S_OK;
 }
+
+HRESULT QWinRTIntegration::onCameraPressed(IInspectable *, ICameraEventArgs *)
+{
+    Q_D(QWinRTIntegration);
+    QWindow *window = d->mainScreen->topWindow();
+    QWindowSystemInterface::handleExtendedKeyEvent(window, QEvent::KeyPress, Qt::Key_Camera, Qt::NoModifier,
+                                                   0, 0, 0, QString(), false, 1, false);
+    d->cameraPressed = true;
+    return S_OK;
+}
+
+HRESULT QWinRTIntegration::onCameraHalfPressed(IInspectable *, ICameraEventArgs *)
+{
+    Q_D(QWinRTIntegration);
+    QWindow *window = d->mainScreen->topWindow();
+    QWindowSystemInterface::handleExtendedKeyEvent(window, QEvent::KeyPress, Qt::Key_CameraFocus, Qt::NoModifier,
+                                                   0, 0, 0, QString(), false, 1, false);
+    d->cameraHalfPressed = true;
+    return S_OK;
+}
+
+HRESULT QWinRTIntegration::onCameraReleased(IInspectable *, ICameraEventArgs *)
+{
+    Q_D(QWinRTIntegration);
+    QWindow *window = d->mainScreen->topWindow();
+    if (d->cameraHalfPressed)
+        QWindowSystemInterface::handleExtendedKeyEvent(window, QEvent::KeyRelease, Qt::Key_CameraFocus, Qt::NoModifier,
+                                                       0, 0, 0, QString(), false, 1, false);
+
+    if (d->cameraPressed)
+        QWindowSystemInterface::handleExtendedKeyEvent(window, QEvent::KeyRelease, Qt::Key_Camera, Qt::NoModifier,
+                                                       0, 0, 0, QString(), false, 1, false);
+    d->cameraHalfPressed = false;
+    d->cameraPressed = false;
+    return S_OK;
+}
 #endif // Q_OS_WINPHONE
 
 HRESULT QWinRTIntegration::onSuspended(IInspectable *, ISuspendingEventArgs *)
@@ -285,4 +356,14 @@ HRESULT QWinRTIntegration::onResume(IInspectable *, IInspectable *)
     return S_OK;
 }
 
+QPlatformOffscreenSurface *QWinRTIntegration::createPlatformOffscreenSurface(QOffscreenSurface *surface) const
+{
+    // This is only used for shutdown of applications.
+    // In case we do not return an empty surface the scenegraph will try
+    // to create a new native window during application exit causing crashes
+    // or assertions.
+    return new QPlatformOffscreenSurface(surface);
+}
+
+
 QT_END_NAMESPACE
diff --git a/src/plugins/platforms/winrt/qwinrtintegration.h b/src/plugins/platforms/winrt/qwinrtintegration.h
index 3a151e1ed889bf157f4492e0f75eb0675806c4d7..31a3ce7c1c4e2a8b74997cc78828e6c67721fa87 100644
--- a/src/plugins/platforms/winrt/qwinrtintegration.h
+++ b/src/plugins/platforms/winrt/qwinrtintegration.h
@@ -52,6 +52,7 @@ namespace ABI {
             namespace UI {
                 namespace Input {
                     struct IBackPressedEventArgs;
+                    struct ICameraEventArgs;
                 }
             }
         }
@@ -97,9 +98,13 @@ public:
     QStringList themeNames() const Q_DECL_OVERRIDE;
     QPlatformTheme *createPlatformTheme(const QString &name) const Q_DECL_OVERRIDE;
 
+    QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const Q_DECL_OVERRIDE;
 private:
 #ifdef Q_OS_WINPHONE
     HRESULT onBackButtonPressed(IInspectable *, ABI::Windows::Phone::UI::Input::IBackPressedEventArgs *args);
+    HRESULT onCameraPressed(IInspectable *, ABI::Windows::Phone::UI::Input::ICameraEventArgs *);
+    HRESULT onCameraHalfPressed(IInspectable *, ABI::Windows::Phone::UI::Input::ICameraEventArgs *);
+    HRESULT onCameraReleased(IInspectable *, ABI::Windows::Phone::UI::Input::ICameraEventArgs *);
 #endif
     HRESULT onSuspended(IInspectable *, ABI::Windows::ApplicationModel::ISuspendingEventArgs *);
     HRESULT onResume(IInspectable *, IInspectable *);
diff --git a/src/plugins/platforms/winrt/qwinrtscreen.cpp b/src/plugins/platforms/winrt/qwinrtscreen.cpp
index a6424433860685fd77d8bc20f0b97b888dcfc91a..997aa0d86cf1f572773dd017d546ad8bb6602e2e 100644
--- a/src/plugins/platforms/winrt/qwinrtscreen.cpp
+++ b/src/plugins/platforms/winrt/qwinrtscreen.cpp
@@ -779,6 +779,7 @@ void QWinRTScreen::addWindow(QWindow *window)
     d->visibleWindows.prepend(window);
     QWindowSystemInterface::handleWindowActivated(window, Qt::OtherFocusReason);
     handleExpose();
+    QWindowSystemInterface::flushWindowSystemEvents();
 }
 
 void QWinRTScreen::removeWindow(QWindow *window)
@@ -796,6 +797,7 @@ void QWinRTScreen::removeWindow(QWindow *window)
     if (wasTopWindow)
         QWindowSystemInterface::handleWindowActivated(window, Qt::OtherFocusReason);
     handleExpose();
+    QWindowSystemInterface::flushWindowSystemEvents();
 }
 
 void QWinRTScreen::raise(QWindow *window)
diff --git a/src/plugins/platforms/xcb/README b/src/plugins/platforms/xcb/README
index 2f666bebfd4826804aa786f4eb274b636e9b2b22..15cf4cf24159716a7a9536bdab2265803f7b8c0d 100644
--- a/src/plugins/platforms/xcb/README
+++ b/src/plugins/platforms/xcb/README
@@ -3,14 +3,14 @@ Requires libxcb >= 1.5.
 PACKAGE DEPENDENCIES
 
 Required packages:
-libxcb1 libxcb1-dev libx11-xcb1 libx11-xcb-dev libxcb-keysyms1 libxcb-keysyms1-dev libxcb-image0 libxcb-image0-dev libxcb-shm0 libxcb-shm0-dev libxcb-icccm1 libxcb-icccm1-dev libxcb-sync0 libxcb-sync0-dev libxcb-render-util0 libxcb-render-util0-dev libxcb-xfixes0-dev libxrender-dev libxcb-shape0-dev libxcb-randr0-dev libxcb-glx0-dev
+libxcb1 libxcb1-dev libx11-xcb1 libx11-xcb-dev libxcb-keysyms1 libxcb-keysyms1-dev libxcb-image0 libxcb-image0-dev libxcb-shm0 libxcb-shm0-dev libxcb-icccm1 libxcb-icccm1-dev libxcb-sync0 libxcb-sync0-dev libxcb-render-util0 libxcb-render-util0-dev libxcb-xfixes0-dev libxrender-dev libxcb-shape0-dev libxcb-randr0-dev libxcb-glx0-dev libxcb-xinerama0-dev
 
 On Ubuntu 11.10 icccm1 is replaced by icccm4 and xcb-render-util is not available:
-libxcb1 libxcb1-dev libx11-xcb1 libx11-xcb-dev libxcb-keysyms1 libxcb-keysyms1-dev libxcb-image0 libxcb-image0-dev libxcb-shm0 libxcb-shm0-dev libxcb-icccm4 libxcb-icccm4-dev libxcb-sync0 libxcb-sync0-dev libxcb-xfixes0-dev libxrender-dev libxcb-shape0-dev libxcb-randr0-dev libxcb-glx0-dev
+libxcb1 libxcb1-dev libx11-xcb1 libx11-xcb-dev libxcb-keysyms1 libxcb-keysyms1-dev libxcb-image0 libxcb-image0-dev libxcb-shm0 libxcb-shm0-dev libxcb-icccm4 libxcb-icccm4-dev libxcb-sync0 libxcb-sync0-dev libxcb-xfixes0-dev libxrender-dev libxcb-shape0-dev libxcb-randr0-dev libxcb-glx0-dev libxcb-xinerama0-dev
 The packages for xcb-render-util can be installed manually from http://packages.ubuntu.com/natty/libxcb-render-util0 and http://packages.ubuntu.com/natty/libxcb-render-util0-dev
 
 On Ubuntu 12.04 icccm1 is replaced by icccm4 and xcb-render-util can be installed automatically:
-libxcb1 libxcb1-dev libx11-xcb1 libx11-xcb-dev libxcb-keysyms1 libxcb-keysyms1-dev libxcb-image0 libxcb-image0-dev libxcb-shm0 libxcb-shm0-dev libxcb-icccm4 libxcb-icccm4-dev libxcb-sync0 libxcb-sync0-dev libxcb-xfixes0-dev libxrender-dev libxcb-shape0-dev libxcb-randr0-dev libxcb-render-util0 libxcb-render-util0-dev libxcb-glx0-dev
+libxcb1 libxcb1-dev libx11-xcb1 libx11-xcb-dev libxcb-keysyms1 libxcb-keysyms1-dev libxcb-image0 libxcb-image0-dev libxcb-shm0 libxcb-shm0-dev libxcb-icccm4 libxcb-icccm4-dev libxcb-sync0 libxcb-sync0-dev libxcb-xfixes0-dev libxrender-dev libxcb-shape0-dev libxcb-randr0-dev libxcb-render-util0 libxcb-render-util0-dev libxcb-glx0-dev libxcb-xinerama0-dev
 
 
 On Fedora, the following packages are required:
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
index 37f01d4eed2bf3fcd49447ce3c81981c46230767..4cb220a02fb3efac4e6eb94d47501232e5358e1c 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
@@ -175,7 +175,11 @@ QGLXContext::QGLXContext(QXcbScreen *screen, const QSurfaceFormat &format, QPlat
 void QGLXContext::init(QXcbScreen *screen, QPlatformOpenGLContext *share)
 {
     if (m_format.renderableType() == QSurfaceFormat::DefaultRenderableType)
+#if defined(QT_OPENGL_ES_2)
+        m_format.setRenderableType(QSurfaceFormat::OpenGLES);
+#else
         m_format.setRenderableType(QSurfaceFormat::OpenGL);
+#endif
     if (m_format.renderableType() != QSurfaceFormat::OpenGL && m_format.renderableType() != QSurfaceFormat::OpenGLES)
         return;
 
diff --git a/src/plugins/platforms/xcb/qxcbbackingstore.cpp b/src/plugins/platforms/xcb/qxcbbackingstore.cpp
index 1825a463d070dd8b9b03ee9764b0495903c16c14..006df320febed059f2efdaf72893f08b958093de 100644
--- a/src/plugins/platforms/xcb/qxcbbackingstore.cpp
+++ b/src/plugins/platforms/xcb/qxcbbackingstore.cpp
@@ -51,6 +51,7 @@
 #include <qscreen.h>
 #include <QtGui/private/qhighdpiscaling_p.h>
 #include <qpa/qplatformgraphicsbuffer.h>
+#include <private/qimage_p.h>
 
 #include <algorithm>
 QT_BEGIN_NAMESPACE
@@ -172,6 +173,9 @@ QXcbShmImage::QXcbShmImage(QXcbScreen *screen, const QSize &size, uint depth, QI
             qWarning() << "QXcbBackingStore: Error while marking the shared memory segment to be destroyed";
     }
 
+    if (QImage::toPixelFormat(format).alphaUsage() == QPixelFormat::IgnoresAlpha)
+        format = qt_alphaVersionForPainting(format);
+
     m_qimage = QImage( (uchar*) m_xcb_image->data, m_xcb_image->width, m_xcb_image->height, m_xcb_image->stride, format);
     m_graphics_buffer = new QXcbShmGraphicsBuffer(&m_qimage);
 }
diff --git a/src/plugins/platforms/xcb/qxcbconnection.cpp b/src/plugins/platforms/xcb/qxcbconnection.cpp
index 231fe9af3f3cd59a3d9769695872bbb2dd3bd726..abb48034cd6a8a920176113e2ab97ee0a2fffd53 100644
--- a/src/plugins/platforms/xcb/qxcbconnection.cpp
+++ b/src/plugins/platforms/xcb/qxcbconnection.cpp
@@ -60,6 +60,7 @@
 #include <xcb/shm.h>
 #include <xcb/sync.h>
 #include <xcb/xfixes.h>
+#include <xcb/xinerama.h>
 
 #ifdef XCB_USE_XLIB
 #include <X11/Xlib.h>
@@ -386,6 +387,7 @@ void QXcbConnection::initializeScreens()
         xcb_screen_t *xcbScreen = it.data;
         QXcbVirtualDesktop *virtualDesktop = new QXcbVirtualDesktop(this, xcbScreen, xcbScreenNumber);
         m_virtualDesktops.append(virtualDesktop);
+        QList<QPlatformScreen *> siblings;
         if (has_randr_extension) {
             xcb_generic_error_t *error = NULL;
             // RRGetScreenResourcesCurrent is fast but it may return nothing if the
@@ -429,7 +431,6 @@ void QXcbConnection::initializeScreens()
                         qWarning("failed to get the primary output of the screen");
                         free(error);
                     } else {
-                        QList<QPlatformScreen *> siblings;
                         for (int i = 0; i < outputCount; i++) {
                             QScopedPointer<xcb_randr_get_output_info_reply_t, QScopedPointerPodDeleter> output(
                                     xcb_randr_get_output_info_reply(xcb_connection(),
@@ -471,12 +472,30 @@ void QXcbConnection::initializeScreens()
                                 }
                             }
                         }
-                        virtualDesktop->setScreens(siblings);
                     }
                 }
             }
+        } else if (has_xinerama_extension) {
+            // Xinerama is available
+            xcb_xinerama_query_screens_cookie_t cookie = xcb_xinerama_query_screens(m_connection);
+            xcb_xinerama_query_screens_reply_t *screens = xcb_xinerama_query_screens_reply(m_connection,
+                                                                                           cookie,
+                                                                                           Q_NULLPTR);
+            if (screens) {
+                xcb_xinerama_screen_info_iterator_t it = xcb_xinerama_query_screens_screen_info_iterator(screens);
+                while (it.rem) {
+                    xcb_xinerama_screen_info_t *screen_info = it.data;
+                    QXcbScreen *screen = new QXcbScreen(this, virtualDesktop,
+                                                        XCB_NONE, Q_NULLPTR,
+                                                        screen_info, it.index);
+                    siblings << screen;
+                    m_screens << screen;
+                    xcb_xinerama_screen_info_next(&it);
+                }
+                free(screens);
+            }
         }
-        if (virtualDesktop->screens().isEmpty()) {
+        if (siblings.isEmpty()) {
             // If there are no XRandR outputs or XRandR extension is missing,
             // then create a fake/legacy screen.
             QXcbScreen *screen = new QXcbScreen(this, virtualDesktop, XCB_NONE, Q_NULLPTR);
@@ -486,8 +505,9 @@ void QXcbConnection::initializeScreens()
                 primaryScreen = screen;
                 primaryScreen->setPrimary(true);
             }
-            virtualDesktop->addScreen(screen);
+            siblings << screen;
         }
+        virtualDesktop->setScreens(siblings);
         xcb_screen_next(&it);
         ++xcbScreenNumber;
     } // for each xcb screen
@@ -529,12 +549,14 @@ QXcbConnection::QXcbConnection(QXcbNativeInterface *nativeInterface, bool canGra
     , xfixes_first_event(0)
     , xrandr_first_event(0)
     , xkb_first_event(0)
+    , has_xinerama_extension(false)
     , has_shape_extension(false)
     , has_randr_extension(false)
     , has_input_shape(false)
     , has_xkb(false)
     , m_buttons(0)
     , m_focusWindow(0)
+    , m_mouseGrabber(0)
     , m_clientLeader(0)
     , m_systemTrayTracker(0)
     , m_glIntegration(Q_NULLPTR)
@@ -583,7 +605,10 @@ QXcbConnection::QXcbConnection(QXcbNativeInterface *nativeInterface, bool canGra
     m_time = XCB_CURRENT_TIME;
     m_netWmUserTime = XCB_CURRENT_TIME;
 
-    initializeXRandr();
+    if (!qEnvironmentVariableIsSet("QT_XCB_NO_XRANDR"))
+        initializeXRandr();
+    if (!has_randr_extension)
+        initializeXinerama();
     initializeXFixes();
     initializeScreens();
 
@@ -1328,6 +1353,10 @@ void QXcbConnection::setFocusWindow(QXcbWindow *w)
 {
     m_focusWindow = w;
 }
+void QXcbConnection::setMouseGrabber(QXcbWindow *w)
+{
+    m_mouseGrabber = w;
+}
 
 void QXcbConnection::grabServer()
 {
@@ -2087,6 +2116,22 @@ void QXcbConnection::initializeXRandr()
     }
 }
 
+void QXcbConnection::initializeXinerama()
+{
+    const xcb_query_extension_reply_t *reply = xcb_get_extension_data(m_connection, &xcb_xinerama_id);
+    if (!reply || !reply->present)
+        return;
+
+    xcb_generic_error_t *error = Q_NULLPTR;
+    xcb_xinerama_is_active_cookie_t xinerama_query_cookie = xcb_xinerama_is_active(m_connection);
+    xcb_xinerama_is_active_reply_t *xinerama_is_active = xcb_xinerama_is_active_reply(m_connection,
+                                                                                      xinerama_query_cookie,
+                                                                                      &error);
+    has_xinerama_extension = xinerama_is_active && !error && xinerama_is_active->state;
+    free(error);
+    free(xinerama_is_active);
+}
+
 void QXcbConnection::initializeXShape()
 {
     const xcb_query_extension_reply_t *xshape_reply = xcb_get_extension_data(m_connection, &xcb_shape_id);
@@ -2174,7 +2219,9 @@ void QXcbConnection::initializeXKB()
 bool QXcbConnection::xi2MouseEvents() const
 {
     static bool mouseViaXI2 = !qEnvironmentVariableIsSet("QT_XCB_NO_XI2_MOUSE");
-    return mouseViaXI2;
+    // Don't use XInput2 when Xinerama extension is enabled,
+    // because it causes problems with multi-monitor setup.
+    return mouseViaXI2 && !has_xinerama_extension;
 }
 
 #if defined(XCB_USE_XINPUT2)
diff --git a/src/plugins/platforms/xcb/qxcbconnection.h b/src/plugins/platforms/xcb/qxcbconnection.h
index fb7cc137b97477a6213229e5d4b0d06801052a9e..a6a7b9e7ca1898fe2add7a51107bfc9e535d9b44 100644
--- a/src/plugins/platforms/xcb/qxcbconnection.h
+++ b/src/plugins/platforms/xcb/qxcbconnection.h
@@ -469,6 +469,8 @@ public:
 
     QXcbWindow *focusWindow() const { return m_focusWindow; }
     void setFocusWindow(QXcbWindow *);
+    QXcbWindow *mouseGrabber() const { return m_mouseGrabber; }
+    void setMouseGrabber(QXcbWindow *);
 
     QByteArray startupId() const { return m_startupId; }
     void setStartupId(const QByteArray &nextId) { m_startupId = nextId; }
@@ -515,6 +517,7 @@ private:
     void initializeXFixes();
     void initializeXRender();
     void initializeXRandr();
+    void initializeXinerama();
     void initializeXShape();
     void initializeXKB();
     void handleClientMessageEvent(const xcb_client_message_event_t *event);
@@ -639,6 +642,7 @@ private:
     uint32_t xrandr_first_event;
     uint32_t xkb_first_event;
 
+    bool has_xinerama_extension;
     bool has_shape_extension;
     bool has_randr_extension;
     bool has_input_shape;
@@ -647,6 +651,7 @@ private:
     Qt::MouseButtons m_buttons;
 
     QXcbWindow *m_focusWindow;
+    QXcbWindow *m_mouseGrabber;
 
     xcb_window_t m_clientLeader;
     QByteArray m_startupId;
diff --git a/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp b/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
index 1a123703a55091cf2390873ea890a6d70e5f8809..1b84de483448b29bbd050983bbb7bdaca1aa3339 100644
--- a/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
+++ b/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
@@ -274,7 +274,7 @@ void QXcbConnection::finalizeXInput2()
 
 void QXcbConnection::xi2Select(xcb_window_t window)
 {
-    if (!m_xi2Enabled)
+    if (!m_xi2Enabled || window == rootWindow())
         return;
 
     Display *xDisplay = static_cast<Display *>(m_xlib_display);
diff --git a/src/plugins/platforms/xcb/qxcbdrag.cpp b/src/plugins/platforms/xcb/qxcbdrag.cpp
index d19ea241f1e22c4528cb8464c1c0dd82b0d0972c..9296a6d1410f72d00efcf8c249bdd8a037b8b4be 100644
--- a/src/plugins/platforms/xcb/qxcbdrag.cpp
+++ b/src/plugins/platforms/xcb/qxcbdrag.cpp
@@ -194,6 +194,8 @@ void QXcbDrag::startDrag()
 
     setUseCompositing(current_virtual_desktop->compositingActive());
     QBasicDrag::startDrag();
+    if (connection()->mouseGrabber() == Q_NULLPTR)
+        shapedPixmapWindow()->setMouseGrabEnabled(true);
 }
 
 void QXcbDrag::endDrag()
diff --git a/src/plugins/platforms/xcb/qxcbscreen.cpp b/src/plugins/platforms/xcb/qxcbscreen.cpp
index f05432ef6855c660fa484a9d7519a80a236ce54f..f3d381b99e014116317286b791a0876ad6d8ca6d 100644
--- a/src/plugins/platforms/xcb/qxcbscreen.cpp
+++ b/src/plugins/platforms/xcb/qxcbscreen.cpp
@@ -70,7 +70,7 @@ QXcbVirtualDesktop::~QXcbVirtualDesktop()
 QXcbScreen *QXcbVirtualDesktop::screenAt(const QPoint &pos) const
 {
     foreach (QXcbScreen *screen, connection()->screens()) {
-        if (screen->virtualDesktop() == this && screen->nativeGeometry().contains(pos))
+        if (screen->virtualDesktop() == this && screen->geometry().contains(pos))
             return screen;
     }
     return Q_NULLPTR;
@@ -155,8 +155,15 @@ void QXcbVirtualDesktop::updateWorkArea()
     }
 }
 
+static inline QSizeF sizeInMillimeters(const QSize &size, const QDpi &dpi)
+{
+    return QSizeF(Q_MM_PER_INCH * size.width() / dpi.first,
+                  Q_MM_PER_INCH * size.height() / dpi.second);
+}
+
 QXcbScreen::QXcbScreen(QXcbConnection *connection, QXcbVirtualDesktop *virtualDesktop,
-                       xcb_randr_output_t outputId, xcb_randr_get_output_info_reply_t *output)
+                       xcb_randr_output_t outputId, xcb_randr_get_output_info_reply_t *output,
+                       const xcb_xinerama_screen_info_t *xineramaScreenInfo, int xineramaScreenIdx)
     : QXcbObject(connection)
     , m_virtualDesktop(virtualDesktop)
     , m_output(outputId)
@@ -188,14 +195,18 @@ QXcbScreen::QXcbScreen(QXcbConnection *connection, QXcbVirtualDesktop *virtualDe
             updateRefreshRate(crtc->mode);
             free(crtc);
         }
-    } else {
-        updateGeometry(output ? output->timestamp : 0);
+    } else if (xineramaScreenInfo) {
+        m_geometry = QRect(xineramaScreenInfo->x_org, xineramaScreenInfo->y_org,
+                           xineramaScreenInfo->width, xineramaScreenInfo->height);
+        m_availableGeometry = m_geometry & m_virtualDesktop->workArea();
+        m_sizeMillimeters = sizeInMillimeters(m_geometry.size(), virtualDpi());
+        if (xineramaScreenIdx > -1)
+            m_outputName += QLatin1Char('-') + QString::number(xineramaScreenIdx);
     }
 
-    if (m_geometry.isEmpty()) {
+    if (m_geometry.isEmpty())
         m_geometry = QRect(QPoint(), m_virtualSize);
-        m_nativeGeometry = QRect(QPoint(), m_virtualSize);
-    }
+
     if (m_availableGeometry.isEmpty())
         m_availableGeometry = m_geometry;
 
@@ -538,16 +549,12 @@ void QXcbScreen::updateGeometry(const QRect &geom, uint8_t rotation)
     // It can be that physical size is unknown while virtual size
     // is known (probably back-calculated from DPI and resolution),
     // e.g. on VNC or with some hardware.
-    if (m_sizeMillimeters.isEmpty()) {
-        QDpi dpi = virtualDpi();
-        m_sizeMillimeters = QSizeF(Q_MM_PER_INCH * xGeometry.width() / dpi.first,
-                                   Q_MM_PER_INCH * xGeometry.width() / dpi.second);
-    }
+    if (m_sizeMillimeters.isEmpty())
+        m_sizeMillimeters = sizeInMillimeters(xGeometry.size(), virtualDpi());
 
     qreal dpi = xGeometry.width() / physicalSize().width() * qreal(25.4);
     m_pixelDensity = qRound(dpi/96);
     m_geometry = QRect(xGeometry.topLeft(), xGeometry.size());
-    m_nativeGeometry = QRect(xGeometry.topLeft(), xGeometry.size());
     m_availableGeometry = xGeometry & m_virtualDesktop->workArea();
     QWindowSystemInterface::handleScreenGeometryChange(QPlatformScreen::screen(), m_geometry, m_availableGeometry);
 }
@@ -818,9 +825,7 @@ QDebug operator<<(QDebug debug, const QXcbScreen *screen)
         debug << ", screenNumber=" << screen->screenNumber();
         debug << ", virtualSize=" << screen->virtualSize().width() << 'x' << screen->virtualSize().height() << " (";
         formatSizeF(debug, screen->virtualSize());
-        debug << "), nativeGeometry=";
-        formatRect(debug, screen->nativeGeometry());
-        debug << ", orientation=" << screen->orientation();
+        debug << "), orientation=" << screen->orientation();
         debug << ", depth=" << screen->depth();
         debug << ", refreshRate=" << screen->refreshRate();
         debug << ", root=" << hex << screen->root();
diff --git a/src/plugins/platforms/xcb/qxcbscreen.h b/src/plugins/platforms/xcb/qxcbscreen.h
index 79620f40ec11af79dc1f110b12f4a41e07a5ef1c..f4de2b9dfd5e3042f4192b85c8e7b9b79aa04e74 100644
--- a/src/plugins/platforms/xcb/qxcbscreen.h
+++ b/src/plugins/platforms/xcb/qxcbscreen.h
@@ -40,6 +40,7 @@
 #include <xcb/xcb.h>
 #include <xcb/randr.h>
 #include <xcb/xfixes.h>
+#include <xcb/xinerama.h>
 
 #include "qxcbobject.h"
 #include "qxcbscreen.h"
@@ -102,7 +103,8 @@ class Q_XCB_EXPORT QXcbScreen : public QXcbObject, public QPlatformScreen
 {
 public:
     QXcbScreen(QXcbConnection *connection, QXcbVirtualDesktop *virtualDesktop,
-               xcb_randr_output_t outputId, xcb_randr_get_output_info_reply_t *outputInfo);
+               xcb_randr_output_t outputId, xcb_randr_get_output_info_reply_t *outputInfo,
+               const xcb_xinerama_screen_info_t *xineramaScreenInfo = Q_NULLPTR, int xineramaScreenIdx = -1);
     ~QXcbScreen();
 
     QString getOutputName(xcb_randr_get_output_info_reply_t *outputInfo);
@@ -112,7 +114,6 @@ public:
     QWindow *topLevelAt(const QPoint &point) const Q_DECL_OVERRIDE;
 
     QRect geometry() const Q_DECL_OVERRIDE { return m_geometry; }
-    QRect nativeGeometry() const { return m_nativeGeometry; }
     QRect availableGeometry() const Q_DECL_OVERRIDE {return m_availableGeometry;}
     int depth() const Q_DECL_OVERRIDE { return screen()->root_depth; }
     QImage::Format format() const Q_DECL_OVERRIDE;
@@ -184,7 +185,6 @@ private:
     QSizeF m_outputSizeMillimeters;
     QSizeF m_sizeMillimeters;
     QRect m_geometry;
-    QRect m_nativeGeometry;
     QRect m_availableGeometry;
     QSize m_virtualSize;
     QSizeF m_virtualSizeMillimeters;
diff --git a/src/plugins/platforms/xcb/qxcbwindow.cpp b/src/plugins/platforms/xcb/qxcbwindow.cpp
index bec167fec2a8159e476361c44176334c5129b6aa..4e4a0cdaefdab0f8af8f47d2fe68884cf905e652 100644
--- a/src/plugins/platforms/xcb/qxcbwindow.cpp
+++ b/src/plugins/platforms/xcb/qxcbwindow.cpp
@@ -594,12 +594,16 @@ QXcbWindow::~QXcbWindow()
 {
     if (window()->type() != Qt::ForeignWindow)
         destroy();
+    else if (connection()->mouseGrabber() == this)
+        connection()->setMouseGrabber(Q_NULLPTR);
 }
 
 void QXcbWindow::destroy()
 {
     if (connection()->focusWindow() == this)
         doFocusOut();
+    if (connection()->mouseGrabber() == this)
+        connection()->setMouseGrabber(Q_NULLPTR);
 
     if (m_syncCounter && m_usingSyncProtocol)
         Q_XCB_CALL(xcb_sync_destroy_counter(xcb_connection(), m_syncCounter));
@@ -847,6 +851,9 @@ void QXcbWindow::hide()
 
     xcb_flush(xcb_connection());
 
+    if (connection()->mouseGrabber() == this)
+        connection()->setMouseGrabber(Q_NULLPTR);
+
     m_mapped = false;
 }
 
@@ -2357,6 +2364,8 @@ void QXcbWindow::handlePropertyNotifyEvent(const xcb_property_notify_event_t *ev
             QWindowSystemInterface::handleWindowStateChanged(window(), newState);
             m_lastWindowStateEvent = newState;
             m_windowState = newState;
+            if (m_windowState == Qt::WindowMinimized && connection()->mouseGrabber() == this)
+                connection()->setMouseGrabber(Q_NULLPTR);
         }
         return;
     } else if (event->atom == atom(QXcbAtom::_NET_FRAME_EXTENTS)) {
@@ -2411,9 +2420,15 @@ bool QXcbWindow::setKeyboardGrabEnabled(bool grab)
 
 bool QXcbWindow::setMouseGrabEnabled(bool grab)
 {
+    if (!grab && connection()->mouseGrabber() == this)
+        connection()->setMouseGrabber(Q_NULLPTR);
 #ifdef XCB_USE_XINPUT22
-    if (connection()->xi2MouseEvents())
-        return connection()->xi2SetMouseGrabEnabled(m_window, grab);
+    if (connection()->xi2MouseEvents()) {
+        bool result = connection()->xi2SetMouseGrabEnabled(m_window, grab);
+        if (grab && result)
+            connection()->setMouseGrabber(this);
+        return result;
+    }
 #endif
     if (grab && !connection()->canGrab())
         return false;
@@ -2432,6 +2447,8 @@ bool QXcbWindow::setMouseGrabEnabled(bool grab)
     xcb_grab_pointer_reply_t *reply = xcb_grab_pointer_reply(xcb_connection(), cookie, NULL);
     bool result = !(!reply || reply->status != XCB_GRAB_STATUS_SUCCESS);
     free(reply);
+    if (result)
+        connection()->setMouseGrabber(this);
     return result;
 }
 
diff --git a/src/plugins/platforms/xcb/qxcbwindow.h b/src/plugins/platforms/xcb/qxcbwindow.h
index 69c081995918213475b44b5caa2ee833df744b59..3cfa71c9e014af6a69e4f3a24eb4b51453698b60 100644
--- a/src/plugins/platforms/xcb/qxcbwindow.h
+++ b/src/plugins/platforms/xcb/qxcbwindow.h
@@ -167,7 +167,6 @@ public:
 
     virtual void create();
     virtual void destroy();
-    QXcbScreen *screenForNativeGeometry(const QRect &newGeometry) const;
 
 public Q_SLOTS:
     void updateSyncRequestCounter();
diff --git a/src/plugins/platforms/xcb/xcb-static/xcb-static.pro b/src/plugins/platforms/xcb/xcb-static/xcb-static.pro
index d0fe282b147139c2554048a1e62c9b3e47653af2..20481e48344627fa97cbe5d740b8a62fff0a59b4 100644
--- a/src/plugins/platforms/xcb/xcb-static/xcb-static.pro
+++ b/src/plugins/platforms/xcb/xcb-static/xcb-static.pro
@@ -1,7 +1,8 @@
 #
 # Statically compile in code for
 # libxcb-fixes, libxcb-randr, libxcb-shm, libxcb-sync, libxcb-image,
-# libxcb-keysyms, libxcb-icccm, libxcb-renderutil, libxcb-xkb
+# libxcb-keysyms, libxcb-icccm, libxcb-renderutil, libxcb-xkb,
+# libxcb-xinerama
 #
 CONFIG += static
 load(qt_helper_lib)
@@ -28,7 +29,8 @@ SOURCES += \
     $$LIBXCB_DIR/sync.c \
     $$LIBXCB_DIR/render.c \
     $$LIBXCB_DIR/shape.c \
-    $$LIBXCB_DIR/xkb.c
+    $$LIBXCB_DIR/xkb.c \
+    $$LIBXCB_DIR/xinerama.c
 
 #
 # xcb-util
diff --git a/src/plugins/platforms/xcb/xcb_qpa_lib.pro b/src/plugins/platforms/xcb/xcb_qpa_lib.pro
index 60eb8a02e31d2e36e88b11cedab854e901e0148e..302d87e0079764d148c1311fa7c77336bcfe316c 100644
--- a/src/plugins/platforms/xcb/xcb_qpa_lib.pro
+++ b/src/plugins/platforms/xcb/xcb_qpa_lib.pro
@@ -92,7 +92,7 @@ contains(QT_CONFIG, xcb-qt) {
     INCLUDEPATH += $$XCB_DIR/include $$XCB_DIR/sysinclude
     LIBS += -lxcb -L$$OUT_PWD/xcb-static -lxcb-static
 } else {
-    LIBS += -lxcb -lxcb-image -lxcb-icccm -lxcb-sync -lxcb-xfixes -lxcb-shm -lxcb-randr -lxcb-shape -lxcb-keysyms
+    LIBS += -lxcb -lxcb-image -lxcb-icccm -lxcb-sync -lxcb-xfixes -lxcb-shm -lxcb-randr -lxcb-shape -lxcb-keysyms -lxcb-xinerama
     !contains(DEFINES, QT_NO_XKB):LIBS += -lxcb-xkb
 }
 
diff --git a/src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.cpp b/src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.cpp
index 2f0bceafe683368b11962f574b24306582dc845e..857f373759ab58791e7571d2d9851b0f6a04d368 100644
--- a/src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.cpp
+++ b/src/plugins/platformthemes/gtk2/qgtk2dialoghelpers.cpp
@@ -71,6 +71,9 @@ Q_SIGNALS:
 protected:
     static void onResponse(QGtk2Dialog *dialog, int response);
 
+private slots:
+    void onParentWindowDestroyed();
+
 private:
     GtkWidget *gtkWidget;
 };
@@ -108,6 +111,8 @@ void QGtk2Dialog::exec()
 
 bool QGtk2Dialog::show(Qt::WindowFlags flags, Qt::WindowModality modality, QWindow *parent)
 {
+    connect(parent, &QWindow::destroyed, this, &QGtk2Dialog::onParentWindowDestroyed,
+            Qt::UniqueConnection);
     setParent(parent);
     setFlags(flags);
     setModality(modality);
@@ -144,6 +149,12 @@ void QGtk2Dialog::onResponse(QGtk2Dialog *dialog, int response)
         emit dialog->reject();
 }
 
+void QGtk2Dialog::onParentWindowDestroyed()
+{
+    // The QGtk2*DialogHelper classes own this object. Make sure the parent doesn't delete it.
+    setParent(0);
+}
+
 QGtk2ColorDialogHelper::QGtk2ColorDialogHelper()
 {
     d.reset(new QGtk2Dialog(gtk_color_selection_dialog_new("")));
diff --git a/src/src.pro b/src/src.pro
index 98802268399322159c2702801397f40f1fef2a4b..5ce647088332f6335bf90386f94e57b04cc9f2ba 100644
--- a/src/src.pro
+++ b/src/src.pro
@@ -68,6 +68,7 @@ src_xml.depends = src_corelib
 src_dbus.subdir = $$PWD/dbus
 src_dbus.target = sub-dbus
 src_dbus.depends = src_corelib
+force_bootstrap: src_dbus.depends += src_tools_bootstrap_dbus  # avoid syncqt race
 
 src_concurrent.subdir = $$PWD/concurrent
 src_concurrent.target = sub-concurrent
@@ -144,9 +145,8 @@ TOOLS = src_tools_moc src_tools_rcc src_tools_qlalr src_tools_nacldeployqt
 win32:SUBDIRS += src_winmain
 SUBDIRS += src_network src_sql src_xml src_testlib
 contains(QT_CONFIG, dbus) {
-    SUBDIRS += src_dbus
     force_bootstrap: SUBDIRS += src_tools_bootstrap_dbus
-    SUBDIRS += src_tools_qdbusxml2cpp src_tools_qdbuscpp2xml
+    SUBDIRS += src_dbus src_tools_qdbusxml2cpp src_tools_qdbuscpp2xml
     TOOLS += src_tools_qdbusxml2cpp src_tools_qdbuscpp2xml
     contains(QT_CONFIG, accessibility-atspi-bridge): \
         src_platformsupport.depends += src_dbus src_tools_qdbusxml2cpp
diff --git a/src/testlib/qtestcase.cpp b/src/testlib/qtestcase.cpp
index 60161d0bd4792e7268c36b46a78142b149cbb8fa..98a14f845903fca677c055bd3e9bbcabf9c82523 100644
--- a/src/testlib/qtestcase.cpp
+++ b/src/testlib/qtestcase.cpp
@@ -3682,10 +3682,6 @@ bool QTest::compare_string_helper(const char *t1, const char *t2, const char *ac
     \internal
 */
 
-/*! \fn bool QTest::qCompare(bool const &t1, int const &t2, const char *actual, const char *expected, const char *file, int line)
-  \internal
- */
-
 /*! \fn bool QTest::qTest(const T& actual, const char *elementName, const char *actualStr, const char *expected, const char *file, int line)
     \internal
 */
diff --git a/src/testlib/qtesttable.cpp b/src/testlib/qtesttable.cpp
index d20bdd846799e09dbd27f57ab907ec53e900886f..05cce37a47dec5425d753343acc22cf604e08eb3 100644
--- a/src/testlib/qtesttable.cpp
+++ b/src/testlib/qtesttable.cpp
@@ -46,6 +46,11 @@ QT_BEGIN_NAMESPACE
 class QTestTablePrivate
 {
 public:
+    ~QTestTablePrivate()
+    {
+        qDeleteAll(dataList.begin(), dataList.end());
+    }
+
     struct Element {
         Element() : name(Q_NULLPTR), type(0) {}
         Element(const char *n, int t) : name(n), type(t) {}
diff --git a/src/tools/bootstrap-dbus/bootstrap-dbus.pro b/src/tools/bootstrap-dbus/bootstrap-dbus.pro
index fb06b4d8a229b417e247003ef72b18147d4ed773..4c466ba0e940b1b07950e9d54c5664eff29db20a 100644
--- a/src/tools/bootstrap-dbus/bootstrap-dbus.pro
+++ b/src/tools/bootstrap-dbus/bootstrap-dbus.pro
@@ -2,16 +2,12 @@ option(host_build)
 
 MODULE = bootstrap_dbus
 TARGET = QtBootstrapDBus
-CONFIG += no_module_headers internal_module force_bootstrap
+CONFIG += minimal_syncqt internal_module force_bootstrap
 
 DEFINES += \
     QT_NO_CAST_FROM_ASCII
 
-MODULE_INCLUDES = \
-    \$\$QT_MODULE_INCLUDE_BASE/QtDBus
-MODULE_PRIVATE_INCLUDES = \
-    \$\$QT_MODULE_INCLUDE_BASE/QtDBus/$$QT_VERSION \
-    \$\$QT_MODULE_INCLUDE_BASE/QtDBus/$$QT_VERSION/QtDBus
+MODULE_INCNAME = QtDBus
 
 load(qt_module)
 
diff --git a/src/tools/bootstrap/bootstrap.pro b/src/tools/bootstrap/bootstrap.pro
index 6cadb7664eb609afcdf17953c721d6f931c0c2b8..5fe3ccdc6a22f7ee04e5257e7dc83a06023072eb 100644
--- a/src/tools/bootstrap/bootstrap.pro
+++ b/src/tools/bootstrap/bootstrap.pro
@@ -2,8 +2,9 @@ option(host_build)
 
 TARGET = QtBootstrap
 QT =
-CONFIG += internal_module force_bootstrap
+CONFIG += minimal_syncqt internal_module force_bootstrap
 
+MODULE_INCNAME = QtCore QtXml
 MODULE_DEFINES = \
         QT_BOOTSTRAPPED \
         QT_LITE_UNICODE \
@@ -26,21 +27,6 @@ DEFINES += \
 
 DEFINES -= QT_EVAL
 
-MODULE_INCLUDES = \
-    \$\$QT_MODULE_INCLUDE_BASE \
-    \$\$QT_MODULE_INCLUDE_BASE/QtCore \
-    \$\$QT_MODULE_INCLUDE_BASE/QtXml
-MODULE_PRIVATE_INCLUDES = \
-    \$\$QT_MODULE_INCLUDE_BASE/QtCore/$$QT_VERSION \
-    \$\$QT_MODULE_INCLUDE_BASE/QtCore/$$QT_VERSION/QtCore \
-    \$\$QT_MODULE_INCLUDE_BASE/QtXml/$$QT_VERSION \
-    \$\$QT_MODULE_INCLUDE_BASE/QtXml/$$QT_VERSION/QtXml
-
-# We need the forwarding headers before their respective modules are built,
-# so do a minimal syncqt run.
-CONFIG += minimal_syncqt
-QMAKE_SYNCQT_OPTIONS = -module QtCore -module QtDBus -module QtXml -version $$QT_VERSION
-
 load(qt_module)
 
 # otherwise mingw headers do not declare common functions like putenv
diff --git a/src/widgets/dialogs/qfontdialog.cpp b/src/widgets/dialogs/qfontdialog.cpp
index 688e8f5c133f4de29734e73fabc0951fa5e6c6bb..d0177941f7eb4df23b98d1cf71dd079d50f546f6 100644
--- a/src/widgets/dialogs/qfontdialog.cpp
+++ b/src/widgets/dialogs/qfontdialog.cpp
@@ -102,6 +102,16 @@ QFontListView::QFontListView(QWidget *parent)
 static const Qt::WindowFlags DefaultWindowFlags =
         Qt::Dialog | Qt::WindowSystemMenuHint;
 
+QFontDialogPrivate::QFontDialogPrivate()
+    : writingSystem(QFontDatabase::Any),
+      options(QSharedPointer<QFontDialogOptions>::create())
+{
+}
+
+QFontDialogPrivate::~QFontDialogPrivate()
+{
+}
+
 /*!
   \class QFontDialog
   \ingroup standard-dialogs
diff --git a/src/widgets/dialogs/qfontdialog_p.h b/src/widgets/dialogs/qfontdialog_p.h
index e456faaa61823d246db919e1301bf8388086c43d..7b92b67f5c2011ac356df82e0dd9b260bf291e8e 100644
--- a/src/widgets/dialogs/qfontdialog_p.h
+++ b/src/widgets/dialogs/qfontdialog_p.h
@@ -65,14 +65,13 @@ class QGroupBox;
 class QLabel;
 class QLineEdit;
 
-class QFontDialogPrivate : public QDialogPrivate
+class Q_AUTOTEST_EXPORT QFontDialogPrivate : public QDialogPrivate
 {
     Q_DECLARE_PUBLIC(QFontDialog)
 
 public:
-    inline QFontDialogPrivate()
-        : writingSystem(QFontDatabase::Any), options(new QFontDialogOptions)
-    { }
+    QFontDialogPrivate();
+    ~QFontDialogPrivate();
 
     QPlatformFontDialogHelper *platformFontDialogHelper() const
         { return static_cast<QPlatformFontDialogHelper *>(platformHelper()); }
diff --git a/src/widgets/graphicsview/qgraphicsproxywidget_p.h b/src/widgets/graphicsview/qgraphicsproxywidget_p.h
index 7b164a0067b31ec3240b6bfd9f544936cf895b6a..c0e0d73aa9058f8334ec1a859fb397aa5a950012 100644
--- a/src/widgets/graphicsview/qgraphicsproxywidget_p.h
+++ b/src/widgets/graphicsview/qgraphicsproxywidget_p.h
@@ -52,7 +52,7 @@
 
 QT_BEGIN_NAMESPACE
 
-class QGraphicsProxyWidgetPrivate : public QGraphicsWidgetPrivate
+class Q_AUTOTEST_EXPORT QGraphicsProxyWidgetPrivate : public QGraphicsWidgetPrivate
 {
     Q_DECLARE_PUBLIC(QGraphicsProxyWidget)
 public:
diff --git a/src/widgets/itemviews/qheaderview.cpp b/src/widgets/itemviews/qheaderview.cpp
index 4cb28d080432900398bc9934d95eabc827d54f9f..338627c79ff5cca11224299a593fe1a3ae06337f 100644
--- a/src/widgets/itemviews/qheaderview.cpp
+++ b/src/widgets/itemviews/qheaderview.cpp
@@ -2608,10 +2608,12 @@ bool QHeaderView::viewportEvent(QEvent *e)
         }
         return true; }
 #endif // QT_NO_STATUSTIP
-    case QEvent::Hide:
-    case QEvent::Show:
     case QEvent::FontChange:
-    case QEvent::StyleChange:{
+    case QEvent::StyleChange:
+        d->invalidateCachedSizeHint();
+        // Fall through
+    case QEvent::Hide:
+    case QEvent::Show: {
         QAbstractScrollArea *parent = qobject_cast<QAbstractScrollArea *>(parentWidget());
         if (parent && parent->isVisible()) // Only resize if we have a visible parent
             resizeSections();
diff --git a/src/widgets/itemviews/qlistview_p.h b/src/widgets/itemviews/qlistview_p.h
index c1b5b8772c8564ae1d959e6c160165145a88131a..62fa45e6403553d3770815944dfe07e85c5a386a 100644
--- a/src/widgets/itemviews/qlistview_p.h
+++ b/src/widgets/itemviews/qlistview_p.h
@@ -293,7 +293,7 @@ private:
 
 };
 
-class QListViewPrivate: public QAbstractItemViewPrivate
+class Q_AUTOTEST_EXPORT QListViewPrivate: public QAbstractItemViewPrivate
 {
     Q_DECLARE_PUBLIC(QListView)
 public:
diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp
index 4f13c06c15aec69e5032fde03c2cc314b49ace3d..e20e820f12a1f914b84f575dd665fff81e499f02 100644
--- a/src/widgets/kernel/qapplication.cpp
+++ b/src/widgets/kernel/qapplication.cpp
@@ -740,15 +740,15 @@ void QApplicationPrivate::initializeWidgetFontHash()
     if (const QFont *font = theme->font(QPlatformTheme::ItemViewFont))
         fontHash->insert(QByteArrayLiteral("QAbstractItemView"), *font);
     if (const QFont *font = theme->font(QPlatformTheme::ListViewFont))
-        fontHash->insert(QByteArrayLiteral("QListViewFont"), *font);
+        fontHash->insert(QByteArrayLiteral("QListView"), *font);
     if (const QFont *font = theme->font(QPlatformTheme::HeaderViewFont))
-        fontHash->insert(QByteArrayLiteral("QHeaderViewFont"), *font);
+        fontHash->insert(QByteArrayLiteral("QHeaderView"), *font);
     if (const QFont *font = theme->font(QPlatformTheme::ListBoxFont))
         fontHash->insert(QByteArrayLiteral("QListBox"), *font);
     if (const QFont *font = theme->font(QPlatformTheme::ComboMenuItemFont))
-        fontHash->insert(QByteArrayLiteral("QComboMenuItemFont"), *font);
+        fontHash->insert(QByteArrayLiteral("QComboMenuItem"), *font);
     if (const QFont *font = theme->font(QPlatformTheme::ComboLineEditFont))
-        fontHash->insert(QByteArrayLiteral("QComboLineEditFont"), *font);
+        fontHash->insert(QByteArrayLiteral("QComboLineEdit"), *font);
     if (const QFont *font = theme->font(QPlatformTheme::SmallFont))
         fontHash->insert(QByteArrayLiteral("QSmallFont"), *font);
     if (const QFont *font = theme->font(QPlatformTheme::MiniFont))
diff --git a/src/widgets/kernel/qdesktopwidget.cpp b/src/widgets/kernel/qdesktopwidget.cpp
index b88b3cc61d9c96861a09cbf8c9fe08fbe1527897..2ddd025239c74ca428168ede23b41874b92abe89 100644
--- a/src/widgets/kernel/qdesktopwidget.cpp
+++ b/src/widgets/kernel/qdesktopwidget.cpp
@@ -36,6 +36,7 @@
 #include "qdesktopwidget_p.h"
 #include "qscreen.h"
 #include "qwidget_p.h"
+#include "qwindow.h"
 
 QT_BEGIN_NAMESPACE
 
@@ -99,13 +100,18 @@ void QDesktopWidgetPrivate::_q_updateScreens()
 
     QRegion virtualGeometry;
 
-    // update the geometry of each screen widget, determine virtual geometry
-    // and emit change signals afterwards.
+    // update the geometry of each screen widget, determine virtual geometry,
+    // set the new screen for window handle and emit change signals afterwards.
     QList<int> changedScreens;
     for (int i = 0; i < screens.length(); i++) {
-        const QRect screenGeometry = screenList.at(i)->geometry();
-        if (screenGeometry != screens.at(i)->geometry()) {
-            screens.at(i)->setGeometry(screenGeometry);
+        QDesktopScreenWidget *screenWidget = screens.at(i);
+        QScreen *qScreen = screenList.at(i);
+        QWindow *winHandle = screenWidget->windowHandle();
+        if (winHandle && winHandle->screen() != qScreen)
+            winHandle->setScreen(qScreen);
+        const QRect screenGeometry = qScreen->geometry();
+        if (screenGeometry != screenWidget->geometry()) {
+            screenWidget->setGeometry(screenGeometry);
             changedScreens.push_back(i);
         }
         virtualGeometry += screenGeometry;
@@ -189,23 +195,69 @@ const QRect QDesktopWidget::screenGeometry(int screenNo) const
 int QDesktopWidget::screenNumber(const QWidget *w) const
 {
     if (!w)
-        return 0;
+        return primaryScreen();
 
+    const QList<QScreen *> allScreens = QGuiApplication::screens();
+    QList<QScreen *> screens = allScreens;
+    if (screens.isEmpty()) // This should never happen
+        return primaryScreen();
+
+    // If there is more than one virtual desktop
+    if (screens.count() != screens.constFirst()->virtualSiblings().count()) {
+        // Find the root widget, get a QScreen from it and use the
+        // virtual siblings for checking the window position.
+        const QWidget *root = w;
+        const QWidget *tmp = w;
+        while ((tmp = tmp->parentWidget()))
+            root = tmp;
+        const QWindow *winHandle = root->windowHandle();
+        if (winHandle) {
+            const QScreen *winScreen = winHandle->screen();
+            if (winScreen)
+                screens = winScreen->virtualSiblings();
+        }
+    }
+
+    // Get the screen number from window position using screen geometry
+    // and proper screens.
     QRect frame = w->frameGeometry();
     if (!w->isWindow())
         frame.moveTopLeft(w->mapToGlobal(QPoint(0, 0)));
-    const QPoint midpoint = (frame.topLeft() + frame.bottomRight()) / 2;
-    return screenNumber(midpoint);
+
+    QScreen *widgetScreen = Q_NULLPTR;
+    int largestArea = 0;
+    foreach (QScreen *screen, screens) {
+        QRect intersected = screen->geometry().intersected(frame);
+        int area = intersected.width() * intersected.height();
+        if (largestArea < area) {
+            widgetScreen = screen;
+            largestArea = area;
+        }
+    }
+    return allScreens.indexOf(widgetScreen);
 }
 
 int QDesktopWidget::screenNumber(const QPoint &p) const
 {
-    QList<QScreen *> screens = QGuiApplication::screens();
-
-    for (int i = 0; i < screens.size(); ++i)
-        if (screens.at(i)->geometry().contains(p))
-            return i;
-
+    const QList<QScreen *> screens = QGuiApplication::screens();
+    if (!screens.isEmpty()) {
+        const QList<QScreen *> primaryScreens = screens.first()->virtualSiblings();
+        // Find the screen index on the primary virtual desktop first
+        foreach (QScreen *screen, primaryScreens) {
+            if (screen->geometry().contains(p))
+                return screens.indexOf(screen);
+        }
+        // If the screen index is not found on primary virtual desktop, find
+        // the screen index on all screens except the first which was for
+        // sure in the previous loop. Some other screens may repeat. Find
+        // only when there is more than one virtual desktop.
+        if (screens.count() != primaryScreens.count()) {
+            for (int i = 1; i < screens.size(); ++i) {
+                if (screens[i]->geometry().contains(p))
+                    return i;
+            }
+        }
+    }
     return primaryScreen(); //even better would be closest screen
 }
 
diff --git a/src/widgets/kernel/qmacgesturerecognizer.cpp b/src/widgets/kernel/qmacgesturerecognizer.cpp
index 47003f58662efae35a67250c5c9bf0d9448e4151..9f55e23cee044ffa963806ea9eb2fd15f3e9e5f3 100644
--- a/src/widgets/kernel/qmacgesturerecognizer.cpp
+++ b/src/widgets/kernel/qmacgesturerecognizer.cpp
@@ -256,6 +256,7 @@ void QMacPanGestureRecognizer::reset(QGesture *gesture)
     QPanGesture *g = static_cast<QPanGesture *>(gesture);
     _startPos = QPointF();
     _panCanceled = true;
+    _panTimer.stop();
     g->setOffset(QPointF(0, 0));
     g->setLastOffset(QPointF(0, 0));
     g->setAcceleration(qreal(1));
diff --git a/src/widgets/styles/qmacstyle_mac.mm b/src/widgets/styles/qmacstyle_mac.mm
index 7fc4093e81fec7b9e72183c389c612585de6318e..ac23512f1d4db64bf4867cd14ed64c1e50ab800e 100644
--- a/src/widgets/styles/qmacstyle_mac.mm
+++ b/src/widgets/styles/qmacstyle_mac.mm
@@ -3698,7 +3698,6 @@ void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter
                 textr.translate(pixmap.width() / pixmap.devicePixelRatio() + 2, 0);
             }
 
-            p->setFont(qt_app_fonts_hash()->value("QSmallFont", QFont()));
             proxy()->drawItemText(p, textr, header->textAlignment | Qt::AlignVCenter, header->palette,
                                        header->state & State_Enabled, header->text, QPalette::ButtonText);
             p->restore();
diff --git a/src/widgets/util/qcompleter.cpp b/src/widgets/util/qcompleter.cpp
index ba56f004b73036b31e109123f1fd95e9fa13a718..4382abaf50a66856b544122f784606f2f1482ece 100644
--- a/src/widgets/util/qcompleter.cpp
+++ b/src/widgets/util/qcompleter.cpp
@@ -432,7 +432,7 @@ void QCompletionEngine::filter(const QStringList& parts)
 
     QModelIndex parent;
     for (int i = 0; i < curParts.count() - 1; i++) {
-        QString part = curParts[i];
+        QString part = curParts.at(i);
         int emi = filter(part, parent, -1).exactMatchIndex;
         if (emi == -1)
             return;
@@ -442,10 +442,10 @@ void QCompletionEngine::filter(const QStringList& parts)
     // Note that we set the curParent to a valid parent, even if we have no matches
     // When filtering is disabled, we show all the items under this parent
     curParent = parent;
-    if (curParts.last().isEmpty())
+    if (curParts.constLast().isEmpty())
         curMatch = QMatchData(QIndexMapper(0, model->rowCount(curParent) - 1), -1, false);
     else
-        curMatch = filter(curParts.last(), curParent, 1); // build at least one
+        curMatch = filter(curParts.constLast(), curParent, 1); // build at least one
     curRow = curMatch.isValid() ? 0 : -1;
 }
 
diff --git a/src/widgets/widgets/qdatetimeedit.cpp b/src/widgets/widgets/qdatetimeedit.cpp
index 42987df3ecd44094d4316f1cf14061b0e64c3035..abee788a46ef3b6df1d14961591c146bc9adb7a4 100644
--- a/src/widgets/widgets/qdatetimeedit.cpp
+++ b/src/widgets/widgets/qdatetimeedit.cpp
@@ -1687,6 +1687,10 @@ QDateTimeEditPrivate::QDateTimeEditPrivate()
 #endif
 }
 
+QDateTimeEditPrivate::~QDateTimeEditPrivate()
+{
+}
+
 void QDateTimeEditPrivate::updateTimeSpec()
 {
     minimum = minimum.toDateTime().toTimeSpec(spec);
diff --git a/src/widgets/widgets/qdatetimeedit_p.h b/src/widgets/widgets/qdatetimeedit_p.h
index 50e2cde8cc83a74aeca59dc80e773373030ffb6b..4a6014000b0ccb9fe5ba9a2e003a978e81283332 100644
--- a/src/widgets/widgets/qdatetimeedit_p.h
+++ b/src/widgets/widgets/qdatetimeedit_p.h
@@ -62,11 +62,12 @@
 QT_BEGIN_NAMESPACE
 
 class QCalendarPopup;
-class QDateTimeEditPrivate : public QAbstractSpinBoxPrivate, public QDateTimeParser
+class Q_AUTOTEST_EXPORT QDateTimeEditPrivate : public QAbstractSpinBoxPrivate, public QDateTimeParser
 {
     Q_DECLARE_PUBLIC(QDateTimeEdit)
 public:
     QDateTimeEditPrivate();
+    ~QDateTimeEditPrivate();
 
     void init(const QVariant &var);
     void readLocaleSettings();
diff --git a/src/widgets/widgets/qdialogbuttonbox.cpp b/src/widgets/widgets/qdialogbuttonbox.cpp
index 5b6bfb3b3c91b1a12ff515fde9263fe0d58ed18d..4d2c32d43eaae9dae74cf81e8340cbe16db3f32d 100644
--- a/src/widgets/widgets/qdialogbuttonbox.cpp
+++ b/src/widgets/widgets/qdialogbuttonbox.cpp
@@ -261,7 +261,7 @@ void QDialogButtonBoxPrivate::layoutButtons()
     if (center)
         buttonLayout->addStretch();
 
-    QList<QAbstractButton *> acceptRoleList = buttonLists[QPlatformDialogHelper::AcceptRole];
+    const QList<QAbstractButton *> &acceptRoleList = buttonLists[QPlatformDialogHelper::AcceptRole];
 
     while (*currentLayout != QPlatformDialogHelper::EOL) {
         int role = (*currentLayout & ~QPlatformDialogHelper::Reverse);
diff --git a/src/widgets/widgets/qlabel_p.h b/src/widgets/widgets/qlabel_p.h
index bd7a9d1e8fa25cd7ec9563c9bda16a28c100cbf8..b4da56c290a72f1ba67fa96d4c7336b9a189924b 100644
--- a/src/widgets/widgets/qlabel_p.h
+++ b/src/widgets/widgets/qlabel_p.h
@@ -60,7 +60,7 @@
 
 QT_BEGIN_NAMESPACE
 
-class QLabelPrivate : public QFramePrivate
+class Q_AUTOTEST_EXPORT QLabelPrivate : public QFramePrivate
 {
     Q_DECLARE_PUBLIC(QLabel)
 public:
diff --git a/src/widgets/widgets/qmenu.cpp b/src/widgets/widgets/qmenu.cpp
index 4239e7f3d4210adc3f0294a45f35f7d7e3befb56..ea3e4c44885e4e5aa91f3284a66869dd65f9b03e 100644
--- a/src/widgets/widgets/qmenu.cpp
+++ b/src/widgets/widgets/qmenu.cpp
@@ -2586,7 +2586,11 @@ void QMenu::mousePressEvent(QMouseEvent *e)
     Q_D(QMenu);
     if (d->aboutToHide || d->mouseEventTaken(e))
         return;
-    if (!rect().contains(e->pos())) {
+    // Workaround for XCB on multiple screens which doesn't have offset. If the menu is open on one screen
+    // and mouse clicks on second screen, e->pos() is QPoint(0,0) and the menu doesn't hide. This trick makes
+    // possible to hide the menu when mouse clicks on another screen (e->screenPos() returns correct value).
+    // Only when mouse clicks in QPoint(0,0) on second screen, the menu doesn't hide.
+    if ((e->pos().isNull() && !e->screenPos().isNull()) || !rect().contains(e->pos())) {
          if (d->noReplayFor
              && QRect(d->noReplayFor->mapToGlobal(QPoint()), d->noReplayFor->size()).contains(e->globalPos()))
              setAttribute(Qt::WA_NoMouseReplay);
diff --git a/src/winmain/qtmain_winrt.cpp b/src/winmain/qtmain_winrt.cpp
index 098ae45dc8eda591373f609acec603f0bde288a2..9e5f206ea5bf727f5fd80b0d27ff09a941ddc993 100644
--- a/src/winmain/qtmain_winrt.cpp
+++ b/src/winmain/qtmain_winrt.cpp
@@ -198,6 +198,15 @@ private:
     HRESULT __stdcall OnLaunched(ILaunchActivatedEventArgs *launchArgs) Q_DECL_OVERRIDE
     {
 #if _MSC_VER >= 1900
+        ComPtr<IPrelaunchActivatedEventArgs> preArgs;
+        HRESULT hr = launchArgs->QueryInterface(preArgs.GetAddressOf());
+        if (SUCCEEDED(hr)) {
+            boolean prelaunched;
+            preArgs->get_PrelaunchActivated(&prelaunched);
+            if (prelaunched)
+                return S_OK;
+        }
+
         commandLine = QString::fromWCharArray(GetCommandLine()).toUtf8();
 #endif
         HString launchCommandLine;
diff --git a/tests/auto/cmake/CMakeLists.txt b/tests/auto/cmake/CMakeLists.txt
index 25bc8a5e4576fc73cfe2cf4f16e11419fafc148e..3a607983f98b12a765f44987996a94dfbd27dae6 100644
--- a/tests/auto/cmake/CMakeLists.txt
+++ b/tests/auto/cmake/CMakeLists.txt
@@ -127,7 +127,7 @@ if (QT_WITH_ANGLE OR (NOT WIN32 AND NOT APPLE AND NOT NO_EGL))
 endif()
 expect_pass(test_opengl_lib)
 
-if (NOT CMAKE_VERSION VERSION_LESS 2.8.11)
+if (NOT CMAKE_VERSION VERSION_LESS 2.8.11 AND NOT NO_WIDGETS)
     expect_pass(test_interface)
 endif()
 
diff --git a/tests/auto/cmake/test_interface/CMakeLists.txt b/tests/auto/cmake/test_interface/CMakeLists.txt
index a8af92da6321b8e53a9fc5fba10691e38e381556..2af80ea4487fd964e4b4b2203fcc2b446d05f23d 100644
--- a/tests/auto/cmake/test_interface/CMakeLists.txt
+++ b/tests/auto/cmake/test_interface/CMakeLists.txt
@@ -8,6 +8,8 @@ find_package(Qt5Widgets)
 set(CMAKE_AUTOMOC ON)
 set(CMAKE_INCLUDE_CURRENT_DIR ON)
 
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Core_EXECUTABLE_COMPILE_FLAGS}")
+
 add_executable(test_interface_exe WIN32 main.cpp mainwindow.cpp)
 
 # No need to specify include directories, compile definitions, the PIC flag, or to
diff --git a/tests/auto/cmake/test_multiple_find_package/CMakeLists.txt b/tests/auto/cmake/test_multiple_find_package/CMakeLists.txt
index c0fdfd6b9ac75833d6499595045079bf6fab705d..6b11c09e7bb6d217a9543f36f5e4ea690800d152 100644
--- a/tests/auto/cmake/test_multiple_find_package/CMakeLists.txt
+++ b/tests/auto/cmake/test_multiple_find_package/CMakeLists.txt
@@ -9,5 +9,5 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Core_EXECUTABLE_COMPILE_FLAGS}")
 
 add_subdirectory(subdir1)
 
-add_executable(exe1 "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp")
-include_directories(${Qt5Core_INCLUDE_DIRS})
+add_executable(exe1 main.cpp)
+target_link_libraries(exe1 Qt5::Core)
diff --git a/tests/auto/cmake/test_multiple_find_package/subdir1/CMakeLists.txt b/tests/auto/cmake/test_multiple_find_package/subdir1/CMakeLists.txt
index 0c7a113f5012a3bb6fc9ef4d4081b6d48dd57f7e..dfcc35d735f9ecda510def25ad26c3e954a83484 100644
--- a/tests/auto/cmake/test_multiple_find_package/subdir1/CMakeLists.txt
+++ b/tests/auto/cmake/test_multiple_find_package/subdir1/CMakeLists.txt
@@ -2,4 +2,4 @@
 find_package(Qt5Core REQUIRED)
 
 add_executable(exe2 "${CMAKE_CURRENT_SOURCE_DIR}/../main.cpp")
-include_directories(${Qt5Core_INCLUDE_DIRS})
+target_link_libraries(exe2 Qt5::Core)
diff --git a/tests/auto/cmake/test_platform_defs_include/CMakeLists.txt b/tests/auto/cmake/test_platform_defs_include/CMakeLists.txt
index 2b32a419e7e42e8960cbc3cbaa6d8b71a81862ff..e2f72842f6554c7552930f5ac5ba17a875ee48cc 100644
--- a/tests/auto/cmake/test_platform_defs_include/CMakeLists.txt
+++ b/tests/auto/cmake/test_platform_defs_include/CMakeLists.txt
@@ -11,3 +11,4 @@ add_definitions(${Qt5Core_DEFINITIONS})
 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Core_EXECUTABLE_COMPILE_FLAGS}")
 
 add_executable(myobject main.cpp)
+target_link_libraries(myobject Qt5::Core)
diff --git a/tests/auto/cmake/test_use_modules_function/CMakeLists.txt b/tests/auto/cmake/test_use_modules_function/CMakeLists.txt
index bfcdd9d1d70d3240ccf34adb43560eb203d82ded..be05c75054cf48b601a6aef98de37cb4edfd33bb 100644
--- a/tests/auto/cmake/test_use_modules_function/CMakeLists.txt
+++ b/tests/auto/cmake/test_use_modules_function/CMakeLists.txt
@@ -12,5 +12,7 @@ add_executable(three three.cpp)
 
 find_package(Qt5Core)
 
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Core_EXECUTABLE_COMPILE_FLAGS}")
+
 qt5_use_modules(two Test)
 qt5_use_modules(three Gui Test)
diff --git a/tests/auto/corelib/io/qfile/BLACKLIST b/tests/auto/corelib/io/qfile/BLACKLIST
index 7aac313b12f90436524e27e09ab9689b464688a2..e3bc093c833e8312d307bdaac2055ef59bb29c91 100644
--- a/tests/auto/corelib/io/qfile/BLACKLIST
+++ b/tests/auto/corelib/io/qfile/BLACKLIST
@@ -3,3 +3,7 @@
 msvc-2015
 [readLineStdin_lineByLine]
 msvc-2015
+[openStandardStreamsFileDescriptors]
+osx
+[openStandardStreamsBufferedStreams]
+osx
diff --git a/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp b/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp
index 24ff2f237feb33bd68f9aacbb76284f3799e3c8b..50c5b938e9d61cc6437f50f4c1b05cbed2ea924f 100644
--- a/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp
+++ b/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp
@@ -464,6 +464,15 @@ void tst_qstandardpaths::testCustomRuntimeDirectory()
 #endif
 
 #ifdef Q_XDG_PLATFORM
+    struct EnvVarRestorer
+    {
+        EnvVarRestorer() : origRuntimeDir(qgetenv("XDG_RUNTIME_DIR")) {}
+        ~EnvVarRestorer() { qputenv("XDG_RUNTIME_DIR", origRuntimeDir.constData()); }
+        const QByteArray origRuntimeDir;
+    };
+    EnvVarRestorer restorer;
+
+    // When $XDG_RUNTIME_DIR points to a directory with wrong ownership, QStandardPaths should warn
     qputenv("XDG_RUNTIME_DIR", QFile::encodeName("/tmp"));
     // It's very unlikely that /tmp is 0600 or that we can chmod it
     // The call below outputs
@@ -474,6 +483,20 @@ void tst_qstandardpaths::testCustomRuntimeDirectory()
             qPrintable(QString::fromLatin1("QStandardPaths: wrong ownership on runtime directory /tmp, 0 instead of %1").arg(uid)));
     const QString runtimeDir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
     QVERIFY2(runtimeDir.isEmpty(), qPrintable(runtimeDir));
+
+    // When $XDG_RUNTIME_DIR points to a non-existing directory, QStandardPaths should warn (QTBUG-48771)
+    qputenv("XDG_RUNTIME_DIR", "does_not_exist");
+    QTest::ignoreMessage(QtWarningMsg, "QStandardPaths: XDG_RUNTIME_DIR points to non-existing path 'does_not_exist', please create it with 0700 permissions.");
+    const QString nonExistingRuntimeDir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
+    QVERIFY2(nonExistingRuntimeDir.isEmpty(), qPrintable(nonExistingRuntimeDir));
+
+    // When $XDG_RUNTIME_DIR points to a file, QStandardPaths should warn
+    const QString file = QFINDTESTDATA("tst_qstandardpaths.cpp");
+    QVERIFY(!file.isEmpty());
+    qputenv("XDG_RUNTIME_DIR", QFile::encodeName(file));
+    QTest::ignoreMessage(QtWarningMsg, qPrintable(QString::fromLatin1("QStandardPaths: XDG_RUNTIME_DIR points to '%1' which is not a directory").arg(file)));
+    const QString noRuntimeDir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
+    QVERIFY2(noRuntimeDir.isEmpty(), qPrintable(file));
 #endif
 }
 
diff --git a/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp b/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
index 58a3db9615ce7c596e7dce88fe367040a34d8134..621e215d60ab998333130d4db58d8f7d3192a7fb 100644
--- a/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
+++ b/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
@@ -229,6 +229,13 @@ void tst_QTemporaryDir::autoRemove()
 void tst_QTemporaryDir::nonWritableCurrentDir()
 {
 #ifdef Q_OS_UNIX
+
+#  if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK)
+    const char nonWritableDir[] = "/data";
+#  else
+    const char nonWritableDir[] = "/home";
+#  endif
+
     if (::geteuid() == 0)
         QSKIP("not valid running this test as root");
 
@@ -240,13 +247,13 @@ void tst_QTemporaryDir::nonWritableCurrentDir()
         }
         QString dir;
     };
-    ChdirOnReturn cor(QDir::currentPath());
 
-#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK)
-    QDir::setCurrent("/data");
-#else
-    QDir::setCurrent("/home");
-#endif
+    const QFileInfo nonWritableDirFi = QFileInfo(QLatin1String(nonWritableDir));
+    QVERIFY(nonWritableDirFi.isDir());
+    QVERIFY(!nonWritableDirFi.isWritable());
+
+    ChdirOnReturn cor(QDir::currentPath());
+    QVERIFY(QDir::setCurrent(nonWritableDirFi.absoluteFilePath()));
     // QTemporaryDir("tempXXXXXX") is probably a bad idea in any app
     // where the current dir could anything...
     QTemporaryDir dir("tempXXXXXX");
diff --git a/tests/auto/corelib/io/qurl/tst_qurl.cpp b/tests/auto/corelib/io/qurl/tst_qurl.cpp
index 7579c6713d5bd8d7856f81ef3af61141eb29c6ef..031a35b3806a4bd4a1da48774cd5c47bc08ddc84 100644
--- a/tests/auto/corelib/io/qurl/tst_qurl.cpp
+++ b/tests/auto/corelib/io/qurl/tst_qurl.cpp
@@ -79,6 +79,8 @@ private slots:
     void toLocalFile();
     void fromLocalFile_data();
     void fromLocalFile();
+    void fromLocalFileNormalize_data();
+    void fromLocalFileNormalize();
     void macTypes();
     void relative();
     void compat_legacy();
@@ -1242,16 +1244,6 @@ void tst_QUrl::fromLocalFile_data()
                         << QString::fromLatin1("/");
     QTest::newRow("data7") << QString::fromLatin1("/Mambo <#5>.mp3") << QString::fromLatin1("file:///Mambo <%235>.mp3")
                            << QString::fromLatin1("/Mambo <#5>.mp3");
-    QTest::newRow("data8") << QString::fromLatin1("/a%.txt") << QString::fromLatin1("file:///a%25.txt")
-                           << QString::fromLatin1("/a%.txt");
-    QTest::newRow("data9") << QString::fromLatin1("/a%25.txt") << QString::fromLatin1("file:///a%2525.txt")
-                           << QString::fromLatin1("/a%25.txt");
-    QTest::newRow("data10") << QString::fromLatin1("/%80.txt") << QString::fromLatin1("file:///%2580.txt")
-                            << QString::fromLatin1("/%80.txt");
-    QTest::newRow("data11") << QString::fromLatin1("./a.txt") << QString::fromLatin1("file:a.txt") << QString::fromLatin1("a.txt");
-    QTest::newRow("data12") << QString::fromLatin1("././a.txt") << QString::fromLatin1("file:a.txt") << QString::fromLatin1("a.txt");
-    QTest::newRow("data13") << QString::fromLatin1("b/../a.txt") << QString::fromLatin1("file:a.txt") << QString::fromLatin1("a.txt");
-    QTest::newRow("data14") << QString::fromLatin1("/b/../a.txt") << QString::fromLatin1("file:///a.txt") << QString::fromLatin1("/a.txt");
 }
 
 void tst_QUrl::fromLocalFile()
@@ -1266,6 +1258,41 @@ void tst_QUrl::fromLocalFile()
     QCOMPARE(url.path(), thePath);
 }
 
+void tst_QUrl::fromLocalFileNormalize_data()
+{
+    QTest::addColumn<QString>("theFile"); // should support the fromLocalFile/toLocalFile roundtrip (so no //host or windows path)
+    QTest::addColumn<QString>("theUrl");
+    QTest::addColumn<QString>("urlWithNormalizedPath");
+
+    QTest::newRow("data0") << QString::fromLatin1("/a.txt") << QString::fromLatin1("file:///a.txt") << QString::fromLatin1("file:///a.txt");
+    QTest::newRow("data1") << QString::fromLatin1("a.txt") << QString::fromLatin1("file:a.txt") << QString::fromLatin1("file:a.txt");
+    QTest::newRow("data8") << QString::fromLatin1("/a%.txt") << QString::fromLatin1("file:///a%25.txt")
+                           << QString::fromLatin1("file:///a%25.txt");
+    QTest::newRow("data9") << QString::fromLatin1("/a%25.txt") << QString::fromLatin1("file:///a%2525.txt")
+                           << QString::fromLatin1("file:///a%2525.txt");
+    QTest::newRow("data10") << QString::fromLatin1("/%80.txt") << QString::fromLatin1("file:///%2580.txt")
+                            << QString::fromLatin1("file:///%2580.txt");
+    QTest::newRow("data11") << QString::fromLatin1("./a.txt") << QString::fromLatin1("file:./a.txt") << QString::fromLatin1("file:a.txt");
+    QTest::newRow("data12") << QString::fromLatin1("././a.txt") << QString::fromLatin1("file:././a.txt") << QString::fromLatin1("file:a.txt");
+    QTest::newRow("data13") << QString::fromLatin1("b/../a.txt") << QString::fromLatin1("file:b/../a.txt") << QString::fromLatin1("file:a.txt");
+    QTest::newRow("data14") << QString::fromLatin1("/b/../a.txt") << QString::fromLatin1("file:///b/../a.txt") << QString::fromLatin1("file:///a.txt");
+    QTest::newRow("data15") << QString::fromLatin1("/b/.") << QString::fromLatin1("file:///b/.") << QString::fromLatin1("file:///b");
+}
+
+void tst_QUrl::fromLocalFileNormalize()
+{
+    QFETCH(QString, theFile);
+    QFETCH(QString, theUrl);
+    QFETCH(QString, urlWithNormalizedPath);
+
+    QUrl url = QUrl::fromLocalFile(theFile);
+
+    QCOMPARE(url.toString(QUrl::DecodeReserved), theUrl);
+    QCOMPARE(url.toLocalFile(), theFile); // roundtrip
+    QCOMPARE(url.path(), theFile); // works as well as long as we don't test windows paths
+    QCOMPARE(url.toString(QUrl::NormalizePathSegments), urlWithNormalizedPath);
+}
+
 void tst_QUrl::macTypes()
 {
 #ifndef Q_OS_MAC
@@ -2960,6 +2987,9 @@ void tst_QUrl::fromUserInputWithCwd_data()
     while (it.hasNext()) {
         it.next();
         QUrl url = QUrl::fromLocalFile(it.filePath());
+        if (it.fileName() == QLatin1String(".")) {
+            url = QUrl::fromLocalFile(QDir::currentPath()); // fromUserInput cleans the path
+        }
         QTest::newRow(QString("file-%1").arg(c++).toLatin1()) << it.fileName() << QDir::currentPath() << url << url;
     }
     QDir parent = QDir::current();
@@ -3021,6 +3051,8 @@ void tst_QUrl::fileName_data()
                               << QString() << "tmp.txt" << "tmp.txt";
     QTest::newRow("encoded") << "print:/specials/Print%20To%20File%20(PDF%252FAcrobat)"
                               << "/specials/" << "Print To File (PDF%252FAcrobat)" << "Print To File (PDF%2FAcrobat)";
+    QTest::newRow("endsWithDot") << "file:///temp/."
+                              << "/temp/" << "." << ".";
 }
 
 void tst_QUrl::fileName()
@@ -3513,7 +3545,7 @@ void tst_QUrl::setComponents_data()
                                       << PrettyDecoded << "/path" << "trash:/path";
     QTest::newRow("path-withdotdot") << QUrl("file:///tmp")
                                       << int(Path) << "//tmp/..///root/." << Tolerant << true
-                                      << PrettyDecoded << "/root" << "file:///root";
+                                      << PrettyDecoded << "/tmp/..///root/." << "file:///tmp/..///root/.";
 
     // the other fields can be present and be empty
     // that is, their delimiters would be present, but there would be nothing to one side
diff --git a/tests/auto/corelib/json/tst_qtjson.cpp b/tests/auto/corelib/json/tst_qtjson.cpp
index 884c4b38505d7e934daf73b32a58693d62017b54..1665ff696d864eabb1c5ee90fe5345ac1f019b4e 100644
--- a/tests/auto/corelib/json/tst_qtjson.cpp
+++ b/tests/auto/corelib/json/tst_qtjson.cpp
@@ -1137,6 +1137,12 @@ void tst_QtJson::fromVariant()
     QCOMPARE(QJsonValue::fromVariant(QVariant(stringList)), QJsonValue(jsonArray_string));
     QCOMPARE(QJsonValue::fromVariant(QVariant(variantList)), QJsonValue(jsonArray_variant));
     QCOMPARE(QJsonValue::fromVariant(QVariant(variantMap)), QJsonValue(jsonObject));
+
+    QVERIFY(QJsonValue::fromVariant(QVariant(QJsonValue(true))).isBool());
+    QVERIFY(QJsonValue::fromVariant(QVariant(jsonArray_string)).isArray());
+    QVERIFY(QJsonValue::fromVariant(QVariant(QJsonDocument(jsonArray_string))).isArray());
+    QVERIFY(QJsonValue::fromVariant(QVariant(jsonObject)).isObject());
+    QVERIFY(QJsonValue::fromVariant(QVariant(QJsonDocument(jsonObject))).isObject());
 }
 
 void tst_QtJson::fromVariantMap()
diff --git a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
index 40eb2e5c9db13ece517837de636381374b256f9a..c91bb2139925b3e8cf23c11c17a5014804429e23 100644
--- a/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
+++ b/tests/auto/corelib/kernel/qvariant/tst_qvariant.cpp
@@ -1711,12 +1711,16 @@ void tst_QVariant::compareNumbers_data() const
     QTest::newRow("float3") << qVariantFromValue(0.f) << qVariantFromValue(-1.f) << +1;
     QTest::newRow("float4") << qVariantFromValue(-float(qInf())) << qVariantFromValue(0.f) << -1;
     QTest::newRow("float5") << qVariantFromValue(0.f) << qVariantFromValue(-float(qInf())) << +1;
+    QTest::newRow("float6") << qVariantFromValue(-float(qInf())) << qVariantFromValue(-float(qInf())) << 0;
+    QTest::newRow("float7") << qVariantFromValue(float(qInf())) << qVariantFromValue(float(qInf())) << 0;
 
     QTest::newRow("double1") << qVariantFromValue(0.) << qVariantFromValue(0.) << 0;
     QTest::newRow("double2") << qVariantFromValue(-1.) << qVariantFromValue(0.) << -1;
     QTest::newRow("double3") << qVariantFromValue(0.) << qVariantFromValue(-1.) << +1;
     QTest::newRow("double4") << qVariantFromValue(-qInf()) << qVariantFromValue(0.) << -1;
     QTest::newRow("double5") << qVariantFromValue(0.) << qVariantFromValue(-qInf()) << +1;
+    QTest::newRow("double6") << qVariantFromValue(-double(qInf())) << qVariantFromValue(-qInf()) << 0;
+    QTest::newRow("double7") << qVariantFromValue(qInf()) << qVariantFromValue(qInf()) << 0;
 
     // mixed comparisons
     // fp + fp
@@ -1725,6 +1729,8 @@ void tst_QVariant::compareNumbers_data() const
     QTest::newRow("float+double3") << qVariantFromValue(0.f) << qVariantFromValue(-1.) << +1;
     QTest::newRow("float+double4") << qVariantFromValue(-float(qInf())) << qVariantFromValue(0.) << -1;
     QTest::newRow("float+double5") << qVariantFromValue(0.f) << qVariantFromValue(-qInf()) << +1;
+    QTest::newRow("float+double6") << qVariantFromValue(-float(qInf())) << qVariantFromValue(qInf()) << 0;
+    QTest::newRow("float+double7") << qVariantFromValue(float(qInf())) << qVariantFromValue(qInf()) << 0;
 
     // fp + int
     QTest::newRow("float+int1") << qVariantFromValue(0.f) << qVariantFromValue(0) << 0;
@@ -1735,6 +1741,7 @@ void tst_QVariant::compareNumbers_data() const
     QTest::newRow("double+int3") << qVariantFromValue(0.) << qVariantFromValue(-1) << +1;
     QTest::newRow("float+int4") << qVariantFromValue(1.5f) << qVariantFromValue(1) << +1;
     QTest::newRow("double+int4") << qVariantFromValue(1.5) << qVariantFromValue(1) << +1;
+    QTest::newRow("double+int5") << qVariantFromValue(qInf()) << qVariantFromValue(1) << +1;
 
     // fp + uint
     QTest::newRow("float+uint1") << qVariantFromValue(0.f) << qVariantFromValue(0U) << 0;
diff --git a/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp b/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp
index 0171c4ac5ae05131ec6c70c5d4d3716b1f460d03..1b4dc020f2c9c69e5e0e38493bd139d4e8ea7f9e 100644
--- a/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp
+++ b/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.cpp
@@ -35,6 +35,11 @@
 
 #include "qstandardpaths.h"
 
+#ifdef Q_OS_UNIX
+#include <sys/types.h>
+#include <sys/stat.h>
+#endif
+
 #include <QtCore/QElapsedTimer>
 #include <QtCore/QFile>
 #include <QtCore/QFileInfo>
@@ -646,6 +651,28 @@ void tst_QMimeDatabase::knownSuffix()
     QCOMPARE(db.suffixForFileName(QString::fromLatin1("foo.tar.bz2")), QString::fromLatin1("tar.bz2"));
 }
 
+void tst_QMimeDatabase::symlinkToFifo() // QTBUG-48529
+{
+#ifdef Q_OS_UNIX
+    QTemporaryDir tempDir;
+    QVERIFY(tempDir.isValid());
+    const QString dir = tempDir.path();
+    const QString fifo = dir + "/fifo";
+    QCOMPARE(mkfifo(QFile::encodeName(fifo), 0006), 0);
+
+    QMimeDatabase db;
+    QCOMPARE(db.mimeTypeForFile(fifo).name(), QString::fromLatin1("inode/fifo"));
+
+    // Now make a symlink to the fifo
+    const QString link = dir + "/link";
+    QVERIFY(QFile::link(fifo, link));
+    QCOMPARE(db.mimeTypeForFile(link).name(), QString::fromLatin1("inode/fifo"));
+
+#else
+    QSKIP("This test requires pipes and symlinks");
+#endif
+}
+
 void tst_QMimeDatabase::findByFileName_data()
 {
     QTest::addColumn<QString>("filePath");
diff --git a/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.h b/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.h
index 2827bd2dc40883e85109bc1ed90b34e2c8a08449..4b703f15d79ede6838937ebd06ff56539dff5193 100644
--- a/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.h
+++ b/tests/auto/corelib/mimetypes/qmimedatabase/tst_qmimedatabase.h
@@ -70,6 +70,7 @@ private slots:
     void suffixes_data();
     void suffixes();
     void knownSuffix();
+    void symlinkToFifo();
     void fromThreads();
 
     // shared-mime-info test suite
diff --git a/tests/auto/corelib/tools/collections/tst_collections.cpp b/tests/auto/corelib/tools/collections/tst_collections.cpp
index ae8ffe48be79f4c0ef7a3f6258e73c4909af09e2..b9487cee33a319c2539915a3aca4a81f75af4f7b 100644
--- a/tests/auto/corelib/tools/collections/tst_collections.cpp
+++ b/tests/auto/corelib/tools/collections/tst_collections.cpp
@@ -90,7 +90,9 @@ void foo()
 #include "qvector.h"
 #include "qqueue.h"
 
+QT_BEGIN_NAMESPACE
 template class QList<int>;
+QT_END_NAMESPACE
 
 class tst_Collections : public QObject
 {
diff --git a/tests/auto/corelib/tools/qdate/tst_qdate.cpp b/tests/auto/corelib/tools/qdate/tst_qdate.cpp
index e515fcf5b9c8c9e3dc947c9de9fc2b5cc577eb5f..937a490da296b20b7b1ebadcceb31b5d465cc009 100644
--- a/tests/auto/corelib/tools/qdate/tst_qdate.cpp
+++ b/tests/auto/corelib/tools/qdate/tst_qdate.cpp
@@ -392,16 +392,37 @@ void tst_QDate::weekNumber_data()
     QTest::addColumn<int>("month");
     QTest::addColumn<int>("day");
 
-    //next we fill it with data
-    QTest::newRow( "data0" )  << 10 << 2002 << 2002 << 3 << 8;
-    QTest::newRow( "data1" )  << 10 << 2002 << 2002 << 3 << 8;
-    QTest::newRow( "data2" )  << 52 << 1999 << 2000 << 1 << 1;
-    QTest::newRow( "data3" )  << 52 << 1999 << 1999 << 12 << 31;
-    QTest::newRow( "data4" )  << 1 << 2001 << 2001 << 1 << 1;
-    QTest::newRow( "data5" )  << 53 << 1998 << 1998 << 12 << 31;
-    QTest::newRow( "data6" )  << 1 << 1985 << 1984 << 12 << 31;
-    QTest::newRow( "data7" )  << 52 << 2006 << 2006 << 12 << 31;
-    QTest::newRow( "data8" )  << 53 << 2004 << 2005 << 1 << 1;
+    enum { Thursday = 4 };
+    bool wasLastYearLong = false;   // 1999 was not a long (53-week) year
+    bool isLongYear;
+
+    // full 400-year cycle for Jan 1, 4 and Dec 28, 31
+    for (int yr = 2000; yr < 2400; ++yr, wasLastYearLong = isLongYear) {
+        QByteArray yrstr = QByteArray::number(yr);
+        int wday = QDate(yr, 1, 1).dayOfWeek();
+
+        // the year is 53-week long if Jan 1 is Thursday or, if it's a leap year, a Wednesday
+        isLongYear = (wday == Thursday) || (QDate::isLeapYear(yr) && wday == Thursday - 1);
+
+        // Jan 4 is always on week 1
+        QTest::newRow(yrstr + "-01-04") << 1 << yr << yr << 1 << 4;
+
+        // Dec 28 is always on the last week
+        QTest::newRow(yrstr + "-12-28") << (52 + isLongYear) << yr << yr << 12 << 28;
+
+        // Jan 1 is on either on week 1 or on the last week of the previous year
+        QTest::newRow(yrstr + "-01-01")
+                << (wday <= Thursday ? 1 : 52 + wasLastYearLong)
+                << (wday <= Thursday ? yr : yr - 1)
+                << yr << 1 << 1;
+
+        // Dec 31 is either on the last week or week 1 of the next year
+        wday = QDate(yr, 12, 31).dayOfWeek();
+        QTest::newRow(yrstr + "-12-31")
+                << (wday >= Thursday ? 52 + isLongYear : 1)
+                << (wday >= Thursday ? yr : yr + 1)
+                << yr << 12 << 31;
+    }
 }
 
 void tst_QDate::weekNumber()
diff --git a/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp b/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp
index 833dfe87d7fcf530e622ad8581f4ffe92ce971df..228ce73c6be131107f486745c337e3e1572320cd 100644
--- a/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp
+++ b/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp
@@ -68,6 +68,7 @@ private slots:
     void timeSpec();
     void toTime_t_data();
     void toTime_t();
+    void daylightSavingsTimeChange_data();
     void daylightSavingsTimeChange();
     void springForward_data();
     void springForward();
@@ -1563,36 +1564,47 @@ void tst_QDateTime::toTime_t()
     }
 }
 
+void tst_QDateTime::daylightSavingsTimeChange_data()
+{
+    QTest::addColumn<QDate>("inDST");
+    QTest::addColumn<QDate>("outDST");
+    QTest::newRow("Autumn") << QDate(2006, 8, 1) << QDate(2006, 12, 1);
+    QTest::newRow("Spring") << QDate(2006, 5, 1) << QDate(2006, 2, 1);
+}
+
 void tst_QDateTime::daylightSavingsTimeChange()
 {
-    // This is a regression test for an old bug where starting with a date in
-    // DST and then moving to a date outside it (or vice-versa) caused 1-hour
-    // jumps in time when addSecs() was called.
+    // This has grown from a regression test for an old bug where starting with
+    // a date in DST and then moving to a date outside it (or vice-versa) caused
+    // 1-hour jumps in time when addSecs() was called.
     //
     // The bug was caused by QDateTime knowing more than it lets show.
     // Internally, if it knows, QDateTime stores a flag indicating if the time is
     // DST or not. If it doesn't, it sets to "LocalUnknown".  The problem happened
     // because some functions did not reset the flag when moving in or out of DST.
 
-    // WARNING: This test only works if there's a Daylight Savings Time change
-    // in the current locale between 2006-11-06 and 2006-10-16
-    // This is true for Central European Time
+    // WARNING: This only tests anything if there's a Daylight Savings Time change
+    // in the current locale between inDST and outDST.
+    // This is true for Central European Time and may be elsewhere.
 
-    if (!europeanTimeZone)
-        QSKIP("Not tested with timezone other than Central European (CET/CEST)");
+    QFETCH(QDate, inDST);
+    QFETCH(QDate, outDST);
 
-    QDateTime dt = QDateTime(QDate(2006, 11, 6), QTime(0, 0, 0), Qt::LocalTime);
-    dt.setDate(QDate(2006, 10, 16));
+    // First with simple construction
+    QDateTime dt = QDateTime(outDST, QTime(0, 0, 0), Qt::LocalTime);
+    int outDSTsecs = dt.toTime_t();
+
+    dt.setDate(inDST);
     dt = dt.addSecs(1);
-    QCOMPARE(dt.date(), QDate(2006, 10, 16));
-    QCOMPARE(dt.time(), QTime(0, 0, 1));
+    QCOMPARE(dt, QDateTime(inDST, QTime(0, 0, 1)));
 
     // now using fromTime_t
-    dt = QDateTime::fromTime_t(1162767600); // 2006-11-06 00:00:00 +0100
-    dt.setDate(QDate(2006, 10, 16));
-    dt = dt.addSecs (1);
-    QCOMPARE(dt.date(), QDate(2006, 10, 16));
-    QCOMPARE(dt.time(), QTime(0, 0, 1));
+    dt = QDateTime::fromTime_t(outDSTsecs);
+    QCOMPARE(dt, QDateTime(outDST, QTime(0, 0, 0)));
+
+    dt.setDate(inDST);
+    dt = dt.addSecs(60);
+    QCOMPARE(dt, QDateTime(inDST, QTime(0, 1, 0)));
 }
 
 void tst_QDateTime::springForward_data()
@@ -1604,9 +1616,7 @@ void tst_QDateTime::springForward_data()
 
     if (europeanTimeZone) {
         QTest::newRow("Europe from day before") << QDate(2015, 3, 29) << QTime(2, 30, 0) << 1 << 60;
-#if 0 // FIXME: fails
         QTest::newRow("Europe from day after") << QDate(2015, 3, 29) << QTime(2, 30, 0) << -1 << 120;
-#endif
  // } else if (otherZone) {
     } else {
         QSKIP("No spring forward test data for this TZ");
diff --git a/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp b/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp
index 0466ced10a2710247a04f6206afd310803dcccf7..5f046575c45795aacc772bb341155c4ef49376aa 100644
--- a/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp
+++ b/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp
@@ -613,7 +613,8 @@ void tst_QLocale::legacyNames()
     TEST_CTOR("no", Norwegian, Norway)
     TEST_CTOR("sh_ME", Serbian, Montenegro)
     TEST_CTOR("tl", Filipino, Philippines)
-
+    TEST_CTOR("iw", Hebrew, Israel)
+    TEST_CTOR("in", Indonesian, Indonesia)
 #undef TEST_CTOR
 }
 
diff --git a/tests/auto/corelib/tools/qstring/tst_qstring.cpp b/tests/auto/corelib/tools/qstring/tst_qstring.cpp
index 907dcf17e1fd9fa00756d37202ee9ca3950053a1..a922e3ad2798a46aa076d383d3fa88b36b41a54b 100644
--- a/tests/auto/corelib/tools/qstring/tst_qstring.cpp
+++ b/tests/auto/corelib/tools/qstring/tst_qstring.cpp
@@ -1148,7 +1148,7 @@ void tst_QString::constructorQByteArray_data()
     ba1[5] = 'e';
     ba1[6] = 'f';
 
-    QTest::newRow( "2" ) << ba1 << QStringLiteral("abc\0def");
+    QTest::newRow( "2" ) << ba1 << QString("abc");
 
     QTest::newRow( "3" ) << QByteArray::fromRawData("abcd", 3) << QString("abc");
     QTest::newRow( "4" ) << QByteArray("\xc3\xa9") << QString("\xc3\xa9");
@@ -1169,6 +1169,12 @@ void tst_QString::constructorQByteArray()
     QCOMPARE( strBA, expected );
 
     // test operator= too
+    if (src.constData()[src.length()] == '\0') {
+        str1.clear();
+        str1 = src.constData();
+        QCOMPARE( str1, expected );
+    }
+
     strBA.clear();
     strBA = src;
     QCOMPARE( strBA, expected );
@@ -2569,6 +2575,14 @@ void tst_QString::append_bytearray_special_cases()
 
         QTEST( str, "res" );
     }
+
+    QFETCH( QByteArray, ba );
+    if (ba.constData()[ba.length()] == '\0') {
+        QFETCH( QString, str );
+
+        str.append(ba.constData());
+        QTEST( str, "res" );
+    }
 }
 
 void tst_QString::operator_pluseq_data(bool emptyIsNoop)
@@ -2599,6 +2613,14 @@ void tst_QString::operator_pluseq_bytearray_special_cases()
 
         QTEST( str, "res" );
     }
+
+    QFETCH( QByteArray, ba );
+    if (ba.constData()[ba.length()] == '\0') {
+        QFETCH( QString, str );
+
+        str += ba.constData();
+        QTEST( str, "res" );
+    }
 }
 
 void tst_QString::operator_eqeq_bytearray_data()
@@ -2613,6 +2635,11 @@ void tst_QString::operator_eqeq_bytearray()
 
     QVERIFY(expected == src);
     QVERIFY(!(expected != src));
+
+    if (src.constData()[src.length()] == '\0') {
+        QVERIFY(expected == src.constData());
+        QVERIFY(!(expected != src.constData()));
+    }
 }
 
 void tst_QString::swap()
@@ -2670,7 +2697,7 @@ void tst_QString::prepend_bytearray_special_cases_data()
     // byte array with only a 0
     ba.resize( 1 );
     ba[0] = 0;
-    QTest::newRow( "emptyString" ) << QString("foobar ") << ba << QStringLiteral("\0foobar ");
+    QTest::newRow( "emptyString" ) << QString("foobar ") << ba << QString("foobar ");
 
     // empty byte array
     ba.resize( 0 );
@@ -2700,6 +2727,14 @@ void tst_QString::prepend_bytearray_special_cases()
 
         QTEST( str, "res" );
     }
+
+    QFETCH( QByteArray, ba );
+    if (ba.constData()[ba.length()] == '\0') {
+        QFETCH( QString, str );
+
+        str.prepend(ba.constData());
+        QTEST( str, "res" );
+    }
 }
 
 void tst_QString::replace_uint_uint()
diff --git a/tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp b/tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp
index 507f7e3992a7b0a81676b62b1ecc42132f523c12..b588e1fe8216bcca948a550d9a1ccf7f41066b40 100644
--- a/tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp
+++ b/tests/auto/corelib/tools/qtimeline/tst_qtimeline.cpp
@@ -93,29 +93,20 @@ void tst_QTimeLine::range()
     QCOMPARE(timeLine.endFrame(), 16);
 
     // Verify that you can change the range in the timeLine
-    timeLine.setFrameRange(10, 20);
+    timeLine.setFrameRange(1000, 2000);
     QSignalSpy spy(&timeLine, &QTimeLine::frameChanged);
     QVERIFY(spy.isValid());
-    timeLine.start();
-#ifdef Q_OS_WINCE
-    QTest::qWait(1000);
-#else
-    QTest::qWait(100);
-#endif
-    QCOMPARE(timeLine.state(), QTimeLine::Running);
+    timeLine.start();  // make sure that the logic works for a running timeline
+    QTRY_COMPARE(timeLine.state(), QTimeLine::Running);
+    timeLine.setCurrentTime(timeLine.duration()/2);
     int oldValue = timeLine.currentFrame();
-    timeLine.setFrameRange(0, 5);
+    timeLine.setFrameRange(0, 500);
     QVERIFY(timeLine.currentFrame() < oldValue);
-    timeLine.setEndFrame(100);
-    timeLine.setStartFrame(50);
+    timeLine.setEndFrame(10000);
+    timeLine.setStartFrame(5000);
     QVERIFY(timeLine.currentFrame() > oldValue);
-    timeLine.setFrameRange(0, 5);
-#ifdef Q_OS_WINCE
-    QTest::qWait(500);
-#else
-    QTest::qWait(50);
-#endif
-    QVERIFY(spy.count() > 1);
+    timeLine.setFrameRange(0, 500);
+    QTRY_VERIFY(spy.count() > 1);
     QVERIFY(timeLine.currentFrame() < oldValue);
 }
 
@@ -123,19 +114,17 @@ void tst_QTimeLine::currentTime()
 {
     QTimeLine timeLine(2000);
     timeLine.setUpdateInterval((timeLine.duration()/2) / 33);
-    QSignalSpy spy(&timeLine, &QTimeLine::valueChanged);
-    QVERIFY(spy.isValid());
     timeLine.setFrameRange(10, 20);
     QCOMPARE(timeLine.currentTime(), 0);
     timeLine.start();
-    QTest::qWait(timeLine.duration()/2);
-    QCOMPARE(timeLine.state(), QTimeLine::Running);
-    QVERIFY(timeLine.currentTime() > timeLine.duration()/2 - timeLine.duration()/10);
-    QVERIFY(timeLine.currentTime() < timeLine.duration()/2 + timeLine.duration()/10);
-    QTest::qWait(timeLine.duration()/4 + timeLine.duration());
-    QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
+    QTRY_COMPARE(timeLine.state(), QTimeLine::Running);
+    QTRY_VERIFY(timeLine.currentTime() > timeLine.duration()/2 - timeLine.duration()/4);
+    QVERIFY(timeLine.currentTime() < timeLine.duration()/2 + timeLine.duration()/4);
+    QTRY_COMPARE(timeLine.state(), QTimeLine::NotRunning);
     QCOMPARE(timeLine.currentTime(), timeLine.duration());
 
+    QSignalSpy spy(&timeLine, &QTimeLine::valueChanged);
+    QVERIFY(spy.isValid());
     spy.clear();
     timeLine.setCurrentTime(timeLine.duration()/2);
     timeLine.setCurrentTime(timeLine.duration()/2);
@@ -144,24 +133,22 @@ void tst_QTimeLine::currentTime()
     QCOMPARE(timeLine.currentTime(), timeLine.duration()/2);
     timeLine.resume();
     // Let it update on its own
-    QTest::qWait(timeLine.duration()/4);
     QCOMPARE(timeLine.state(), QTimeLine::Running);
-    QVERIFY(timeLine.currentTime() > timeLine.duration()/2);
+    QTRY_VERIFY(timeLine.currentTime() > timeLine.duration()/2);
     QVERIFY(timeLine.currentTime() < timeLine.duration());
-    QTest::qWait(timeLine.duration()/4 + timeLine.duration());
-    QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
-    QVERIFY(timeLine.currentTime() == timeLine.duration());
+    QTRY_COMPARE(timeLine.state(), QTimeLine::NotRunning);
+    QCOMPARE(timeLine.currentTime(), timeLine.duration());
 
     // Reverse should decrease the currentTime
     timeLine.setCurrentTime(timeLine.duration()/2);
     timeLine.start();
     // Let it update on its own
-    QTest::qWait(timeLine.duration()/4);
-    QCOMPARE(timeLine.state(), QTimeLine::Running);
     int currentTime = timeLine.currentTime();
+    QTRY_VERIFY(timeLine.currentTime() > currentTime);
+    QCOMPARE(timeLine.state(), QTimeLine::Running);
+    currentTime = timeLine.currentTime();
     timeLine.setDirection(QTimeLine::Backward);
-    QTest::qWait(timeLine.duration()/4);
-    QVERIFY(timeLine.currentTime() < currentTime);
+    QTRY_VERIFY(timeLine.currentTime() < currentTime);
     timeLine.stop();
 }
 
@@ -174,11 +161,9 @@ void tst_QTimeLine::duration()
     QCOMPARE(timeLine.duration(), 1000);
 
     timeLine.start();
-    QTest::qWait(999);
-    QCOMPARE(timeLine.state(), QTimeLine::Running);
-    QVERIFY(timeLine.currentTime() > 900);
-    QTest::qWait(100);
-    QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
+    QTRY_COMPARE(timeLine.state(), QTimeLine::Running);
+    QTRY_VERIFY(timeLine.currentTime() > 0);
+    QTRY_COMPARE(timeLine.state(), QTimeLine::NotRunning);
     QCOMPARE(timeLine.currentTime(), 1000);
     // The duration shouldn't change
     QCOMPARE(timeLine.duration(), 1000);
@@ -187,7 +172,7 @@ void tst_QTimeLine::duration()
 void tst_QTimeLine::frameRate()
 {
     QTimeLine timeLine;
-    timeLine.setFrameRange(10, 20);
+    timeLine.setFrameRange(100, 2000);
     QCOMPARE(timeLine.updateInterval(), 1000 / 25);
     timeLine.setUpdateInterval(1000 / 60);
     QCOMPARE(timeLine.updateInterval(), 1000 / 60);
@@ -213,31 +198,27 @@ void tst_QTimeLine::frameRate()
 
 void tst_QTimeLine::value()
 {
-    QTimeLine timeLine(2000);
-    QVERIFY(timeLine.currentValue() == 0.0);
+    QTimeLine timeLine(5000);
+    QCOMPARE(timeLine.currentValue(), 0.0);
 
     // Default speed
     QSignalSpy spy(&timeLine, &QTimeLine::valueChanged);
     QVERIFY(spy.isValid());
     timeLine.start();
-    QTest::qWait(timeLine.duration()/3);
-    QVERIFY(timeLine.currentValue() > 0);
-    QTest::qWait(timeLine.duration());
-    QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
-    qreal currentValue = timeLine.currentValue();
-    QVERIFY(currentValue == 1);
+    QTRY_VERIFY(timeLine.currentValue() > 0);
+    QTRY_COMPARE(timeLine.state(), QTimeLine::NotRunning);
+    QCOMPARE(timeLine.currentValue(), 1.0);
     QVERIFY(spy.count() > 0);
 
     // Reverse should decrease the value
     timeLine.setCurrentTime(100);
     timeLine.start();
     // Let it update on its own
-    QTest::qWait(500);
     QCOMPARE(timeLine.state(), QTimeLine::Running);
+    QTRY_VERIFY(timeLine.currentValue());
     qreal value = timeLine.currentValue();
     timeLine.setDirection(QTimeLine::Backward);
-    QTest::qWait(1000);
-    QVERIFY(timeLine.currentValue() < value);
+    QTRY_VERIFY(timeLine.currentValue() < value);
     timeLine.stop();
 }
 
@@ -251,22 +232,19 @@ void tst_QTimeLine::currentFrame()
     QSignalSpy spy(&timeLine, &QTimeLine::frameChanged);
     QVERIFY(spy.isValid());
     timeLine.start();
-    QTest::qWait(timeLine.duration()/3);
-    QVERIFY(timeLine.currentFrame() > 10);
-    QTest::qWait(timeLine.duration());
-    QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
+    QTRY_VERIFY(timeLine.currentFrame() > 10);
+    QTRY_COMPARE(timeLine.state(), QTimeLine::NotRunning);
     QCOMPARE(timeLine.currentFrame(), 20);
 
     // Reverse should decrease the value
     timeLine.setCurrentTime(timeLine.duration()/2);
     timeLine.start();
     // Let it update on its own
-    QTest::qWait(timeLine.duration()/4);
     QCOMPARE(timeLine.state(), QTimeLine::Running);
+    QTRY_VERIFY(timeLine.currentTime() > timeLine.duration()/2); // wait for continuation
     int value = timeLine.currentFrame();
     timeLine.setDirection(QTimeLine::Backward);
-    QTest::qWait(timeLine.duration()/2);
-    QVERIFY(timeLine.currentFrame() < value);
+    QTRY_VERIFY(timeLine.currentFrame() < value);
     timeLine.stop();
 }
 
@@ -505,9 +483,8 @@ void tst_QTimeLine::finished()
     QSignalSpy spy(&timeLine, &QTimeLine::finished);
     QVERIFY(spy.isValid());
     timeLine.start();
-    QTest::qWait(timeLine.duration()*2);
+    QTRY_COMPARE(spy.count(), 1);
     QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
-    QCOMPARE(spy.count(), 1);
 
     spy.clear();
     timeLine.start();
@@ -606,16 +583,15 @@ void tst_QTimeLine::resume()
     {
         QCOMPARE(timeLine.currentTime(), 0);
         timeLine.start();
-        QTest::qWait(250);
+        QTRY_VERIFY(timeLine.currentTime() > 0);
         timeLine.stop();
         int oldCurrentTime = timeLine.currentTime();
         QVERIFY(oldCurrentTime > 0);
         QVERIFY(oldCurrentTime < 1000);
         timeLine.resume();
-        QTest::qWait(250);
+        QTRY_VERIFY(timeLine.currentTime() > oldCurrentTime);
         timeLine.stop();
         int currentTime = timeLine.currentTime();
-        QVERIFY(currentTime > oldCurrentTime);
         QVERIFY(currentTime < 1000);
     }
     timeLine.setDirection(QTimeLine::Backward);
@@ -623,13 +599,13 @@ void tst_QTimeLine::resume()
         timeLine.setCurrentTime(1000);
         QCOMPARE(timeLine.currentTime(), 1000);
         timeLine.start();
-        QTest::qWait(250);
+        QTRY_VERIFY(timeLine.currentTime() < 1000);
         timeLine.stop();
         int oldCurrentTime = timeLine.currentTime();
         QVERIFY(oldCurrentTime < 1000);
         QVERIFY(oldCurrentTime > 0);
         timeLine.resume();
-        QTest::qWait(250);
+        QTRY_VERIFY(timeLine.currentTime() < oldCurrentTime);
         timeLine.stop();
         int currentTime = timeLine.currentTime();
         QVERIFY(currentTime < oldCurrentTime);
@@ -643,8 +619,7 @@ void tst_QTimeLine::restart()
     timeLine.setFrameRange(0,9);
 
     timeLine.start();
-    QTest::qWait(timeLine.duration()*2);
-    QCOMPARE(timeLine.currentFrame(), timeLine.endFrame());
+    QTRY_COMPARE(timeLine.currentFrame(), timeLine.endFrame());
     QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
 
     // A restart with the same duration
@@ -652,8 +627,7 @@ void tst_QTimeLine::restart()
     QCOMPARE(timeLine.state(), QTimeLine::Running);
     QCOMPARE(timeLine.currentFrame(), timeLine.startFrame());
     QCOMPARE(timeLine.currentTime(), 0);
-    QTest::qWait(250);
-    QCOMPARE(timeLine.currentFrame(), timeLine.endFrame());
+    QTRY_COMPARE(timeLine.currentFrame(), timeLine.endFrame());
     QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
 
     // Set a smaller duration and restart
@@ -662,8 +636,7 @@ void tst_QTimeLine::restart()
     QCOMPARE(timeLine.state(), QTimeLine::Running);
     QCOMPARE(timeLine.currentFrame(), timeLine.startFrame());
     QCOMPARE(timeLine.currentTime(), 0);
-    QTest::qWait(250);
-    QCOMPARE(timeLine.currentFrame(), timeLine.endFrame());
+    QTRY_COMPARE(timeLine.currentFrame(), timeLine.endFrame());
     QCOMPARE(timeLine.state(), QTimeLine::NotRunning);
 
     // Set a longer duration and restart
diff --git a/tests/auto/dbus/dbus.pro b/tests/auto/dbus/dbus.pro
index bd1fef519375990d1f20cfc55d5ecd35e52ae25a..67cbc4bfef3a81f9e322fd7c82cbb7a93a0def3d 100644
--- a/tests/auto/dbus/dbus.pro
+++ b/tests/auto/dbus/dbus.pro
@@ -1,10 +1,16 @@
 TEMPLATE=subdirs
+
+# Run this test first
 SUBDIRS=\
+           qdbusconnection_delayed
+
+SUBDIRS+=\
            qdbusabstractadaptor \
            qdbusabstractinterface \
            qdbusconnection \
            qdbusconnection_no_app \
            qdbusconnection_no_bus \
+           qdbusconnection_no_libdbus \
            qdbuscontext \
            qdbusinterface \
            qdbuslocalcalls \
diff --git a/tests/auto/dbus/qdbusconnection_delayed/qdbusconnection_delayed.pro b/tests/auto/dbus/qdbusconnection_delayed/qdbusconnection_delayed.pro
new file mode 100644
index 0000000000000000000000000000000000000000..71a75c644d05e4a4c2d1587f3159f5a4d2687922
--- /dev/null
+++ b/tests/auto/dbus/qdbusconnection_delayed/qdbusconnection_delayed.pro
@@ -0,0 +1,5 @@
+CONFIG += testcase parallel_test
+TARGET = tst_qdbusconnection_delayed
+QT = core dbus testlib
+SOURCES += tst_qdbusconnection_delayed.cpp
+DEFINES += SRCDIR=\\\"$$PWD/\\\"
diff --git a/tests/auto/dbus/qdbusconnection_delayed/tst_qdbusconnection_delayed.cpp b/tests/auto/dbus/qdbusconnection_delayed/tst_qdbusconnection_delayed.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c4f30631692f1b39efccb51a322b75f16743b5e0
--- /dev/null
+++ b/tests/auto/dbus/qdbusconnection_delayed/tst_qdbusconnection_delayed.cpp
@@ -0,0 +1,113 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the test suite of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** 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 http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://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 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtDBus>
+#include <QtTest>
+
+#ifdef Q_OS_WIN
+#  include <process.h>
+#  define getpid _getpid
+#else
+#  include <sys/types.h>
+#  include <unistd.h>
+#endif
+
+class tst_QDBusConnection_Delayed : public QObject
+{
+    Q_OBJECT
+private slots:
+    void delayedMessages();
+};
+
+class Foo : public QObject
+{
+    Q_OBJECT
+    Q_CLASSINFO("D-Bus Interface", "org.qtproject.tst_qdbusconnection_delayed.Foo")
+public slots:
+    int bar() { return 42; }
+};
+
+static bool executedOnce = false;
+
+void tst_QDBusConnection_Delayed::delayedMessages()
+{
+    if (executedOnce)
+        QSKIP("This test can only be executed once");
+    executedOnce = true;
+
+    int argc = 1;
+    char *argv[] = { const_cast<char *>("tst_qdbusconnection_delayed"), 0 };
+    QCoreApplication app(argc, argv);
+
+    QDBusConnection session = QDBusConnection::sessionBus();
+    QVERIFY(session.isConnected());
+    QVERIFY(!session.baseService().isEmpty());
+
+    QDBusConnection other = QDBusConnection::connectToBus(QDBusConnection::SessionBus, "other");
+    QVERIFY(other.isConnected());
+    QVERIFY(!other.baseService().isEmpty());
+
+    // make a method call: those should work even if delivery is disabled
+    QVERIFY(session.interface()->isServiceRegistered(other.baseService()));
+
+    // acquire a name in the main session bus connection: the effect is immediate
+    QString name = "org.qtproject.tst_qdbusconnection_delayed-" +
+                   QString::number(getpid());
+    QVERIFY(session.registerService(name));
+    QVERIFY(other.interface()->isServiceRegistered(name));
+
+    // make an asynchronous call to a yet-unregistered object
+    QDBusPendingCallWatcher pending(other.asyncCall(QDBusMessage::createMethodCall(name, "/foo", QString(), "bar")));
+
+    // sleep the main thread without running the event loop;
+    // the call must not be delivered
+    QTest::qSleep(1000);
+    QVERIFY(!pending.isFinished());
+
+    // now register the object
+    Foo foo;
+    session.registerObject("/foo", &foo, QDBusConnection::ExportAllSlots);
+
+    connect(&pending, &QDBusPendingCallWatcher::finished,
+            &QTestEventLoop::instance(), &QTestEventLoop::exitLoop);
+    QTestEventLoop::instance().enterLoop(2);
+    QVERIFY(!QTestEventLoop::instance().timeout());
+    QVERIFY(pending.isFinished());
+    QVERIFY2(!pending.isError(), pending.error().name().toLatin1());
+    QVERIFY(!pending.reply().arguments().isEmpty());
+    QCOMPARE(pending.reply().arguments().at(0), QVariant(42));
+}
+
+QTEST_APPLESS_MAIN(tst_QDBusConnection_Delayed)
+
+#include "tst_qdbusconnection_delayed.moc"
diff --git a/tests/auto/dbus/qdbusconnection_no_bus/qdbusconnection_no_bus.pro b/tests/auto/dbus/qdbusconnection_no_bus/qdbusconnection_no_bus.pro
index 7b15a4fb81f78fc8f3bd2027ccf2b5332a6984e8..57712f0689b3ce54f4823c43415ab03576f9e33a 100644
--- a/tests/auto/dbus/qdbusconnection_no_bus/qdbusconnection_no_bus.pro
+++ b/tests/auto/dbus/qdbusconnection_no_bus/qdbusconnection_no_bus.pro
@@ -1,4 +1,4 @@
-CONFIG += testcase
+CONFIG += testcase parallel_test
 TARGET = tst_qdbusconnection_no_bus
 QT = core dbus testlib
 SOURCES += tst_qdbusconnection_no_bus.cpp
diff --git a/tests/auto/dbus/qdbusconnection_no_bus/tst_qdbusconnection_no_bus.cpp b/tests/auto/dbus/qdbusconnection_no_bus/tst_qdbusconnection_no_bus.cpp
index 21f8f11f80c14b31d99010bc619a9ee7521c7a63..5a740960596fb68efe8fd534472d4025b6bb6b93 100644
--- a/tests/auto/dbus/qdbusconnection_no_bus/tst_qdbusconnection_no_bus.cpp
+++ b/tests/auto/dbus/qdbusconnection_no_bus/tst_qdbusconnection_no_bus.cpp
@@ -52,7 +52,9 @@ public:
     tst_QDBusConnectionNoBus()
     {
         qputenv("DBUS_SESSION_BUS_ADDRESS", "unix:abstract=/tmp/does_not_exist");
+#ifdef SIMULATE_LOAD_FAIL
         qputenv("QT_SIMULATE_DBUS_LIBFAIL", "1");
+#endif
     }
 
 private slots:
@@ -67,7 +69,7 @@ void tst_QDBusConnectionNoBus::connectToBus()
 
     QDBusConnection con = QDBusConnection::sessionBus();
 
-    QVERIFY(true); // if we didn't crash here, the test passed :)
+    QVERIFY(!con.isConnected()); // if we didn't crash here, the test passed :)
 }
 
 QTEST_APPLESS_MAIN(tst_QDBusConnectionNoBus)
diff --git a/tests/auto/dbus/qdbusconnection_no_libdbus/qdbusconnection_no_libdbus.pro b/tests/auto/dbus/qdbusconnection_no_libdbus/qdbusconnection_no_libdbus.pro
new file mode 100644
index 0000000000000000000000000000000000000000..cb0eab1a187fd168f67073acfe71789d82be072e
--- /dev/null
+++ b/tests/auto/dbus/qdbusconnection_no_libdbus/qdbusconnection_no_libdbus.pro
@@ -0,0 +1,5 @@
+CONFIG += testcase parallel_test
+TARGET = tst_qdbusconnection_no_libdbus
+QT = core dbus testlib
+DEFINES += SIMULATE_LOAD_FAIL
+SOURCES += ../qdbusconnection_no_bus/tst_qdbusconnection_no_bus.cpp
diff --git a/tests/auto/dbus/qdbusmetaobject/qdbusmetaobject.pro b/tests/auto/dbus/qdbusmetaobject/qdbusmetaobject.pro
index c0b38cf478919555bf0ed92884d2bc5291c9ac6a..26dd58a0102054d4b0437d7829d2304ca352265d 100644
--- a/tests/auto/dbus/qdbusmetaobject/qdbusmetaobject.pro
+++ b/tests/auto/dbus/qdbusmetaobject/qdbusmetaobject.pro
@@ -1,4 +1,4 @@
-CONFIG += testcase
+CONFIG += testcase parallel_test
 TARGET = tst_qdbusmetaobject
 QT = core dbus-private testlib
 SOURCES += tst_qdbusmetaobject.cpp
diff --git a/tests/auto/dbus/qdbusmetatype/qdbusmetatype.pro b/tests/auto/dbus/qdbusmetatype/qdbusmetatype.pro
index aef9bc73cbe42759d694c34a01a7aef3ba0b77bc..ac020b435acf83c56424b150a531bb665e266420 100644
--- a/tests/auto/dbus/qdbusmetatype/qdbusmetatype.pro
+++ b/tests/auto/dbus/qdbusmetatype/qdbusmetatype.pro
@@ -1,4 +1,4 @@
-CONFIG += testcase
+CONFIG += testcase parallel_test
 TARGET = tst_qdbusmetatype
 QT = core dbus testlib
 SOURCES += tst_qdbusmetatype.cpp
diff --git a/tests/auto/dbus/qdbustype/qdbustype.pro b/tests/auto/dbus/qdbustype/qdbustype.pro
index 21df33d2c7296ed1e6ee690e9a7c8d3a5e00989c..7db87d279ee4919ad15d1ddccdafc0e52705b502 100644
--- a/tests/auto/dbus/qdbustype/qdbustype.pro
+++ b/tests/auto/dbus/qdbustype/qdbustype.pro
@@ -1,4 +1,4 @@
-CONFIG += testcase
+CONFIG += testcase parallel_test
 TARGET = tst_qdbustype
 QT = core-private dbus-private testlib
 SOURCES += tst_qdbustype.cpp
diff --git a/tests/auto/dbus/qdbusxmlparser/qdbusxmlparser.pro b/tests/auto/dbus/qdbusxmlparser/qdbusxmlparser.pro
index a7186c341b42b62f4dc9857ccf2fd40e501faf00..6cdd09007c68866dfa1ac345c5dfc70be5ce95dd 100644
--- a/tests/auto/dbus/qdbusxmlparser/qdbusxmlparser.pro
+++ b/tests/auto/dbus/qdbusxmlparser/qdbusxmlparser.pro
@@ -1,4 +1,4 @@
-CONFIG += testcase
+CONFIG += testcase parallel_test
 TARGET = tst_qdbusxmlparser
 QT = core-private dbus-private xml testlib
 SOURCES += tst_qdbusxmlparser.cpp
diff --git a/tests/auto/gui/kernel/qclipboard/test/test.pro b/tests/auto/gui/kernel/qclipboard/test/test.pro
index f27c582de2e660de6bd7e44a9320fab9014fc5cf..40bf9c8d8ea4cd78294d3087a13a47c6fb1135e3 100644
--- a/tests/auto/gui/kernel/qclipboard/test/test.pro
+++ b/tests/auto/gui/kernel/qclipboard/test/test.pro
@@ -3,6 +3,8 @@ SOURCES  += ../tst_qclipboard.cpp
 TARGET = ../tst_qclipboard
 QT += testlib
 
+osx: LIBS += -framework AppKit
+
 win32 {
   CONFIG(debug, debug|release) {
     TARGET = ../../debug/tst_qclipboard
diff --git a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp
index 2219306b814690a10e752f5dd28423ad36d0b9d2..a89f0da4d27c01a345a475ebf7fcaffb83d797c3 100644
--- a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp
+++ b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp
@@ -95,6 +95,8 @@ private slots:
     void windowsTransientChildren();
     void requestUpdate();
     void initTestCase();
+    void stateChange_data();
+    void stateChange();
     void cleanup();
 
 private:
@@ -272,6 +274,18 @@ static inline bool qFuzzyCompareWindowPosition(const QPoint &p1, const QPoint p2
     return (p1 - p2).manhattanLength() <= fuzz;
 }
 
+static inline bool qFuzzyCompareWindowSize(const QSize &s1, const QSize &s2, int fuzz)
+{
+    const int manhattanLength = qAbs(s1.width() - s2.width()) + qAbs(s1.height() - s2.height());
+    return manhattanLength <= fuzz;
+}
+
+static inline bool qFuzzyCompareWindowGeometry(const QRect &r1, const QRect &r2, int fuzz)
+{
+    return qFuzzyCompareWindowPosition(r1.topLeft(), r2.topLeft(), fuzz)
+        && qFuzzyCompareWindowSize(r1.size(), r2.size(), fuzz);
+}
+
 static QString msgPointMismatch(const QPoint &p1, const QPoint p2)
 {
     QString result;
@@ -279,6 +293,13 @@ static QString msgPointMismatch(const QPoint &p1, const QPoint p2)
     return result;
 }
 
+static QString msgRectMismatch(const QRect &r1, const QRect &r2)
+{
+    QString result;
+    QDebug(&result) << r1 << "!=" << r2;
+    return result;
+}
+
 void tst_QWindow::positioning()
 {
     if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(
@@ -394,6 +415,52 @@ void tst_QWindow::positioningDuringMinimized()
     QTRY_COMPARE(window.geometry(), newGeometry);
 }
 
+// QTBUG-49709: Verify that the normal geometry is correctly restored
+// when executing a sequence of window state changes. So far, Windows
+// only where state changes have immediate effect.
+
+typedef QList<Qt::WindowState> WindowStateList;
+
+Q_DECLARE_METATYPE(WindowStateList)
+
+void tst_QWindow::stateChange_data()
+{
+    QTest::addColumn<WindowStateList>("stateSequence");
+
+    QTest::newRow("normal->min->normal") <<
+        (WindowStateList() << Qt::WindowMinimized << Qt::WindowNoState);
+    QTest::newRow("normal->maximized->normal") <<
+        (WindowStateList() << Qt::WindowMaximized << Qt::WindowNoState);
+    QTest::newRow("normal->fullscreen->normal") <<
+        (WindowStateList() << Qt::WindowFullScreen << Qt::WindowNoState);
+    QTest::newRow("normal->maximized->fullscreen->normal") <<
+        (WindowStateList() << Qt::WindowMaximized << Qt::WindowFullScreen << Qt::WindowNoState);
+}
+
+void tst_QWindow::stateChange()
+{
+    QFETCH(WindowStateList, stateSequence);
+
+    if (QGuiApplication::platformName().compare(QLatin1String("windows"), Qt::CaseInsensitive))
+        QSKIP("Windows-only test");
+
+    Window window;
+    window.setTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char(' ') + QLatin1String(QTest::currentDataTag()));
+    const QRect normalGeometry(m_availableTopLeft + QPoint(40, 40), m_testWindowSize);
+    window.setGeometry(normalGeometry);
+    //  explicitly use non-fullscreen show. show() can be fullscreen on some platforms
+    window.showNormal();
+    QVERIFY(QTest::qWaitForWindowExposed(&window));
+    foreach (Qt::WindowState state, stateSequence) {
+        window.setWindowState(state);
+        QCoreApplication::processEvents();
+    }
+    const QRect geometry = window.geometry();
+    const int fuzz = int(QHighDpiScaling::factor(&window));
+    QVERIFY2(qFuzzyCompareWindowGeometry(geometry, normalGeometry, fuzz),
+             qPrintable(msgRectMismatch(geometry, normalGeometry)));
+}
+
 class PlatformWindowFilter : public QObject
 {
     Q_OBJECT
diff --git a/tests/auto/network/kernel/qhostinfo/qhostinfo.pro b/tests/auto/network/kernel/qhostinfo/qhostinfo.pro
index c9b795d0988ef68442b7f16d6888fc28bf9def78..12858c97eee244c8ade2f44f5443e4f982d6d948 100644
--- a/tests/auto/network/kernel/qhostinfo/qhostinfo.pro
+++ b/tests/auto/network/kernel/qhostinfo/qhostinfo.pro
@@ -14,3 +14,5 @@ wince {
 
 # needed for getaddrinfo with official MinGW
 mingw:DEFINES += _WIN32_WINNT=0x0501
+
+winrt: WINRT_MANIFEST.capabilities += internetClientServer
diff --git a/tests/auto/opengl/qglthreads/tst_qglthreads.cpp b/tests/auto/opengl/qglthreads/tst_qglthreads.cpp
index ff5a18dedb65c9ea65ae230082ecdf6aa6e9c331..6a726ac62d112ab249d6287ec31cfe5d31974b4e 100644
--- a/tests/auto/opengl/qglthreads/tst_qglthreads.cpp
+++ b/tests/auto/opengl/qglthreads/tst_qglthreads.cpp
@@ -796,7 +796,6 @@ void tst_QGLThreads::painterOnFboInThread()
 
 int main(int argc, char **argv)
 {
-    QApplication::setAttribute(Qt::AA_X11InitThreads);
     QApplication app(argc, argv);
     QTEST_DISABLE_KEYPAD_NAVIGATION \
 
diff --git a/tests/auto/other/gestures/tst_gestures.cpp b/tests/auto/other/gestures/tst_gestures.cpp
index 2a4f88c62745532afb432341a346e956062a0772..6db918cffd0a9fc095d3b61a220943845a9392b6 100644
--- a/tests/auto/other/gestures/tst_gestures.cpp
+++ b/tests/auto/other/gestures/tst_gestures.cpp
@@ -48,6 +48,24 @@
 
 #include <qdebug.h>
 
+static bool waitForWindowExposed(QWindow *window)
+{
+    if (!window)
+        return false;
+#ifdef Q_OS_OSX
+    QTest::qWait(100);
+    return window->isExposed();
+#endif
+    return QTest::qWaitForWindowExposed(window);
+}
+
+static bool waitForWindowExposed(QWidget *widget)
+{
+    if (!widget)
+        return false;
+    return waitForWindowExposed(widget->windowHandle());
+}
+
 static QPointF mapToGlobal(const QPointF &pt, QGraphicsItem *item, QGraphicsView *view)
 {
     return view->viewport()->mapToGlobal(view->mapFromScene(item->mapToScene(pt)));
@@ -387,7 +405,7 @@ void tst_Gestures::customGesture()
     GestureWidget widget;
     widget.grabGesture(CustomGesture::GestureType, Qt::DontStartGestureOnChildren);
     widget.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&widget));
+    QVERIFY(waitForWindowExposed(&widget));
 
     CustomEvent event;
     event.hotSpot = widget.mapToGlobal(QPoint(5,5));
@@ -856,7 +874,7 @@ void tst_Gestures::graphicsItemGesture()
     item->setPos(100, 100);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     item->grabGesture(CustomGesture::GestureType);
@@ -918,7 +936,7 @@ void tst_Gestures::graphicsView()
     item->setPos(100, 100);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     item->grabGesture(CustomGesture::GestureType);
@@ -994,7 +1012,7 @@ void tst_Gestures::graphicsItemTreeGesture()
     item1_child2->setParentItem(item1);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     item1->grabGesture(CustomGesture::GestureType);
@@ -1051,7 +1069,7 @@ void tst_Gestures::explicitGraphicsObjectTarget()
     item2_child1->setPos(10, 10);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     item1->grabGesture(CustomGesture::GestureType, Qt::DontStartGestureOnChildren);
@@ -1110,7 +1128,7 @@ void tst_Gestures::gestureOverChildGraphicsItem()
     item2_child1->setPos(0, 0);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     item1->grabGesture(CustomGesture::GestureType);
@@ -1408,7 +1426,7 @@ void tst_Gestures::testMapToScene()
     item0->setPos(14, 16);
 
     view.show(); // need to show to give it a global coordinate
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     QPoint origin = view.mapToGlobal(QPoint());
@@ -1534,7 +1552,7 @@ void tst_Gestures::autoCancelGestures()
     parent.grabGesture(CustomGesture::GestureType);
     child->grabGesture(secondGesture);
     parent.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&parent));
+    QVERIFY(waitForWindowExposed(&parent));
 
     /*
       An event is sent to both the child and the parent, when the child gets it a gesture is triggered
@@ -1593,7 +1611,7 @@ void tst_Gestures::autoCancelGestures2()
     child->grabGesture(secondGesture);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     CustomEvent event;
@@ -1639,7 +1657,7 @@ void tst_Gestures::graphicsViewParentPropagation()
     item1_c1_c1->setPos(0, 0);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     item0->grabGesture(CustomGesture::GestureType, Qt::ReceivePartialGestures | Qt::IgnoredGesturesPropagateToParent);
@@ -1709,7 +1727,7 @@ void tst_Gestures::panelPropagation()
     item1_child1_child1->setZValue(10);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     static const int TotalGestureEventsCount = CustomGesture::SerialFinishedThreshold - CustomGesture::SerialStartedThreshold + 1;
@@ -1820,7 +1838,7 @@ void tst_Gestures::panelStacksBehindParent()
     panel->setZValue(5);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     static const int TotalGestureEventsCount = CustomGesture::SerialFinishedThreshold - CustomGesture::SerialStartedThreshold + 1;
@@ -1904,7 +1922,7 @@ void tst_Gestures::deleteGestureTargetItem()
     items.insert(item2->objectName(), item2);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     if (propagateUpdateGesture)
@@ -1949,7 +1967,7 @@ void tst_Gestures::viewportCoordinates()
     scene.addItem(item1);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     CustomEvent event;
@@ -1986,7 +2004,7 @@ void tst_Gestures::partialGesturePropagation()
     scene.addItem(item4);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     item1->ignoredUpdatedGestures << CustomGesture::GestureType;
@@ -2074,7 +2092,7 @@ void tst_Gestures::testQGestureRecognizerCleanup()
     //QGestureRecognizer::registerRecognizer(new PanRecognizer(PanRecognizer::Custom));
 
     w->show();
-    QVERIFY(QTest::qWaitForWindowExposed(w));
+    QVERIFY(waitForWindowExposed(w));
     delete w;
 }
 
@@ -2195,7 +2213,7 @@ void tst_Gestures::testReuseCanceledGestures()
     gv->viewport()->grabGesture(tapGestureTypeId);
 
     mw.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&mw));
+    QVERIFY(waitForWindowExposed(&mw));
 
     QPoint targetPos(gv->mapFromScene(target->mapToScene(target->rect().center())));
     targetPos = gv->viewport()->mapFromParent(targetPos);
@@ -2261,7 +2279,7 @@ void tst_Gestures::conflictingGesturesInGraphicsView()
     scene.addItem(item2);
 
     view.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&view));
+    QVERIFY(waitForWindowExposed(&view));
     view.ensureVisible(scene.sceneRect());
 
     static const int TotalGestureEventsCount = CustomGesture::SerialFinishedThreshold - CustomGesture::SerialStartedThreshold + 1;
@@ -2326,7 +2344,7 @@ void tst_Gestures::bug_13501_gesture_not_accepted()
     NoConsumeWidgetBug13501 w;
     w.grabGesture(Qt::TapGesture);
     w.show();
-    QVERIFY(QTest::qWaitForWindowExposed(&w));
+    QVERIFY(waitForWindowExposed(&w));
     //QTest::mousePress(&ignoreEvent, Qt::LeftButton);
     QTouchDevice *device = new QTouchDevice;
     device->setType(QTouchDevice::TouchScreen);
diff --git a/tests/auto/other/macgui/macgui.pro b/tests/auto/other/macgui/macgui.pro
index bf805ccd75d9c5592e1374109856ac58d0ce8bc2..a793a304ca7c186cab1969b9bfc2c964f3beb8b6 100644
--- a/tests/auto/other/macgui/macgui.pro
+++ b/tests/auto/other/macgui/macgui.pro
@@ -6,5 +6,7 @@ HEADERS += guitest.h
 
 QT = core-private widgets-private testlib
 
+osx: LIBS += -framework ApplicationServices
+
 requires(mac)
 DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
diff --git a/tests/auto/other/toolsupport/tst_toolsupport.cpp b/tests/auto/other/toolsupport/tst_toolsupport.cpp
index f3c99af8ba64329ae631d7de4cf87483b27e6603..92127fcd5c2dd48c0bdc211e996f49a06c608d8f 100644
--- a/tests/auto/other/toolsupport/tst_toolsupport.cpp
+++ b/tests/auto/other/toolsupport/tst_toolsupport.cpp
@@ -111,7 +111,7 @@ void tst_toolsupport::offsets_data()
     }
 
 #ifdef Q_OS_LINUX
-    if (sizeof(void *) == 8) {
+    {
         QTestData &data = QTest::newRow("QFilePrivate::fileName")
                 << pmm_to_offsetof(&QFilePrivate::fileName);
         data << 168 << 248;
diff --git a/tests/auto/tools/qmake/testdata/findMocs/findMocs.pro b/tests/auto/tools/qmake/testdata/findMocs/findMocs.pro
index a4a7dc987d59b9cc6a606d4e2b6309319b6319c5..af672c262166fd2ca41406cf7e8622ffe233825d 100644
--- a/tests/auto/tools/qmake/testdata/findMocs/findMocs.pro
+++ b/tests/auto/tools/qmake/testdata/findMocs/findMocs.pro
@@ -1,4 +1,5 @@
 DESTDIR	= ./
 
-HEADERS += object1.h object2.h object3.h object4.h object5.h object6.h object7.h
+HEADERS += object1.h object2.h object3.h object4.h \
+        object5.h object6.h object7.h object8.h object9.h
 SOURCES += main.cpp
diff --git a/tests/auto/tools/qmake/testdata/findMocs/main.cpp b/tests/auto/tools/qmake/testdata/findMocs/main.cpp
index 8e0ef9fc415ec021a383e1f2e87e5adc4c52f4fb..3f566c4af4d66060b3364602ce6a0922893ca0b6 100644
--- a/tests/auto/tools/qmake/testdata/findMocs/main.cpp
+++ b/tests/auto/tools/qmake/testdata/findMocs/main.cpp
@@ -39,6 +39,7 @@
 #include <moc_object5.cpp>
 #include <moc_object6.cpp>
 #include <moc_object7.cpp>
+#include     "object8.h"
+#include <moc_object9.cpp>
 
-int main () {}
-
+int main() { return 0; }
diff --git a/tests/auto/tools/qmake/testdata/findMocs/object1.h b/tests/auto/tools/qmake/testdata/findMocs/object1.h
index e0857f429738ec8430c40d116df655dfc8870b96..1fcac5f51167da88713e53a18b41ecd9e16fbde3 100644
--- a/tests/auto/tools/qmake/testdata/findMocs/object1.h
+++ b/tests/auto/tools/qmake/testdata/findMocs/object1.h
@@ -37,6 +37,6 @@
 
 class Object1 : public QObject
 {
-    Q_OBJECT
+    Q\
+_OBJECT
 };
-
diff --git a/tests/auto/tools/qmake/testdata/findMocs/object2.h b/tests/auto/tools/qmake/testdata/findMocs/object2.h
index cc60269cd32067aaf6743d8759efe2f211140b6b..a52489b44cb42b112214073a7b2a8eb4ac0b1471 100644
--- a/tests/auto/tools/qmake/testdata/findMocs/object2.h
+++ b/tests/auto/tools/qmake/testdata/findMocs/object2.h
@@ -36,6 +36,6 @@
 
 class Object2 : public QObject
 {
-    Q_OBJECT
+    Q_\
+OBJECT
 };
-
diff --git a/tests/auto/tools/qmake/testdata/findMocs/object3.h b/tests/auto/tools/qmake/testdata/findMocs/object3.h
index c66edee6e128905847769ced807e5ef31b4d125f..c481a0796da0524128ea84b1e3c2413466e500d5 100644
--- a/tests/auto/tools/qmake/testdata/findMocs/object3.h
+++ b/tests/auto/tools/qmake/testdata/findMocs/object3.h
@@ -37,6 +37,6 @@
 
 class Object3 : public QObject
 {
-    Q_OBJECT
+    Q_OBJ\
+ECT
 };
-
diff --git a/tests/auto/tools/qmake/testdata/findMocs/object4.h b/tests/auto/tools/qmake/testdata/findMocs/object4.h
index 73bf9cdaa3451a67af0a708e59c6daa7737d35bf..eb38652f147e003cdd26d4c1227febfaf4cfca15 100644
--- a/tests/auto/tools/qmake/testdata/findMocs/object4.h
+++ b/tests/auto/tools/qmake/testdata/findMocs/object4.h
@@ -44,10 +44,9 @@ class Object4 : public QObject
 Comment ends there --> /*/
 
 // Now we poison moc, just to make sure this doesn't get moc'ed :)
-class NonMocObject
+class NonMocObject4
 /*  : QObject */
 {
     /* qmake ignore Q_OBJECT */
     Q_OBJECT
 };
-
diff --git a/tests/auto/tools/qmake/testdata/findMocs/object8.h b/tests/auto/tools/qmake/testdata/findMocs/object8.h
new file mode 100644
index 0000000000000000000000000000000000000000..51096e4c27a9dcac29bdf662f2e0894183cf6d3c
--- /dev/null
+++ b/tests/auto/tools/qmake/testdata/findMocs/object8.h
@@ -0,0 +1,50 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the test suite of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** 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 http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://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 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include <QObject>
+#define Q_OBJECTOID_THING // empty
+
+class Object8 : public QObject
+{
+    Q_OBJECT\
+OID_THING
+};
+
+// Now we poison moc, just to make sure this doesn't get moc'ed :)
+class NonMocObject8
+/*  : QObject */
+{
+    /* qmake ignore Q_OBJECT */
+    Q_OBJECT
+};
diff --git a/tests/auto/tools/qmake/testdata/findMocs/object9.h b/tests/auto/tools/qmake/testdata/findMocs/object9.h
new file mode 100644
index 0000000000000000000000000000000000000000..bda50355d91d43088937952eb5ed1de0be7cdfb0
--- /dev/null
+++ b/tests/auto/tools/qmake/testdata/findMocs/object9.h
@@ -0,0 +1,41 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the test suite of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL21$
+** 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 http://www.qt.io/terms-conditions. For further
+** information use the contact form at http://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 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** As a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include <QObject>
+#define juxtaposed "lorem ""ipsum /*"
+
+class Object9 : public QObject
+{
+    Q_OBJECT
+};
diff --git a/tests/auto/tools/qmake/testdata/rawString/object1.h b/tests/auto/tools/qmake/testdata/rawString/object1.h
index 07af4229fb1645e795ff28b8f7721b6758c8707e..1435624f7b989da529c942c5de6b36e9fcdfc56e 100644
--- a/tests/auto/tools/qmake/testdata/rawString/object1.h
+++ b/tests/auto/tools/qmake/testdata/rawString/object1.h
@@ -31,11 +31,10 @@
 **
 ****************************************************************************/
 
-
+#define rawstring R"blah(lorem " ipsum /*)blah";
 #include <QObject>
 
 class Object1 : public QObject
 {
     Q_OBJECT
 };
-
diff --git a/tests/auto/tools/qmakelib/evaltest.cpp b/tests/auto/tools/qmakelib/evaltest.cpp
index bed4c792a1ecf22f38354056bd3bbfab097181be..beafef5ad23b1127beda24103bbe29d64946d50e 100644
--- a/tests/auto/tools/qmakelib/evaltest.cpp
+++ b/tests/auto/tools/qmakelib/evaltest.cpp
@@ -2205,9 +2205,10 @@ void tst_qmakelib::addTestFunctions(const QString &qindir)
             << ""
             << true;
 
+    // FIXME: This also tests that 'exe' is accepted, but does not test whether it actually works.
     QTest::newRow("write_file(): append")
             << "VAR = 'one more line'\n"
-               "write_file(" + wpath + ", VAR, append): OK = 1\n"
+               "write_file(" + wpath + ", VAR, append exe): OK = 1\n"
                "OUT = $$cat(" + wpath + ", lines)"
             << "OK = 1\nOUT = 'other content' 'one more line'"
             << ""
@@ -2227,7 +2228,13 @@ void tst_qmakelib::addTestFunctions(const QString &qindir)
     QTest::newRow("write_file(): bad number of arguments")
             << "write_file(1, 2, 3, 4): OK = 1"
             << "OK = UNDEF"
-            << "##:1: write_file(name, [content var, [append]]) requires one to three arguments."
+            << "##:1: write_file(name, [content var, [append] [exe]]) requires one to three arguments."
+            << true;
+
+    QTest::newRow("write_file(): invalid flag")
+            << "write_file(file, VAR, fail): OK = 1"
+            << "OK = UNDEF"
+            << "##:1: write_file(): invalid flag fail."
             << true;
 
     // FIXME: This doesn't test whether it actually works.
diff --git a/tests/auto/tools/qmakelib/tst_qmakelib.h b/tests/auto/tools/qmakelib/tst_qmakelib.h
index c4716ca65ef5853f6c827ec52732654384eb8d57..b043d31e21fa22a2c91df662bc2a241f071c66f3 100644
--- a/tests/auto/tools/qmakelib/tst_qmakelib.h
+++ b/tests/auto/tools/qmakelib/tst_qmakelib.h
@@ -90,8 +90,8 @@ public:
     virtual void message(int type, const QString &msg, const QString &fileName, int lineNo)
         { print(fileName, lineNo, type, msg); }
 
-    virtual void fileMessage(const QString &msg)
-        { doPrint(msg); }
+    virtual void fileMessage(int type, const QString &msg)
+        { Q_UNUSED(type) doPrint(msg); }
 
     virtual void aboutToEval(ProFile *, ProFile *, EvalFileType) {}
     virtual void doneWithEval(ProFile *) {}
diff --git a/tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp b/tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp
index f206a5fe9a74b2bfa890c87292f5615ffe2d19b8..15aef8d5038faa77612105f084e76c078a15e2a7 100644
--- a/tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp
+++ b/tests/auto/widgets/kernel/qshortcut/tst_qshortcut.cpp
@@ -72,7 +72,8 @@ public:
         TriggerSlot4,
         TriggerSlot5,
         TriggerSlot6,
-        TriggerSlot7
+        TriggerSlot7,
+        SendKeyEvent
     };
 
     enum Result {
@@ -84,6 +85,7 @@ public:
         Slot5Triggered,
         Slot6Triggered,
         Slot7Triggered,
+        SentKeyEvent,
         Ambiguous
     } currentResult;
 
@@ -104,6 +106,7 @@ public slots:
     void ambigSlot7() { currentResult = Ambiguous; ambigResult = Slot7Triggered; }
     void statusMessage( const QString& message ) { sbText = message; }
     void shortcutDestroyed(QObject* obj);
+    void sendKeyEvent() { sendKeyEvents(edit, Qt::CTRL + Qt::Key_B, 0); currentResult = SentKeyEvent; }
 
 public slots:
     void initTestCase();
@@ -981,6 +984,19 @@ void tst_QShortcut::keypressConsumption()
     QVERIFY(edit->toPlainText().endsWith("<Ctrl+I>a"));
 
     clearAllShortcuts();
+    edit->clear();
+    QCOMPARE(edit->toPlainText().size(), 0);
+
+    setupShortcut(edit, "first", SendKeyEvent, "Ctrl+A");
+
+    // Verify reentrancy when a non-shortcut is triggered as part
+    // of shortcut processing.
+    currentResult = NoResult;
+    ambigResult = NoResult;
+    sendKeyEvents(edit, Qt::CTRL + Qt::Key_A, 0);
+    QCOMPARE(currentResult, SentKeyEvent);
+    QCOMPARE(ambigResult, NoResult);
+    QCOMPARE(edit->toPlainText(), QString(QString("<Ctrl+B>")));
 }
 
 // ------------------------------------------------------------------
@@ -1182,9 +1198,12 @@ QShortcut *tst_QShortcut::setupShortcut(QWidget *parent, const char *name, int t
         normal = SLOT(slotTrig7());
         ambig  = SLOT(ambigSlot7());
         break;
+    case SendKeyEvent:
+        normal = SLOT(sendKeyEvent());
     }
     connect(cut, SIGNAL(activated()), this, normal);
-    connect(cut, SIGNAL(activatedAmbiguously()), this, ambig);
+    if (ambig)
+        connect(cut, SIGNAL(activatedAmbiguously()), this, ambig);
     connect(cut, SIGNAL(destroyed(QObject*)), this, SLOT(shortcutDestroyed(QObject*)));
     shortcuts.append(cut);
     return cut;
diff --git a/tests/auto/widgets/util/qundogroup/tst_qundogroup.cpp b/tests/auto/widgets/util/qundogroup/tst_qundogroup.cpp
index 781adeedada76bcfebe1df50e66928094f100d53..9f03e9b3a0473ff59a3c66efc180b63f32baf195 100644
--- a/tests/auto/widgets/util/qundogroup/tst_qundogroup.cpp
+++ b/tests/auto/widgets/util/qundogroup/tst_qundogroup.cpp
@@ -36,7 +36,22 @@
 #include <QAction>
 
 // Temporarily disabling IRIX due to build issuues with GCC
-#if !defined(__sgi) || defined(__sgi) && !defined(__GNUC__)
+#if defined(__sgi) && defined(__GNUC__)
+
+class tst_QUndoGroup : public QObject
+{
+    Q_OBJECT
+public:
+    tst_QUndoGroup() {}
+
+private slots:
+    void setActive() { QSKIP( "Not tested on irix-g++"); }
+    void addRemoveStack() { QSKIP( "Not tested on irix-g++"); }
+    void deleteStack() { QSKIP( "Not tested on irix-g++"); }
+    void checkSignals() { QSKIP( "Not tested on irix-g++"); }
+    void addStackAndDie() { QSKIP( "Not tested on irix-g++"); }
+};
+#else
 
 /******************************************************************************
 ** Commands
@@ -645,22 +660,7 @@ void tst_QUndoGroup::commandTextFormat()
     qApp->removeTranslator(&translator);
 #endif
 }
-
-#else
-class tst_QUndoGroup : public QObject
-{
-    Q_OBJECT
-public:
-    tst_QUndoGroup() {}
-
-private slots:
-    void setActive() { QSKIP( "Not tested on irix-g++"); }
-    void addRemoveStack() { QSKIP( "Not tested on irix-g++"); }
-    void deleteStack() { QSKIP( "Not tested on irix-g++"); }
-    void checkSignals() { QSKIP( "Not tested on irix-g++"); }
-    void addStackAndDie() { QSKIP( "Not tested on irix-g++"); }
-};
-#endif
+#endif // !(SGI && GCC)
 
 QTEST_MAIN(tst_QUndoGroup)
 
diff --git a/tests/auto/widgets/widgets/qlineedit/qlineedit.pro b/tests/auto/widgets/widgets/qlineedit/qlineedit.pro
index 715dcb955052e21337e069c373b6623ad70256ad..636208d67a5155357f8d85bd09246b6c2474bc80 100644
--- a/tests/auto/widgets/widgets/qlineedit/qlineedit.pro
+++ b/tests/auto/widgets/widgets/qlineedit/qlineedit.pro
@@ -3,3 +3,4 @@ TARGET = tst_qlineedit
 QT += gui-private core-private widgets widgets-private testlib
 SOURCES  += tst_qlineedit.cpp
 
+osx: LIBS += -framework AppKit
diff --git a/tests/auto/widgets/widgets/qplaintextedit/qplaintextedit.pro b/tests/auto/widgets/widgets/qplaintextedit/qplaintextedit.pro
index e98bae2089eddc976ac044c83ed1fbfa5abd9c68..be4102ec75f9b505382f3f66fb42c74110b3e34d 100644
--- a/tests/auto/widgets/widgets/qplaintextedit/qplaintextedit.pro
+++ b/tests/auto/widgets/widgets/qplaintextedit/qplaintextedit.pro
@@ -9,3 +9,4 @@ INCLUDEPATH += ../
 HEADERS +=  
 SOURCES += tst_qplaintextedit.cpp 
 
+osx: LIBS += -framework AppKit
diff --git a/tests/auto/widgets/widgets/qtextedit/qtextedit.pro b/tests/auto/widgets/widgets/qtextedit/qtextedit.pro
index 6e0fff17d5bad473bc16631e093d2c99ca97c407..8b39ab59b78f1720b0670b7339822eb4fdbd5354 100644
--- a/tests/auto/widgets/widgets/qtextedit/qtextedit.pro
+++ b/tests/auto/widgets/widgets/qtextedit/qtextedit.pro
@@ -4,3 +4,5 @@ TARGET = tst_qtextedit
 QT += widgets widgets-private gui-private core-private testlib
 
 SOURCES += tst_qtextedit.cpp
+
+osx: LIBS += -framework AppKit
diff --git a/tests/manual/diaglib/nativewindowdump_win.cpp b/tests/manual/diaglib/nativewindowdump_win.cpp
index e3885eb96d3bcac490048e8bf53ec4c4e5aff8f6..b25f8aa8645faddbeabf57dca396b01968419f90 100644
--- a/tests/manual/diaglib/nativewindowdump_win.cpp
+++ b/tests/manual/diaglib/nativewindowdump_win.cpp
@@ -48,9 +48,10 @@
 namespace QtDiag {
 
 struct DumpContext {
-    DumpContext() : indentation(0) {}
+    DumpContext() : indentation(0), parent(0) {}
 
     int indentation;
+    HWND parent;
     QSharedPointer<QTextStream> stream;
 };
 
@@ -64,11 +65,19 @@ static void formatNativeWindow(HWND hwnd, QTextStream &str)
     RECT rect;
     if (GetWindowRect(hwnd, &rect)) {
         str << ' ' << (rect.right - rect.left) << 'x' << (rect.bottom - rect.top)
-            << '+' << rect.left << '+' << rect.top;
+            << forcesign << rect.left << rect.top << noforcesign;
     }
     if (IsWindowVisible(hwnd))
         str << " [visible]";
 
+    wchar_t buf[512];
+    if (GetWindowText(hwnd, buf, sizeof(buf)/sizeof(buf[0])) && buf[0])
+        str << " title=\"" << QString::fromWCharArray(buf) << "\"/";
+    else
+        str << ' ';
+    if (GetClassName(hwnd, buf, sizeof(buf)/sizeof(buf[0])))
+        str << '"' << QString::fromWCharArray(buf) << '"';
+
     str << hex << showbase;
     if (const LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE)) {
         str << " style=" << style;
@@ -121,13 +130,31 @@ static void formatNativeWindow(HWND hwnd, QTextStream &str)
         debugWinStyle(str, exStyle, WS_EX_COMPOSITED)
         debugWinStyle(str, exStyle, WS_EX_NOACTIVATE)
     }
+
+    if (const ULONG_PTR classStyle = GetClassLongPtr(hwnd, GCL_STYLE)) {
+        str << " classStyle=" << classStyle;
+        debugWinStyle(str, classStyle, CS_BYTEALIGNCLIENT)
+        debugWinStyle(str, classStyle, CS_BYTEALIGNWINDOW)
+        debugWinStyle(str, classStyle, CS_CLASSDC)
+        debugWinStyle(str, classStyle, CS_DBLCLKS)
+        debugWinStyle(str, classStyle, CS_DROPSHADOW)
+        debugWinStyle(str, classStyle, CS_GLOBALCLASS)
+        debugWinStyle(str, classStyle, CS_HREDRAW)
+        debugWinStyle(str, classStyle, CS_NOCLOSE)
+        debugWinStyle(str, classStyle, CS_OWNDC)
+        debugWinStyle(str, classStyle, CS_PARENTDC)
+        debugWinStyle(str, classStyle, CS_SAVEBITS)
+        debugWinStyle(str, classStyle, CS_VREDRAW)
+    }
+
+    if (const ULONG_PTR wndProc = GetClassLongPtr(hwnd, GCLP_WNDPROC))
+        str << " wndProc=" << wndProc;
+
     str << noshowbase << dec;
 
-    wchar_t buf[512];
-    if (GetWindowText(hwnd, buf, sizeof(buf)/sizeof(buf[0])))
-        str << " title=\"" << QString::fromWCharArray(buf) << '"';
-    if (GetClassName(hwnd, buf, sizeof(buf)/sizeof(buf[0])))
-        str << " class=\"" << QString::fromWCharArray(buf) << '"';
+    if (GetWindowModuleFileName(hwnd, buf, sizeof(buf)/sizeof(buf[0])))
+        str << " module=\"" << QString::fromWCharArray(buf) << '"';
+
     str << '\n';
 }
 
@@ -135,7 +162,11 @@ static void dumpNativeWindowRecursion(HWND hwnd, DumpContext *dc);
 
 BOOL CALLBACK dumpWindowEnumChildProc(HWND hwnd, LPARAM lParam)
 {
-    dumpNativeWindowRecursion(hwnd, reinterpret_cast<DumpContext *>(lParam));
+    DumpContext *dumpContext = reinterpret_cast<DumpContext *>(lParam);
+    // EnumChildWindows enumerates grand children as well, skip these to
+    // get the hierarchical formatting right.
+    if (GetAncestor(hwnd, GA_PARENT) == dumpContext->parent)
+        dumpNativeWindowRecursion(hwnd, dumpContext);
     return TRUE;
 }
 
@@ -145,6 +176,7 @@ static void dumpNativeWindowRecursion(HWND hwnd, DumpContext *dc)
     formatNativeWindow(hwnd, *dc->stream);
     DumpContext nextLevel = *dc;
     nextLevel.indentation += 2;
+    nextLevel.parent = hwnd;
     EnumChildWindows(hwnd, dumpWindowEnumChildProc, reinterpret_cast<LPARAM>(&nextLevel));
 }
 
diff --git a/tests/manual/diaglib/qwindowdump.cpp b/tests/manual/diaglib/qwindowdump.cpp
index a77bae22e986a70469471dfaf552b92a650bfe07..c0faefb9188f86b5eaac0ac677c47c0d120c3da9 100644
--- a/tests/manual/diaglib/qwindowdump.cpp
+++ b/tests/manual/diaglib/qwindowdump.cpp
@@ -38,6 +38,9 @@
 #  include <QtGui/QScreen>
 #  include <QtGui/QWindow>
 #  include <qpa/qplatformwindow.h>
+#  if QT_VERSION >= 0x050600
+#    include <private/qhighdpiscaling_p.h>
+#  endif
 #endif
 #include <QtCore/QMetaObject>
 #include <QtCore/QRect>
@@ -131,9 +134,19 @@ void formatWindow(QTextStream &str, const QWindow *w, FormatWindowOptions option
         str << "[top] ";
     if (w->isExposed())
         str << "[exposed] ";
+    if (w->surfaceClass() == QWindow::Offscreen)
+        str << "[offscreen] ";
+    str << "surface=" << w->surfaceType() << ' ';
     if (const Qt::WindowState state = w->windowState())
         str << "windowState=" << state << ' ';
     formatRect(str, w->geometry());
+    if (w->isTopLevel()) {
+        str << " \"" << w->screen()->name() << "\" ";
+#if QT_VERSION >= 0x050600
+        if (QHighDpiScaling::isActive())
+            str << "factor=" << QHighDpiScaling::factor(w) << ' ';
+#endif
+    }
     if (!(options & DontPrintWindowFlags)) {
         str << ' ';
         formatWindowFlags(str, w->flags());